laya.d3.js 1.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771
  1. (function (exports, Laya) {
  2. 'use strict';
  3. class MathUtils3D {
  4. constructor() {
  5. }
  6. static isZero(v) {
  7. return Math.abs(v) < MathUtils3D.zeroTolerance;
  8. }
  9. static nearEqual(n1, n2) {
  10. if (MathUtils3D.isZero(n1 - n2))
  11. return true;
  12. return false;
  13. }
  14. static fastInvSqrt(value) {
  15. if (MathUtils3D.isZero(value))
  16. return value;
  17. return 1.0 / Math.sqrt(value);
  18. }
  19. }
  20. MathUtils3D.zeroTolerance = 1e-6;
  21. MathUtils3D.MaxValue = 3.40282347e+38;
  22. MathUtils3D.MinValue = -3.40282347e+38;
  23. class Vector2 {
  24. constructor(x = 0, y = 0) {
  25. this.x = x;
  26. this.y = y;
  27. }
  28. setValue(x, y) {
  29. this.x = x;
  30. this.y = y;
  31. }
  32. static scale(a, b, out) {
  33. out.x = a.x * b;
  34. out.y = a.y * b;
  35. }
  36. fromArray(array, offset = 0) {
  37. this.x = array[offset + 0];
  38. this.y = array[offset + 1];
  39. }
  40. cloneTo(destObject) {
  41. var destVector2 = destObject;
  42. destVector2.x = this.x;
  43. destVector2.y = this.y;
  44. }
  45. static dot(a, b) {
  46. return (a.x * b.x) + (a.y * b.y);
  47. }
  48. static normalize(s, out) {
  49. var x = s.x, y = s.y;
  50. var len = x * x + y * y;
  51. if (len > 0) {
  52. len = 1 / Math.sqrt(len);
  53. out.x = x * len;
  54. out.y = y * len;
  55. }
  56. }
  57. static scalarLength(a) {
  58. var x = a.x, y = a.y;
  59. return Math.sqrt(x * x + y * y);
  60. }
  61. clone() {
  62. var destVector2 = new Vector2();
  63. this.cloneTo(destVector2);
  64. return destVector2;
  65. }
  66. forNativeElement(nativeElements = null) {
  67. if (nativeElements) {
  68. this.elements = nativeElements;
  69. this.elements[0] = this.x;
  70. this.elements[1] = this.y;
  71. }
  72. else {
  73. this.elements = new Float32Array([this.x, this.y]);
  74. }
  75. Vector2.rewriteNumProperty(this, "x", 0);
  76. Vector2.rewriteNumProperty(this, "y", 1);
  77. }
  78. static rewriteNumProperty(proto, name, index) {
  79. Object["defineProperty"](proto, name, {
  80. "get": function () {
  81. return this.elements[index];
  82. },
  83. "set": function (v) {
  84. this.elements[index] = v;
  85. }
  86. });
  87. }
  88. }
  89. Vector2.ZERO = new Vector2(0.0, 0.0);
  90. Vector2.ONE = new Vector2(1.0, 1.0);
  91. class Vector4 {
  92. constructor(x = 0, y = 0, z = 0, w = 0) {
  93. this.x = x;
  94. this.y = y;
  95. this.z = z;
  96. this.w = w;
  97. }
  98. setValue(x, y, z, w) {
  99. this.x = x;
  100. this.y = y;
  101. this.z = z;
  102. this.w = w;
  103. }
  104. fromArray(array, offset = 0) {
  105. this.x = array[offset + 0];
  106. this.y = array[offset + 1];
  107. this.z = array[offset + 2];
  108. this.w = array[offset + 3];
  109. }
  110. cloneTo(destObject) {
  111. var destVector4 = destObject;
  112. destVector4.x = this.x;
  113. destVector4.y = this.y;
  114. destVector4.z = this.z;
  115. destVector4.w = this.w;
  116. }
  117. clone() {
  118. var destVector4 = new Vector4();
  119. this.cloneTo(destVector4);
  120. return destVector4;
  121. }
  122. static lerp(a, b, t, out) {
  123. var ax = a.x, ay = a.y, az = a.z, aw = a.w;
  124. out.x = ax + t * (b.x - ax);
  125. out.y = ay + t * (b.y - ay);
  126. out.z = az + t * (b.z - az);
  127. out.w = aw + t * (b.w - aw);
  128. }
  129. static transformByM4x4(vector4, m4x4, out) {
  130. var vx = vector4.x;
  131. var vy = vector4.y;
  132. var vz = vector4.z;
  133. var vw = vector4.w;
  134. var me = m4x4.elements;
  135. out.x = vx * me[0] + vy * me[4] + vz * me[8] + vw * me[12];
  136. out.y = vx * me[1] + vy * me[5] + vz * me[9] + vw * me[13];
  137. out.z = vx * me[2] + vy * me[6] + vz * me[10] + vw * me[14];
  138. out.w = vx * me[3] + vy * me[7] + vz * me[11] + vw * me[15];
  139. }
  140. static equals(a, b) {
  141. return MathUtils3D.nearEqual(Math.abs(a.x), Math.abs(b.x)) && MathUtils3D.nearEqual(Math.abs(a.y), Math.abs(b.y)) && MathUtils3D.nearEqual(Math.abs(a.z), Math.abs(b.z)) && MathUtils3D.nearEqual(Math.abs(a.w), Math.abs(b.w));
  142. }
  143. length() {
  144. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  145. }
  146. lengthSquared() {
  147. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  148. }
  149. static normalize(s, out) {
  150. var len = s.length();
  151. if (len > 0) {
  152. var inverse = 1.0 / len;
  153. out.x = s.x * inverse;
  154. out.y = s.y * inverse;
  155. out.z = s.z * inverse;
  156. out.w = s.w * inverse;
  157. }
  158. }
  159. static add(a, b, out) {
  160. out.x = a.x + b.x;
  161. out.y = a.y + b.y;
  162. out.z = a.z + b.z;
  163. out.w = a.w + b.w;
  164. }
  165. static subtract(a, b, out) {
  166. out.x = a.x - b.x;
  167. out.y = a.y - b.y;
  168. out.z = a.z - b.z;
  169. out.w = a.w - b.w;
  170. }
  171. static multiply(a, b, out) {
  172. out.x = a.x * b.x;
  173. out.y = a.y * b.y;
  174. out.z = a.z * b.z;
  175. out.w = a.w * b.w;
  176. }
  177. static scale(a, b, out) {
  178. out.x = a.x * b;
  179. out.y = a.y * b;
  180. out.z = a.z * b;
  181. out.w = a.w * b;
  182. }
  183. static Clamp(value, min, max, out) {
  184. var x = value.x;
  185. var y = value.y;
  186. var z = value.z;
  187. var w = value.w;
  188. var mineX = min.x;
  189. var mineY = min.y;
  190. var mineZ = min.z;
  191. var mineW = min.w;
  192. var maxeX = max.x;
  193. var maxeY = max.y;
  194. var maxeZ = max.z;
  195. var maxeW = max.w;
  196. x = (x > maxeX) ? maxeX : x;
  197. x = (x < mineX) ? mineX : x;
  198. y = (y > maxeY) ? maxeY : y;
  199. y = (y < mineY) ? mineY : y;
  200. z = (z > maxeZ) ? maxeZ : z;
  201. z = (z < mineZ) ? mineZ : z;
  202. w = (w > maxeW) ? maxeW : w;
  203. w = (w < mineW) ? mineW : w;
  204. out.x = x;
  205. out.y = y;
  206. out.z = z;
  207. out.w = w;
  208. }
  209. static distanceSquared(value1, value2) {
  210. var x = value1.x - value2.x;
  211. var y = value1.y - value2.y;
  212. var z = value1.z - value2.z;
  213. var w = value1.w - value2.w;
  214. return (x * x) + (y * y) + (z * z) + (w * w);
  215. }
  216. static distance(value1, value2) {
  217. var x = value1.x - value2.x;
  218. var y = value1.y - value2.y;
  219. var z = value1.z - value2.z;
  220. var w = value1.w - value2.w;
  221. return Math.sqrt((x * x) + (y * y) + (z * z) + (w * w));
  222. }
  223. static dot(a, b) {
  224. return (a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.w * b.w);
  225. }
  226. static min(a, b, out) {
  227. out.x = Math.min(a.x, b.x);
  228. out.y = Math.min(a.y, b.y);
  229. out.z = Math.min(a.z, b.z);
  230. out.w = Math.min(a.w, b.w);
  231. }
  232. static max(a, b, out) {
  233. out.x = Math.max(a.x, b.x);
  234. out.y = Math.max(a.y, b.y);
  235. out.z = Math.max(a.z, b.z);
  236. out.w = Math.max(a.w, b.w);
  237. }
  238. forNativeElement(nativeElements = null) {
  239. if (nativeElements) {
  240. this.elements = nativeElements;
  241. this.elements[0] = this.x;
  242. this.elements[1] = this.y;
  243. this.elements[2] = this.z;
  244. this.elements[3] = this.w;
  245. }
  246. else {
  247. this.elements = new Float32Array([this.x, this.y, this.z, this.w]);
  248. }
  249. Vector2.rewriteNumProperty(this, "x", 0);
  250. Vector2.rewriteNumProperty(this, "y", 1);
  251. Vector2.rewriteNumProperty(this, "z", 2);
  252. Vector2.rewriteNumProperty(this, "w", 3);
  253. }
  254. }
  255. Vector4.ZERO = new Vector4();
  256. Vector4.ONE = new Vector4(1.0, 1.0, 1.0, 1.0);
  257. Vector4.UnitX = new Vector4(1.0, 0.0, 0.0, 0.0);
  258. Vector4.UnitY = new Vector4(0.0, 1.0, 0.0, 0.0);
  259. Vector4.UnitZ = new Vector4(0.0, 0.0, 1.0, 0.0);
  260. Vector4.UnitW = new Vector4(0.0, 0.0, 0.0, 1.0);
  261. class Vector3 {
  262. constructor(x = 0, y = 0, z = 0, nativeElements = null) {
  263. this.x = x;
  264. this.y = y;
  265. this.z = z;
  266. }
  267. static distanceSquared(value1, value2) {
  268. var x = value1.x - value2.x;
  269. var y = value1.y - value2.y;
  270. var z = value1.z - value2.z;
  271. return (x * x) + (y * y) + (z * z);
  272. }
  273. static distance(value1, value2) {
  274. var x = value1.x - value2.x;
  275. var y = value1.y - value2.y;
  276. var z = value1.z - value2.z;
  277. return Math.sqrt((x * x) + (y * y) + (z * z));
  278. }
  279. static min(a, b, out) {
  280. out.x = Math.min(a.x, b.x);
  281. out.y = Math.min(a.y, b.y);
  282. out.z = Math.min(a.z, b.z);
  283. }
  284. static max(a, b, out) {
  285. out.x = Math.max(a.x, b.x);
  286. out.y = Math.max(a.y, b.y);
  287. out.z = Math.max(a.z, b.z);
  288. }
  289. static transformQuat(source, rotation, out) {
  290. var x = source.x, y = source.y, z = source.z, qx = rotation.x, qy = rotation.y, qz = rotation.z, qw = rotation.w, ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  291. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  292. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  293. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  294. }
  295. static scalarLength(a) {
  296. var x = a.x, y = a.y, z = a.z;
  297. return Math.sqrt(x * x + y * y + z * z);
  298. }
  299. static scalarLengthSquared(a) {
  300. var x = a.x, y = a.y, z = a.z;
  301. return x * x + y * y + z * z;
  302. }
  303. static normalize(s, out) {
  304. var x = s.x, y = s.y, z = s.z;
  305. var len = x * x + y * y + z * z;
  306. if (len > 0) {
  307. len = 1 / Math.sqrt(len);
  308. out.x = x * len;
  309. out.y = y * len;
  310. out.z = z * len;
  311. }
  312. }
  313. static multiply(a, b, out) {
  314. out.x = a.x * b.x;
  315. out.y = a.y * b.y;
  316. out.z = a.z * b.z;
  317. }
  318. static scale(a, b, out) {
  319. out.x = a.x * b;
  320. out.y = a.y * b;
  321. out.z = a.z * b;
  322. }
  323. static lerp(a, b, t, out) {
  324. var ax = a.x, ay = a.y, az = a.z;
  325. out.x = ax + t * (b.x - ax);
  326. out.y = ay + t * (b.y - ay);
  327. out.z = az + t * (b.z - az);
  328. }
  329. static transformV3ToV3(vector, transform, result) {
  330. var intermediate = Vector3._tempVector4;
  331. Vector3.transformV3ToV4(vector, transform, intermediate);
  332. result.x = intermediate.x;
  333. result.y = intermediate.y;
  334. result.z = intermediate.z;
  335. }
  336. static transformV3ToV4(vector, transform, result) {
  337. var vectorX = vector.x;
  338. var vectorY = vector.y;
  339. var vectorZ = vector.z;
  340. var transformElem = transform.elements;
  341. result.x = (vectorX * transformElem[0]) + (vectorY * transformElem[4]) + (vectorZ * transformElem[8]) + transformElem[12];
  342. result.y = (vectorX * transformElem[1]) + (vectorY * transformElem[5]) + (vectorZ * transformElem[9]) + transformElem[13];
  343. result.z = (vectorX * transformElem[2]) + (vectorY * transformElem[6]) + (vectorZ * transformElem[10]) + transformElem[14];
  344. result.w = (vectorX * transformElem[3]) + (vectorY * transformElem[7]) + (vectorZ * transformElem[11]) + transformElem[15];
  345. }
  346. static TransformNormal(normal, transform, result) {
  347. var normalX = normal.x;
  348. var normalY = normal.y;
  349. var normalZ = normal.z;
  350. var transformElem = transform.elements;
  351. result.x = (normalX * transformElem[0]) + (normalY * transformElem[4]) + (normalZ * transformElem[8]);
  352. result.y = (normalX * transformElem[1]) + (normalY * transformElem[5]) + (normalZ * transformElem[9]);
  353. result.z = (normalX * transformElem[2]) + (normalY * transformElem[6]) + (normalZ * transformElem[10]);
  354. }
  355. static transformCoordinate(coordinate, transform, result) {
  356. var coordinateX = coordinate.x;
  357. var coordinateY = coordinate.y;
  358. var coordinateZ = coordinate.z;
  359. var transformElem = transform.elements;
  360. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  361. result.x = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  362. result.y = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  363. result.z = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  364. }
  365. static Clamp(value, min, max, out) {
  366. var x = value.x;
  367. var y = value.y;
  368. var z = value.z;
  369. var mineX = min.x;
  370. var mineY = min.y;
  371. var mineZ = min.z;
  372. var maxeX = max.x;
  373. var maxeY = max.y;
  374. var maxeZ = max.z;
  375. x = (x > maxeX) ? maxeX : x;
  376. x = (x < mineX) ? mineX : x;
  377. y = (y > maxeY) ? maxeY : y;
  378. y = (y < mineY) ? mineY : y;
  379. z = (z > maxeZ) ? maxeZ : z;
  380. z = (z < mineZ) ? mineZ : z;
  381. out.x = x;
  382. out.y = y;
  383. out.z = z;
  384. }
  385. static add(a, b, out) {
  386. out.x = a.x + b.x;
  387. out.y = a.y + b.y;
  388. out.z = a.z + b.z;
  389. }
  390. static subtract(a, b, o) {
  391. o.x = a.x - b.x;
  392. o.y = a.y - b.y;
  393. o.z = a.z - b.z;
  394. }
  395. static cross(a, b, o) {
  396. var ax = a.x, ay = a.y, az = a.z, bx = b.x, by = b.y, bz = b.z;
  397. o.x = ay * bz - az * by;
  398. o.y = az * bx - ax * bz;
  399. o.z = ax * by - ay * bx;
  400. }
  401. static dot(a, b) {
  402. return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
  403. }
  404. static equals(a, b) {
  405. return MathUtils3D.nearEqual(a.x, b.x) && MathUtils3D.nearEqual(a.y, b.y) && MathUtils3D.nearEqual(a.z, b.z);
  406. }
  407. setValue(x, y, z) {
  408. this.x = x;
  409. this.y = y;
  410. this.z = z;
  411. }
  412. fromArray(array, offset = 0) {
  413. this.x = array[offset + 0];
  414. this.y = array[offset + 1];
  415. this.z = array[offset + 2];
  416. }
  417. cloneTo(destObject) {
  418. var destVector3 = destObject;
  419. destVector3.x = this.x;
  420. destVector3.y = this.y;
  421. destVector3.z = this.z;
  422. }
  423. clone() {
  424. var destVector3 = new Vector3();
  425. this.cloneTo(destVector3);
  426. return destVector3;
  427. }
  428. toDefault() {
  429. this.x = 0;
  430. this.y = 0;
  431. this.z = 0;
  432. }
  433. forNativeElement(nativeElements = null) {
  434. if (nativeElements) {
  435. this.elements = nativeElements;
  436. this.elements[0] = this.x;
  437. this.elements[1] = this.y;
  438. this.elements[2] = this.z;
  439. }
  440. else {
  441. this.elements = new Float32Array([this.x, this.y, this.z]);
  442. }
  443. Vector2.rewriteNumProperty(this, "x", 0);
  444. Vector2.rewriteNumProperty(this, "y", 1);
  445. Vector2.rewriteNumProperty(this, "z", 2);
  446. }
  447. }
  448. Vector3._tempVector4 = new Vector4();
  449. Vector3._ZERO = new Vector3(0.0, 0.0, 0.0);
  450. Vector3._ONE = new Vector3(1.0, 1.0, 1.0);
  451. Vector3._NegativeUnitX = new Vector3(-1, 0, 0);
  452. Vector3._UnitX = new Vector3(1, 0, 0);
  453. Vector3._UnitY = new Vector3(0, 1, 0);
  454. Vector3._UnitZ = new Vector3(0, 0, 1);
  455. Vector3._ForwardRH = new Vector3(0, 0, -1);
  456. Vector3._ForwardLH = new Vector3(0, 0, 1);
  457. Vector3._Up = new Vector3(0, 1, 0);
  458. class Config3D {
  459. constructor() {
  460. this._defaultPhysicsMemory = 16;
  461. this._maxLightCount = 32;
  462. this._lightClusterCount = new Vector3(12, 12, 12);
  463. this._editerEnvironment = false;
  464. this.isAntialias = true;
  465. this.isAlpha = false;
  466. this.premultipliedAlpha = true;
  467. this.isStencil = true;
  468. this.enableMultiLight = true;
  469. this.octreeCulling = false;
  470. this.octreeInitialSize = 64.0;
  471. this.octreeInitialCenter = new Vector3(0, 0, 0);
  472. this.octreeMinNodeSize = 2.0;
  473. this.octreeLooseness = 1.25;
  474. this.debugFrustumCulling = false;
  475. this._maxAreaLightCountPerClusterAverage = Math.min(Math.floor(2048 / this._lightClusterCount.z - 1) * 4, this._maxLightCount);
  476. }
  477. get defaultPhysicsMemory() {
  478. return this._defaultPhysicsMemory;
  479. }
  480. set defaultPhysicsMemory(value) {
  481. if (value < 16)
  482. throw "defaultPhysicsMemory must large than 16M";
  483. this._defaultPhysicsMemory = value;
  484. }
  485. get maxLightCount() {
  486. return this._maxLightCount;
  487. }
  488. set maxLightCount(value) {
  489. if (value > 2048) {
  490. this._maxLightCount = 2048;
  491. console.warn("Config3D: maxLightCount must less equal 2048.");
  492. }
  493. else {
  494. this._maxLightCount = value;
  495. }
  496. }
  497. get lightClusterCount() {
  498. return this._lightClusterCount;
  499. }
  500. set lightClusterCount(value) {
  501. if (value.x > 128 || value.y > 128 || value.z > 128) {
  502. this._lightClusterCount.setValue(Math.min(value.x, 128), Math.min(value.y, 128), Math.min(value.z, 128));
  503. console.warn("Config3D: lightClusterCount X and Y、Z must less equal 128.");
  504. }
  505. else {
  506. value.cloneTo(this._lightClusterCount);
  507. }
  508. var maxAreaLightCountWithZ = Math.floor(2048 / this._lightClusterCount.z - 1) * 4;
  509. if (maxAreaLightCountWithZ < this._maxLightCount)
  510. console.warn("Config3D: if the area light(PointLight、SpotLight) count is large than " + maxAreaLightCountWithZ + ",maybe the far away culster will ingonre some light.");
  511. this._maxAreaLightCountPerClusterAverage = Math.min(maxAreaLightCountWithZ, this._maxLightCount);
  512. }
  513. cloneTo(dest) {
  514. var destConfig3D = dest;
  515. destConfig3D._defaultPhysicsMemory = this._defaultPhysicsMemory;
  516. destConfig3D._editerEnvironment = this._editerEnvironment;
  517. destConfig3D.isAntialias = this.isAntialias;
  518. destConfig3D.isAlpha = this.isAlpha;
  519. destConfig3D.premultipliedAlpha = this.premultipliedAlpha;
  520. destConfig3D.isStencil = this.isStencil;
  521. destConfig3D.octreeCulling = this.octreeCulling;
  522. this.octreeInitialCenter.cloneTo(destConfig3D.octreeInitialCenter);
  523. destConfig3D.octreeInitialSize = this.octreeInitialSize;
  524. destConfig3D.octreeMinNodeSize = this.octreeMinNodeSize;
  525. destConfig3D.octreeLooseness = this.octreeLooseness;
  526. destConfig3D.debugFrustumCulling = this.debugFrustumCulling;
  527. destConfig3D.maxLightCount = this.maxLightCount;
  528. destConfig3D.enableMultiLight = this.enableMultiLight;
  529. var lightClusterCount = destConfig3D.lightClusterCount;
  530. this.lightClusterCount.cloneTo(lightClusterCount);
  531. destConfig3D.lightClusterCount = lightClusterCount;
  532. }
  533. clone() {
  534. var dest = new Config3D();
  535. this.cloneTo(dest);
  536. return dest;
  537. }
  538. }
  539. Config3D._config = new Config3D();
  540. window.Config3D = Config3D;
  541. class ILaya3D {
  542. }
  543. ILaya3D.Shader3D = null;
  544. ILaya3D.Scene3D = null;
  545. ILaya3D.MeshRenderStaticBatchManager = null;
  546. ILaya3D.MeshRenderDynamicBatchManager = null;
  547. ILaya3D.SubMeshDynamicBatch = null;
  548. ILaya3D.Laya3D = null;
  549. ILaya3D.Matrix4x4 = null;
  550. class KeyframeNode {
  551. constructor() {
  552. this._ownerPath = [];
  553. this._propertys = [];
  554. this._keyFrames = [];
  555. }
  556. get ownerPathCount() {
  557. return this._ownerPath.length;
  558. }
  559. get propertyCount() {
  560. return this._propertys.length;
  561. }
  562. get keyFramesCount() {
  563. return this._keyFrames.length;
  564. }
  565. _setOwnerPathCount(value) {
  566. this._ownerPath.length = value;
  567. }
  568. _setOwnerPathByIndex(index, value) {
  569. this._ownerPath[index] = value;
  570. }
  571. _joinOwnerPath(sep) {
  572. return this._ownerPath.join(sep);
  573. }
  574. _setPropertyCount(value) {
  575. this._propertys.length = value;
  576. }
  577. _setPropertyByIndex(index, value) {
  578. this._propertys[index] = value;
  579. }
  580. _joinProperty(sep) {
  581. return this._propertys.join(sep);
  582. }
  583. _setKeyframeCount(value) {
  584. this._keyFrames.length = value;
  585. }
  586. _setKeyframeByIndex(index, value) {
  587. this._keyFrames[index] = value;
  588. }
  589. getOwnerPathByIndex(index) {
  590. return this._ownerPath[index];
  591. }
  592. getPropertyByIndex(index) {
  593. return this._propertys[index];
  594. }
  595. getKeyframeByIndex(index) {
  596. return this._keyFrames[index];
  597. }
  598. }
  599. class AnimationEvent {
  600. constructor() {
  601. }
  602. }
  603. class Keyframe {
  604. constructor() {
  605. }
  606. cloneTo(destObject) {
  607. var destKeyFrame = destObject;
  608. destKeyFrame.time = this.time;
  609. }
  610. clone() {
  611. var dest = new Keyframe();
  612. this.cloneTo(dest);
  613. return dest;
  614. }
  615. }
  616. class FloatKeyframe extends Keyframe {
  617. constructor() {
  618. super();
  619. }
  620. cloneTo(destObject) {
  621. super.cloneTo(destObject);
  622. var destKeyFrame = destObject;
  623. destKeyFrame.inTangent = this.inTangent;
  624. destKeyFrame.outTangent = this.outTangent;
  625. destKeyFrame.value = this.value;
  626. }
  627. }
  628. class Matrix3x3 {
  629. constructor() {
  630. var e = this.elements = new Float32Array(9);
  631. e[0] = 1;
  632. e[1] = 0;
  633. e[2] = 0;
  634. e[3] = 0;
  635. e[4] = 1;
  636. e[5] = 0;
  637. e[6] = 0;
  638. e[7] = 0;
  639. e[8] = 1;
  640. }
  641. static createRotationQuaternion(rotation, out) {
  642. var rotX = rotation.x;
  643. var rotY = rotation.y;
  644. var rotZ = rotation.z;
  645. var rotW = rotation.w;
  646. var xx = rotX * rotX;
  647. var yy = rotY * rotY;
  648. var zz = rotZ * rotZ;
  649. var xy = rotX * rotY;
  650. var zw = rotZ * rotW;
  651. var zx = rotZ * rotX;
  652. var yw = rotY * rotW;
  653. var yz = rotY * rotZ;
  654. var xw = rotX * rotW;
  655. var resultE = out.elements;
  656. resultE[0] = 1.0 - (2.0 * (yy + zz));
  657. resultE[1] = 2.0 * (xy + zw);
  658. resultE[2] = 2.0 * (zx - yw);
  659. resultE[3] = 2.0 * (xy - zw);
  660. resultE[4] = 1.0 - (2.0 * (zz + xx));
  661. resultE[5] = 2.0 * (yz + xw);
  662. resultE[6] = 2.0 * (zx + yw);
  663. resultE[7] = 2.0 * (yz - xw);
  664. resultE[8] = 1.0 - (2.0 * (yy + xx));
  665. }
  666. static createFromTranslation(trans, out) {
  667. var e = out.elements;
  668. e[0] = 1;
  669. e[1] = 0;
  670. e[2] = 0;
  671. e[3] = 0;
  672. e[4] = 1;
  673. e[5] = 0;
  674. e[6] = trans.x;
  675. e[7] = trans.y;
  676. e[8] = 1;
  677. }
  678. static createFromRotation(rad, out) {
  679. var e = out.elements;
  680. var s = Math.sin(rad), c = Math.cos(rad);
  681. e[0] = c;
  682. e[1] = s;
  683. e[2] = 0;
  684. e[3] = -s;
  685. e[4] = c;
  686. e[5] = 0;
  687. e[6] = 0;
  688. e[7] = 0;
  689. e[8] = 1;
  690. }
  691. static createFromScaling(scale, out) {
  692. var e = out.elements;
  693. e[0] = scale.x;
  694. e[1] = 0;
  695. e[2] = 0;
  696. e[3] = 0;
  697. e[4] = scale.y;
  698. e[5] = 0;
  699. e[6] = 0;
  700. e[7] = 0;
  701. e[8] = scale.z;
  702. }
  703. static createFromMatrix4x4(sou, out) {
  704. var souE = sou.elements;
  705. var outE = out.elements;
  706. outE[0] = souE[0];
  707. outE[1] = souE[1];
  708. outE[2] = souE[2];
  709. outE[3] = souE[4];
  710. outE[4] = souE[5];
  711. outE[5] = souE[6];
  712. outE[6] = souE[8];
  713. outE[7] = souE[9];
  714. outE[8] = souE[10];
  715. }
  716. static multiply(left, right, out) {
  717. var l = left.elements;
  718. var r = right.elements;
  719. var e = out.elements;
  720. var l11 = l[0], l12 = l[1], l13 = l[2];
  721. var l21 = l[3], l22 = l[4], l23 = l[5];
  722. var l31 = l[6], l32 = l[7], l33 = l[8];
  723. var r11 = r[0], r12 = r[1], r13 = r[2];
  724. var r21 = r[3], r22 = r[4], r23 = r[5];
  725. var r31 = r[6], r32 = r[7], r33 = r[8];
  726. e[0] = r11 * l11 + r12 * l21 + r13 * l31;
  727. e[1] = r11 * l12 + r12 * l22 + r13 * r32;
  728. e[2] = r11 * l13 + r12 * l23 + r13 * l33;
  729. e[3] = r21 * l11 + r22 * l21 + r23 * l31;
  730. e[4] = r21 * l12 + r22 * l22 + r23 * l32;
  731. e[5] = r21 * l13 + r22 * l23 + r23 * l33;
  732. e[6] = r31 * l11 + r32 * l21 + r33 * l31;
  733. e[7] = r31 * l12 + r32 * l22 + r33 * l32;
  734. e[8] = r31 * l13 + r32 * l23 + r33 * l33;
  735. }
  736. determinant() {
  737. var f = this.elements;
  738. var a00 = f[0], a01 = f[1], a02 = f[2];
  739. var a10 = f[3], a11 = f[4], a12 = f[5];
  740. var a20 = f[6], a21 = f[7], a22 = f[8];
  741. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  742. }
  743. translate(trans, out) {
  744. var e = out.elements;
  745. var f = this.elements;
  746. var a00 = f[0], a01 = f[1], a02 = f[2];
  747. var a10 = f[3], a11 = f[4], a12 = f[5];
  748. var a20 = f[6], a21 = f[7], a22 = f[8];
  749. var x = trans.x, y = trans.y;
  750. e[0] = a00;
  751. e[1] = a01;
  752. e[2] = a02;
  753. e[3] = a10;
  754. e[4] = a11;
  755. e[5] = a12;
  756. e[6] = x * a00 + y * a10 + a20;
  757. e[7] = x * a01 + y * a11 + a21;
  758. e[8] = x * a02 + y * a12 + a22;
  759. }
  760. rotate(rad, out) {
  761. var e = out.elements;
  762. var f = this.elements;
  763. var a00 = f[0], a01 = f[1], a02 = f[2];
  764. var a10 = f[3], a11 = f[4], a12 = f[5];
  765. var a20 = f[6], a21 = f[7], a22 = f[8];
  766. var s = Math.sin(rad);
  767. var c = Math.cos(rad);
  768. e[0] = c * a00 + s * a10;
  769. e[1] = c * a01 + s * a11;
  770. e[2] = c * a02 + s * a12;
  771. e[3] = c * a10 - s * a00;
  772. e[4] = c * a11 - s * a01;
  773. e[5] = c * a12 - s * a02;
  774. e[6] = a20;
  775. e[7] = a21;
  776. e[8] = a22;
  777. }
  778. scale(scale, out) {
  779. var e = out.elements;
  780. var f = this.elements;
  781. var x = scale.x, y = scale.y;
  782. e[0] = x * f[0];
  783. e[1] = x * f[1];
  784. e[2] = x * f[2];
  785. e[3] = y * f[3];
  786. e[4] = y * f[4];
  787. e[5] = y * f[5];
  788. e[6] = f[6];
  789. e[7] = f[7];
  790. e[8] = f[8];
  791. }
  792. invert(out) {
  793. var e = out.elements;
  794. var f = this.elements;
  795. var a00 = f[0], a01 = f[1], a02 = f[2];
  796. var a10 = f[3], a11 = f[4], a12 = f[5];
  797. var a20 = f[6], a21 = f[7], a22 = f[8];
  798. var b01 = a22 * a11 - a12 * a21;
  799. var b11 = -a22 * a10 + a12 * a20;
  800. var b21 = a21 * a10 - a11 * a20;
  801. var det = a00 * b01 + a01 * b11 + a02 * b21;
  802. if (!det) {
  803. out = null;
  804. }
  805. det = 1.0 / det;
  806. e[0] = b01 * det;
  807. e[1] = (-a22 * a01 + a02 * a21) * det;
  808. e[2] = (a12 * a01 - a02 * a11) * det;
  809. e[3] = b11 * det;
  810. e[4] = (a22 * a00 - a02 * a20) * det;
  811. e[5] = (-a12 * a00 + a02 * a10) * det;
  812. e[6] = b21 * det;
  813. e[7] = (-a21 * a00 + a01 * a20) * det;
  814. e[8] = (a11 * a00 - a01 * a10) * det;
  815. }
  816. transpose(out) {
  817. var e = out.elements;
  818. var f = this.elements;
  819. if (out === this) {
  820. var a01 = f[1], a02 = f[2], a12 = f[5];
  821. e[1] = f[3];
  822. e[2] = f[6];
  823. e[3] = a01;
  824. e[5] = f[7];
  825. e[6] = a02;
  826. e[7] = a12;
  827. }
  828. else {
  829. e[0] = f[0];
  830. e[1] = f[3];
  831. e[2] = f[6];
  832. e[3] = f[1];
  833. e[4] = f[4];
  834. e[5] = f[7];
  835. e[6] = f[2];
  836. e[7] = f[5];
  837. e[8] = f[8];
  838. }
  839. }
  840. identity() {
  841. var e = this.elements;
  842. e[0] = 1;
  843. e[1] = 0;
  844. e[2] = 0;
  845. e[3] = 0;
  846. e[4] = 1;
  847. e[5] = 0;
  848. e[6] = 0;
  849. e[7] = 0;
  850. e[8] = 1;
  851. }
  852. cloneTo(destObject) {
  853. var i, s, d;
  854. s = this.elements;
  855. d = destObject.elements;
  856. if (s === d) {
  857. return;
  858. }
  859. for (i = 0; i < 9; ++i) {
  860. d[i] = s[i];
  861. }
  862. }
  863. clone() {
  864. var dest = new Matrix3x3();
  865. this.cloneTo(dest);
  866. return dest;
  867. }
  868. static lookAt(eye, target, up, out) {
  869. Vector3.subtract(eye, target, Matrix3x3._tempV30);
  870. Vector3.normalize(Matrix3x3._tempV30, Matrix3x3._tempV30);
  871. Vector3.cross(up, Matrix3x3._tempV30, Matrix3x3._tempV31);
  872. Vector3.normalize(Matrix3x3._tempV31, Matrix3x3._tempV31);
  873. Vector3.cross(Matrix3x3._tempV30, Matrix3x3._tempV31, Matrix3x3._tempV32);
  874. var v0 = Matrix3x3._tempV30;
  875. var v1 = Matrix3x3._tempV31;
  876. var v2 = Matrix3x3._tempV32;
  877. var me = out.elements;
  878. me[0] = v1.x;
  879. me[3] = v1.y;
  880. me[6] = v1.z;
  881. me[1] = v2.x;
  882. me[4] = v2.y;
  883. me[7] = v2.z;
  884. me[2] = v0.x;
  885. me[5] = v0.y;
  886. me[8] = v0.z;
  887. }
  888. }
  889. Matrix3x3.DEFAULT = new Matrix3x3();
  890. Matrix3x3._tempV30 = new Vector3();
  891. Matrix3x3._tempV31 = new Vector3();
  892. Matrix3x3._tempV32 = new Vector3();
  893. class Quaternion {
  894. constructor(x = 0, y = 0, z = 0, w = 1, nativeElements = null) {
  895. this.x = x;
  896. this.y = y;
  897. this.z = z;
  898. this.w = w;
  899. }
  900. static createFromYawPitchRoll(yaw, pitch, roll, out) {
  901. var halfRoll = roll * 0.5;
  902. var halfPitch = pitch * 0.5;
  903. var halfYaw = yaw * 0.5;
  904. var sinRoll = Math.sin(halfRoll);
  905. var cosRoll = Math.cos(halfRoll);
  906. var sinPitch = Math.sin(halfPitch);
  907. var cosPitch = Math.cos(halfPitch);
  908. var sinYaw = Math.sin(halfYaw);
  909. var cosYaw = Math.cos(halfYaw);
  910. out.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  911. out.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  912. out.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  913. out.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  914. }
  915. static multiply(left, right, out) {
  916. var lx = left.x;
  917. var ly = left.y;
  918. var lz = left.z;
  919. var lw = left.w;
  920. var rx = right.x;
  921. var ry = right.y;
  922. var rz = right.z;
  923. var rw = right.w;
  924. var a = (ly * rz - lz * ry);
  925. var b = (lz * rx - lx * rz);
  926. var c = (lx * ry - ly * rx);
  927. var d = (lx * rx + ly * ry + lz * rz);
  928. out.x = (lx * rw + rx * lw) + a;
  929. out.y = (ly * rw + ry * lw) + b;
  930. out.z = (lz * rw + rz * lw) + c;
  931. out.w = lw * rw - d;
  932. }
  933. static arcTanAngle(x, y) {
  934. if (x == 0) {
  935. if (y == 1)
  936. return Math.PI / 2;
  937. return -Math.PI / 2;
  938. }
  939. if (x > 0)
  940. return Math.atan(y / x);
  941. if (x < 0) {
  942. if (y > 0)
  943. return Math.atan(y / x) + Math.PI;
  944. return Math.atan(y / x) - Math.PI;
  945. }
  946. return 0;
  947. }
  948. static angleTo(from, location, angle) {
  949. Vector3.subtract(location, from, Quaternion.TEMPVector30);
  950. Vector3.normalize(Quaternion.TEMPVector30, Quaternion.TEMPVector30);
  951. angle.x = Math.asin(Quaternion.TEMPVector30.y);
  952. angle.y = Quaternion.arcTanAngle(-Quaternion.TEMPVector30.z, -Quaternion.TEMPVector30.x);
  953. }
  954. static createFromAxisAngle(axis, rad, out) {
  955. rad = rad * 0.5;
  956. var s = Math.sin(rad);
  957. out.x = s * axis.x;
  958. out.y = s * axis.y;
  959. out.z = s * axis.z;
  960. out.w = Math.cos(rad);
  961. }
  962. static createFromMatrix4x4(mat, out) {
  963. var me = mat.elements;
  964. var sqrt;
  965. var half;
  966. var scale = me[0] + me[5] + me[10];
  967. if (scale > 0.0) {
  968. sqrt = Math.sqrt(scale + 1.0);
  969. out.w = sqrt * 0.5;
  970. sqrt = 0.5 / sqrt;
  971. out.x = (me[6] - me[9]) * sqrt;
  972. out.y = (me[8] - me[2]) * sqrt;
  973. out.z = (me[1] - me[4]) * sqrt;
  974. }
  975. else if ((me[0] >= me[5]) && (me[0] >= me[10])) {
  976. sqrt = Math.sqrt(1.0 + me[0] - me[5] - me[10]);
  977. half = 0.5 / sqrt;
  978. out.x = 0.5 * sqrt;
  979. out.y = (me[1] + me[4]) * half;
  980. out.z = (me[2] + me[8]) * half;
  981. out.w = (me[6] - me[9]) * half;
  982. }
  983. else if (me[5] > me[10]) {
  984. sqrt = Math.sqrt(1.0 + me[5] - me[0] - me[10]);
  985. half = 0.5 / sqrt;
  986. out.x = (me[4] + me[1]) * half;
  987. out.y = 0.5 * sqrt;
  988. out.z = (me[9] + me[6]) * half;
  989. out.w = (me[8] - me[2]) * half;
  990. }
  991. else {
  992. sqrt = Math.sqrt(1.0 + me[10] - me[0] - me[5]);
  993. half = 0.5 / sqrt;
  994. out.x = (me[8] + me[2]) * half;
  995. out.y = (me[9] + me[6]) * half;
  996. out.z = 0.5 * sqrt;
  997. out.w = (me[1] - me[4]) * half;
  998. }
  999. }
  1000. static slerp(left, right, t, out) {
  1001. var ax = left.x, ay = left.y, az = left.z, aw = left.w, bx = right.x, by = right.y, bz = right.z, bw = right.w;
  1002. var omega, cosom, sinom, scale0, scale1;
  1003. cosom = ax * bx + ay * by + az * bz + aw * bw;
  1004. if (cosom < 0.0) {
  1005. cosom = -cosom;
  1006. bx = -bx;
  1007. by = -by;
  1008. bz = -bz;
  1009. bw = -bw;
  1010. }
  1011. if ((1.0 - cosom) > 0.000001) {
  1012. omega = Math.acos(cosom);
  1013. sinom = Math.sin(omega);
  1014. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  1015. scale1 = Math.sin(t * omega) / sinom;
  1016. }
  1017. else {
  1018. scale0 = 1.0 - t;
  1019. scale1 = t;
  1020. }
  1021. out.x = scale0 * ax + scale1 * bx;
  1022. out.y = scale0 * ay + scale1 * by;
  1023. out.z = scale0 * az + scale1 * bz;
  1024. out.w = scale0 * aw + scale1 * bw;
  1025. return out;
  1026. }
  1027. static lerp(left, right, amount, out) {
  1028. var inverse = 1.0 - amount;
  1029. if (Quaternion.dot(left, right) >= 0) {
  1030. out.x = (inverse * left.x) + (amount * right.x);
  1031. out.y = (inverse * left.y) + (amount * right.y);
  1032. out.z = (inverse * left.z) + (amount * right.z);
  1033. out.w = (inverse * left.w) + (amount * right.w);
  1034. }
  1035. else {
  1036. out.x = (inverse * left.x) - (amount * right.x);
  1037. out.y = (inverse * left.y) - (amount * right.y);
  1038. out.z = (inverse * left.z) - (amount * right.z);
  1039. out.w = (inverse * left.w) - (amount * right.w);
  1040. }
  1041. out.normalize(out);
  1042. }
  1043. static add(left, right, out) {
  1044. out.x = left.x + right.x;
  1045. out.y = left.y + right.y;
  1046. out.z = left.z + right.z;
  1047. out.w = left.w + right.w;
  1048. }
  1049. static dot(left, right) {
  1050. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  1051. }
  1052. scaling(scaling, out) {
  1053. out.x = this.x * scaling;
  1054. out.y = this.y * scaling;
  1055. out.z = this.z * scaling;
  1056. out.w = this.w * scaling;
  1057. }
  1058. normalize(out) {
  1059. var len = this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1060. if (len > 0) {
  1061. len = 1 / Math.sqrt(len);
  1062. out.x = this.x * len;
  1063. out.y = this.y * len;
  1064. out.z = this.z * len;
  1065. out.w = this.w * len;
  1066. }
  1067. }
  1068. length() {
  1069. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1070. }
  1071. rotateX(rad, out) {
  1072. rad *= 0.5;
  1073. var bx = Math.sin(rad), bw = Math.cos(rad);
  1074. out.x = this.x * bw + this.w * bx;
  1075. out.y = this.y * bw + this.z * bx;
  1076. out.z = this.z * bw - this.y * bx;
  1077. out.w = this.w * bw - this.x * bx;
  1078. }
  1079. rotateY(rad, out) {
  1080. rad *= 0.5;
  1081. var by = Math.sin(rad), bw = Math.cos(rad);
  1082. out.x = this.x * bw - this.z * by;
  1083. out.y = this.y * bw + this.w * by;
  1084. out.z = this.z * bw + this.x * by;
  1085. out.w = this.w * bw - this.y * by;
  1086. }
  1087. rotateZ(rad, out) {
  1088. rad *= 0.5;
  1089. var bz = Math.sin(rad), bw = Math.cos(rad);
  1090. out.x = this.x * bw + this.y * bz;
  1091. out.y = this.y * bw - this.x * bz;
  1092. out.z = this.z * bw + this.w * bz;
  1093. out.w = this.w * bw - this.z * bz;
  1094. }
  1095. getYawPitchRoll(out) {
  1096. Vector3.transformQuat(Vector3._ForwardRH, this, Quaternion.TEMPVector31);
  1097. Vector3.transformQuat(Vector3._Up, this, Quaternion.TEMPVector32);
  1098. var upe = Quaternion.TEMPVector32;
  1099. Quaternion.angleTo(Vector3._ZERO, Quaternion.TEMPVector31, Quaternion.TEMPVector33);
  1100. var angle = Quaternion.TEMPVector33;
  1101. if (angle.x == Math.PI / 2) {
  1102. angle.y = Quaternion.arcTanAngle(upe.z, upe.x);
  1103. angle.z = 0;
  1104. }
  1105. else if (angle.x == -Math.PI / 2) {
  1106. angle.y = Quaternion.arcTanAngle(-upe.z, -upe.x);
  1107. angle.z = 0;
  1108. }
  1109. else {
  1110. ILaya3D.Matrix4x4.createRotationY(-angle.y, ILaya3D.Matrix4x4.TEMPMatrix0);
  1111. ILaya3D.Matrix4x4.createRotationX(-angle.x, ILaya3D.Matrix4x4.TEMPMatrix1);
  1112. Vector3.transformCoordinate(Quaternion.TEMPVector32, ILaya3D.Matrix4x4.TEMPMatrix0, Quaternion.TEMPVector32);
  1113. Vector3.transformCoordinate(Quaternion.TEMPVector32, ILaya3D.Matrix4x4.TEMPMatrix1, Quaternion.TEMPVector32);
  1114. angle.z = Quaternion.arcTanAngle(upe.y, -upe.x);
  1115. }
  1116. if (angle.y <= -Math.PI)
  1117. angle.y = Math.PI;
  1118. if (angle.z <= -Math.PI)
  1119. angle.z = Math.PI;
  1120. if (angle.y >= Math.PI && angle.z >= Math.PI) {
  1121. angle.y = 0;
  1122. angle.z = 0;
  1123. angle.x = Math.PI - angle.x;
  1124. }
  1125. var oe = out;
  1126. oe.x = angle.y;
  1127. oe.y = angle.x;
  1128. oe.z = angle.z;
  1129. }
  1130. invert(out) {
  1131. var a0 = this.x, a1 = this.y, a2 = this.z, a3 = this.w;
  1132. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  1133. var invDot = dot ? 1.0 / dot : 0;
  1134. out.x = -a0 * invDot;
  1135. out.y = -a1 * invDot;
  1136. out.z = -a2 * invDot;
  1137. out.w = a3 * invDot;
  1138. }
  1139. identity() {
  1140. this.x = 0;
  1141. this.y = 0;
  1142. this.z = 0;
  1143. this.w = 1;
  1144. }
  1145. fromArray(array, offset = 0) {
  1146. this.x = array[offset + 0];
  1147. this.y = array[offset + 1];
  1148. this.z = array[offset + 2];
  1149. this.w = array[offset + 3];
  1150. }
  1151. cloneTo(destObject) {
  1152. if (this === destObject) {
  1153. return;
  1154. }
  1155. destObject.x = this.x;
  1156. destObject.y = this.y;
  1157. destObject.z = this.z;
  1158. destObject.w = this.w;
  1159. }
  1160. clone() {
  1161. var dest = new Quaternion();
  1162. this.cloneTo(dest);
  1163. return dest;
  1164. }
  1165. equals(b) {
  1166. return MathUtils3D.nearEqual(this.x, b.x) && MathUtils3D.nearEqual(this.y, b.y) && MathUtils3D.nearEqual(this.z, b.z) && MathUtils3D.nearEqual(this.w, b.w);
  1167. }
  1168. static rotationLookAt(forward, up, out) {
  1169. Quaternion.lookAt(Vector3._ZERO, forward, up, out);
  1170. }
  1171. static lookAt(eye, target, up, out) {
  1172. Matrix3x3.lookAt(eye, target, up, Quaternion._tempMatrix3x3);
  1173. Quaternion.rotationMatrix(Quaternion._tempMatrix3x3, out);
  1174. }
  1175. lengthSquared() {
  1176. return (this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w);
  1177. }
  1178. static invert(value, out) {
  1179. var lengthSq = value.lengthSquared();
  1180. if (!MathUtils3D.isZero(lengthSq)) {
  1181. lengthSq = 1.0 / lengthSq;
  1182. out.x = -value.x * lengthSq;
  1183. out.y = -value.y * lengthSq;
  1184. out.z = -value.z * lengthSq;
  1185. out.w = value.w * lengthSq;
  1186. }
  1187. }
  1188. static rotationMatrix(matrix3x3, out) {
  1189. var me = matrix3x3.elements;
  1190. var m11 = me[0];
  1191. var m12 = me[1];
  1192. var m13 = me[2];
  1193. var m21 = me[3];
  1194. var m22 = me[4];
  1195. var m23 = me[5];
  1196. var m31 = me[6];
  1197. var m32 = me[7];
  1198. var m33 = me[8];
  1199. var sqrt, half;
  1200. var scale = m11 + m22 + m33;
  1201. if (scale > 0) {
  1202. sqrt = Math.sqrt(scale + 1);
  1203. out.w = sqrt * 0.5;
  1204. sqrt = 0.5 / sqrt;
  1205. out.x = (m23 - m32) * sqrt;
  1206. out.y = (m31 - m13) * sqrt;
  1207. out.z = (m12 - m21) * sqrt;
  1208. }
  1209. else if ((m11 >= m22) && (m11 >= m33)) {
  1210. sqrt = Math.sqrt(1 + m11 - m22 - m33);
  1211. half = 0.5 / sqrt;
  1212. out.x = 0.5 * sqrt;
  1213. out.y = (m12 + m21) * half;
  1214. out.z = (m13 + m31) * half;
  1215. out.w = (m23 - m32) * half;
  1216. }
  1217. else if (m22 > m33) {
  1218. sqrt = Math.sqrt(1 + m22 - m11 - m33);
  1219. half = 0.5 / sqrt;
  1220. out.x = (m21 + m12) * half;
  1221. out.y = 0.5 * sqrt;
  1222. out.z = (m32 + m23) * half;
  1223. out.w = (m31 - m13) * half;
  1224. }
  1225. else {
  1226. sqrt = Math.sqrt(1 + m33 - m11 - m22);
  1227. half = 0.5 / sqrt;
  1228. out.x = (m31 + m13) * half;
  1229. out.y = (m32 + m23) * half;
  1230. out.z = 0.5 * sqrt;
  1231. out.w = (m12 - m21) * half;
  1232. }
  1233. }
  1234. forNativeElement(nativeElements = null) {
  1235. if (nativeElements) {
  1236. this.elements = nativeElements;
  1237. this.elements[0] = this.x;
  1238. this.elements[1] = this.y;
  1239. this.elements[2] = this.z;
  1240. this.elements[3] = this.w;
  1241. }
  1242. else {
  1243. this.elements = new Float32Array([this.x, this.y, this.z, this.w]);
  1244. }
  1245. Vector2.rewriteNumProperty(this, "x", 0);
  1246. Vector2.rewriteNumProperty(this, "y", 1);
  1247. Vector2.rewriteNumProperty(this, "z", 2);
  1248. Vector2.rewriteNumProperty(this, "w", 3);
  1249. }
  1250. }
  1251. Quaternion.TEMPVector30 = new Vector3();
  1252. Quaternion.TEMPVector31 = new Vector3();
  1253. Quaternion.TEMPVector32 = new Vector3();
  1254. Quaternion.TEMPVector33 = new Vector3();
  1255. Quaternion._tempMatrix3x3 = new Matrix3x3();
  1256. Quaternion.DEFAULT = new Quaternion();
  1257. Quaternion.NAN = new Quaternion(NaN, NaN, NaN, NaN);
  1258. class QuaternionKeyframe extends Keyframe {
  1259. constructor() {
  1260. super();
  1261. this.inTangent = new Vector4();
  1262. this.outTangent = new Vector4();
  1263. this.value = new Quaternion();
  1264. }
  1265. cloneTo(dest) {
  1266. super.cloneTo(dest);
  1267. var destKeyFarme = dest;
  1268. this.inTangent.cloneTo(destKeyFarme.inTangent);
  1269. this.outTangent.cloneTo(destKeyFarme.outTangent);
  1270. this.value.cloneTo(destKeyFarme.value);
  1271. }
  1272. }
  1273. class Vector3Keyframe extends Keyframe {
  1274. constructor() {
  1275. super();
  1276. this.inTangent = new Vector3();
  1277. this.outTangent = new Vector3();
  1278. this.value = new Vector3();
  1279. }
  1280. cloneTo(dest) {
  1281. super.cloneTo(dest);
  1282. var destKeyFarme = dest;
  1283. this.inTangent.cloneTo(destKeyFarme.inTangent);
  1284. this.outTangent.cloneTo(destKeyFarme.outTangent);
  1285. this.value.cloneTo(destKeyFarme.value);
  1286. }
  1287. }
  1288. class AnimationClipParser03 {
  1289. static READ_DATA() {
  1290. AnimationClipParser03._DATA.offset = AnimationClipParser03._reader.getUint32();
  1291. AnimationClipParser03._DATA.size = AnimationClipParser03._reader.getUint32();
  1292. }
  1293. static READ_BLOCK() {
  1294. var count = AnimationClipParser03._BLOCK.count = AnimationClipParser03._reader.getUint16();
  1295. var blockStarts = AnimationClipParser03._BLOCK.blockStarts = [];
  1296. var blockLengths = AnimationClipParser03._BLOCK.blockLengths = [];
  1297. for (var i = 0; i < count; i++) {
  1298. blockStarts.push(AnimationClipParser03._reader.getUint32());
  1299. blockLengths.push(AnimationClipParser03._reader.getUint32());
  1300. }
  1301. }
  1302. static READ_STRINGS() {
  1303. var offset = AnimationClipParser03._reader.getUint32();
  1304. var count = AnimationClipParser03._reader.getUint16();
  1305. var prePos = AnimationClipParser03._reader.pos;
  1306. AnimationClipParser03._reader.pos = offset + AnimationClipParser03._DATA.offset;
  1307. for (var i = 0; i < count; i++)
  1308. AnimationClipParser03._strings[i] = AnimationClipParser03._reader.readUTFString();
  1309. AnimationClipParser03._reader.pos = prePos;
  1310. }
  1311. static parse(clip, reader) {
  1312. AnimationClipParser03._animationClip = clip;
  1313. AnimationClipParser03._reader = reader;
  1314. var arrayBuffer = reader.__getBuffer();
  1315. AnimationClipParser03.READ_DATA();
  1316. AnimationClipParser03.READ_BLOCK();
  1317. AnimationClipParser03.READ_STRINGS();
  1318. for (var i = 0, n = AnimationClipParser03._BLOCK.count; i < n; i++) {
  1319. var index = reader.getUint16();
  1320. var blockName = AnimationClipParser03._strings[index];
  1321. var fn = AnimationClipParser03["READ_" + blockName];
  1322. if (fn == null)
  1323. throw new Error("model file err,no this function:" + index + " " + blockName);
  1324. else
  1325. fn.call(null);
  1326. }
  1327. }
  1328. static READ_ANIMATIONS() {
  1329. var i, j;
  1330. var node;
  1331. var reader = AnimationClipParser03._reader;
  1332. var buffer = reader.__getBuffer();
  1333. var startTimeTypes = [];
  1334. var startTimeTypeCount = reader.getUint16();
  1335. startTimeTypes.length = startTimeTypeCount;
  1336. for (i = 0; i < startTimeTypeCount; i++)
  1337. startTimeTypes[i] = reader.getFloat32();
  1338. var clip = AnimationClipParser03._animationClip;
  1339. clip.name = AnimationClipParser03._strings[reader.getUint16()];
  1340. var clipDur = clip._duration = reader.getFloat32();
  1341. clip.islooping = !!reader.getByte();
  1342. clip._frameRate = reader.getInt16();
  1343. var nodeCount = reader.getInt16();
  1344. var nodes = clip._nodes;
  1345. nodes.count = nodeCount;
  1346. var nodesMap = clip._nodesMap = {};
  1347. var nodesDic = clip._nodesDic = {};
  1348. for (i = 0; i < nodeCount; i++) {
  1349. node = new KeyframeNode();
  1350. nodes.setNodeByIndex(i, node);
  1351. node._indexInList = i;
  1352. var type = node.type = reader.getUint8();
  1353. var pathLength = reader.getUint16();
  1354. node._setOwnerPathCount(pathLength);
  1355. for (j = 0; j < pathLength; j++)
  1356. node._setOwnerPathByIndex(j, AnimationClipParser03._strings[reader.getUint16()]);
  1357. var nodePath = node._joinOwnerPath("/");
  1358. var mapArray = nodesMap[nodePath];
  1359. (mapArray) || (nodesMap[nodePath] = mapArray = []);
  1360. mapArray.push(node);
  1361. node.propertyOwner = AnimationClipParser03._strings[reader.getUint16()];
  1362. var propertyLength = reader.getUint16();
  1363. node._setPropertyCount(propertyLength);
  1364. for (j = 0; j < propertyLength; j++)
  1365. node._setPropertyByIndex(j, AnimationClipParser03._strings[reader.getUint16()]);
  1366. var fullPath = nodePath + "." + node.propertyOwner + "." + node._joinProperty(".");
  1367. nodesDic[fullPath] = node;
  1368. node.fullPath = fullPath;
  1369. var keyframeCount = reader.getUint16();
  1370. node._setKeyframeCount(keyframeCount);
  1371. var startTime;
  1372. for (j = 0; j < keyframeCount; j++) {
  1373. switch (type) {
  1374. case 0:
  1375. var floatKeyframe = new FloatKeyframe();
  1376. node._setKeyframeByIndex(j, floatKeyframe);
  1377. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  1378. floatKeyframe.inTangent = reader.getFloat32();
  1379. floatKeyframe.outTangent = reader.getFloat32();
  1380. floatKeyframe.value = reader.getFloat32();
  1381. break;
  1382. case 1:
  1383. case 3:
  1384. case 4:
  1385. var floatArrayKeyframe = new Vector3Keyframe();
  1386. node._setKeyframeByIndex(j, floatArrayKeyframe);
  1387. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  1388. if (Laya.Render.supportWebGLPlusAnimation) {
  1389. var data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  1390. for (var k = 0; k < 3; k++)
  1391. data[k] = reader.getFloat32();
  1392. for (k = 0; k < 3; k++)
  1393. data[3 + k] = reader.getFloat32();
  1394. for (k = 0; k < 3; k++)
  1395. data[6 + k] = reader.getFloat32();
  1396. }
  1397. else {
  1398. var inTangent = floatArrayKeyframe.inTangent;
  1399. var outTangent = floatArrayKeyframe.outTangent;
  1400. var value = floatArrayKeyframe.value;
  1401. inTangent.x = reader.getFloat32();
  1402. inTangent.y = reader.getFloat32();
  1403. inTangent.z = reader.getFloat32();
  1404. outTangent.x = reader.getFloat32();
  1405. outTangent.y = reader.getFloat32();
  1406. outTangent.z = reader.getFloat32();
  1407. value.x = reader.getFloat32();
  1408. value.y = reader.getFloat32();
  1409. value.z = reader.getFloat32();
  1410. }
  1411. break;
  1412. case 2:
  1413. var quaArrayKeyframe = new QuaternionKeyframe();
  1414. node._setKeyframeByIndex(j, quaArrayKeyframe);
  1415. startTime = quaArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  1416. if (Laya.Render.supportWebGLPlusAnimation) {
  1417. data = quaArrayKeyframe.data = new Float32Array(3 * 4);
  1418. for (k = 0; k < 4; k++)
  1419. data[k] = reader.getFloat32();
  1420. for (k = 0; k < 4; k++)
  1421. data[4 + k] = reader.getFloat32();
  1422. for (k = 0; k < 4; k++)
  1423. data[8 + k] = reader.getFloat32();
  1424. }
  1425. else {
  1426. var inTangentQua = quaArrayKeyframe.inTangent;
  1427. var outTangentQua = quaArrayKeyframe.outTangent;
  1428. var valueQua = quaArrayKeyframe.value;
  1429. inTangentQua.x = reader.getFloat32();
  1430. inTangentQua.y = reader.getFloat32();
  1431. inTangentQua.z = reader.getFloat32();
  1432. inTangentQua.w = reader.getFloat32();
  1433. outTangentQua.x = reader.getFloat32();
  1434. outTangentQua.y = reader.getFloat32();
  1435. outTangentQua.z = reader.getFloat32();
  1436. outTangentQua.w = reader.getFloat32();
  1437. valueQua.x = reader.getFloat32();
  1438. valueQua.y = reader.getFloat32();
  1439. valueQua.z = reader.getFloat32();
  1440. valueQua.w = reader.getFloat32();
  1441. }
  1442. break;
  1443. default:
  1444. throw "AnimationClipParser03:unknown type.";
  1445. }
  1446. }
  1447. }
  1448. var eventCount = reader.getUint16();
  1449. for (i = 0; i < eventCount; i++) {
  1450. var event = new AnimationEvent();
  1451. event.time = Math.min(clipDur, reader.getFloat32());
  1452. event.eventName = AnimationClipParser03._strings[reader.getUint16()];
  1453. var params;
  1454. var paramCount = reader.getUint16();
  1455. (paramCount > 0) && (event.params = params = []);
  1456. for (j = 0; j < paramCount; j++) {
  1457. var eventType = reader.getByte();
  1458. switch (eventType) {
  1459. case 0:
  1460. params.push(!!reader.getByte());
  1461. break;
  1462. case 1:
  1463. params.push(reader.getInt32());
  1464. break;
  1465. case 2:
  1466. params.push(reader.getFloat32());
  1467. break;
  1468. case 3:
  1469. params.push(AnimationClipParser03._strings[reader.getUint16()]);
  1470. break;
  1471. default:
  1472. throw new Error("unknown type.");
  1473. }
  1474. }
  1475. clip.addEvent(event);
  1476. }
  1477. }
  1478. }
  1479. AnimationClipParser03._strings = [];
  1480. AnimationClipParser03._BLOCK = { count: 0 };
  1481. AnimationClipParser03._DATA = { offset: 0, size: 0 };
  1482. class HalfFloatUtils {
  1483. static __init__() {
  1484. for (var i = 0; i < 256; ++i) {
  1485. var e = i - 127;
  1486. if (e < -27) {
  1487. HalfFloatUtils._baseTable[i | 0x000] = 0x0000;
  1488. HalfFloatUtils._baseTable[i | 0x100] = 0x8000;
  1489. HalfFloatUtils._shiftTable[i | 0x000] = 24;
  1490. HalfFloatUtils._shiftTable[i | 0x100] = 24;
  1491. }
  1492. else if (e < -14) {
  1493. HalfFloatUtils._baseTable[i | 0x000] = 0x0400 >> (-e - 14);
  1494. HalfFloatUtils._baseTable[i | 0x100] = (0x0400 >> (-e - 14)) | 0x8000;
  1495. HalfFloatUtils._shiftTable[i | 0x000] = -e - 1;
  1496. HalfFloatUtils._shiftTable[i | 0x100] = -e - 1;
  1497. }
  1498. else if (e <= 15) {
  1499. HalfFloatUtils._baseTable[i | 0x000] = (e + 15) << 10;
  1500. HalfFloatUtils._baseTable[i | 0x100] = ((e + 15) << 10) | 0x8000;
  1501. HalfFloatUtils._shiftTable[i | 0x000] = 13;
  1502. HalfFloatUtils._shiftTable[i | 0x100] = 13;
  1503. }
  1504. else if (e < 128) {
  1505. HalfFloatUtils._baseTable[i | 0x000] = 0x7c00;
  1506. HalfFloatUtils._baseTable[i | 0x100] = 0xfc00;
  1507. HalfFloatUtils._shiftTable[i | 0x000] = 24;
  1508. HalfFloatUtils._shiftTable[i | 0x100] = 24;
  1509. }
  1510. else {
  1511. HalfFloatUtils._baseTable[i | 0x000] = 0x7c00;
  1512. HalfFloatUtils._baseTable[i | 0x100] = 0xfc00;
  1513. HalfFloatUtils._shiftTable[i | 0x000] = 13;
  1514. HalfFloatUtils._shiftTable[i | 0x100] = 13;
  1515. }
  1516. }
  1517. HalfFloatUtils._mantissaTable[0] = 0;
  1518. for (i = 1; i < 1024; ++i) {
  1519. var m = i << 13;
  1520. e = 0;
  1521. while ((m & 0x00800000) === 0) {
  1522. e -= 0x00800000;
  1523. m <<= 1;
  1524. }
  1525. m &= ~0x00800000;
  1526. e += 0x38800000;
  1527. HalfFloatUtils._mantissaTable[i] = m | e;
  1528. }
  1529. for (i = 1024; i < 2048; ++i) {
  1530. HalfFloatUtils._mantissaTable[i] = 0x38000000 + ((i - 1024) << 13);
  1531. }
  1532. HalfFloatUtils._exponentTable[0] = 0;
  1533. for (i = 1; i < 31; ++i) {
  1534. HalfFloatUtils._exponentTable[i] = i << 23;
  1535. }
  1536. HalfFloatUtils._exponentTable[31] = 0x47800000;
  1537. HalfFloatUtils._exponentTable[32] = 0x80000000;
  1538. for (i = 33; i < 63; ++i) {
  1539. HalfFloatUtils._exponentTable[i] = 0x80000000 + ((i - 32) << 23);
  1540. }
  1541. HalfFloatUtils._exponentTable[63] = 0xc7800000;
  1542. HalfFloatUtils._offsetTable[0] = 0;
  1543. for (i = 1; i < 64; ++i) {
  1544. if (i === 32) {
  1545. HalfFloatUtils._offsetTable[i] = 0;
  1546. }
  1547. else {
  1548. HalfFloatUtils._offsetTable[i] = 1024;
  1549. }
  1550. }
  1551. }
  1552. static roundToFloat16Bits(num) {
  1553. HalfFloatUtils._floatView[0] = num;
  1554. var f = HalfFloatUtils._uint32View[0];
  1555. var e = (f >> 23) & 0x1ff;
  1556. return HalfFloatUtils._baseTable[e] + ((f & 0x007fffff) >> HalfFloatUtils._shiftTable[e]);
  1557. }
  1558. static convertToNumber(float16bits) {
  1559. var m = float16bits >> 10;
  1560. HalfFloatUtils._uint32View[0] = HalfFloatUtils._mantissaTable[HalfFloatUtils._offsetTable[m] + (float16bits & 0x3ff)] + HalfFloatUtils._exponentTable[m];
  1561. return HalfFloatUtils._floatView[0];
  1562. }
  1563. }
  1564. HalfFloatUtils._buffer = new ArrayBuffer(4);
  1565. HalfFloatUtils._floatView = new Float32Array(HalfFloatUtils._buffer);
  1566. HalfFloatUtils._uint32View = new Uint32Array(HalfFloatUtils._buffer);
  1567. HalfFloatUtils._baseTable = new Uint32Array(512);
  1568. HalfFloatUtils._shiftTable = new Uint32Array(512);
  1569. HalfFloatUtils._mantissaTable = new Uint32Array(2048);
  1570. HalfFloatUtils._exponentTable = new Uint32Array(64);
  1571. HalfFloatUtils._offsetTable = new Uint32Array(64);
  1572. class AnimationClipParser04 {
  1573. static READ_DATA() {
  1574. AnimationClipParser04._DATA.offset = AnimationClipParser04._reader.getUint32();
  1575. AnimationClipParser04._DATA.size = AnimationClipParser04._reader.getUint32();
  1576. }
  1577. static READ_BLOCK() {
  1578. var count = AnimationClipParser04._BLOCK.count = AnimationClipParser04._reader.getUint16();
  1579. var blockStarts = AnimationClipParser04._BLOCK.blockStarts = [];
  1580. var blockLengths = AnimationClipParser04._BLOCK.blockLengths = [];
  1581. for (var i = 0; i < count; i++) {
  1582. blockStarts.push(AnimationClipParser04._reader.getUint32());
  1583. blockLengths.push(AnimationClipParser04._reader.getUint32());
  1584. }
  1585. }
  1586. static READ_STRINGS() {
  1587. var offset = AnimationClipParser04._reader.getUint32();
  1588. var count = AnimationClipParser04._reader.getUint16();
  1589. var prePos = AnimationClipParser04._reader.pos;
  1590. AnimationClipParser04._reader.pos = offset + AnimationClipParser04._DATA.offset;
  1591. for (var i = 0; i < count; i++)
  1592. AnimationClipParser04._strings[i] = AnimationClipParser04._reader.readUTFString();
  1593. AnimationClipParser04._reader.pos = prePos;
  1594. }
  1595. static parse(clip, reader, version) {
  1596. AnimationClipParser04._animationClip = clip;
  1597. AnimationClipParser04._reader = reader;
  1598. AnimationClipParser04._version = version;
  1599. AnimationClipParser04.READ_DATA();
  1600. AnimationClipParser04.READ_BLOCK();
  1601. AnimationClipParser04.READ_STRINGS();
  1602. for (var i = 0, n = AnimationClipParser04._BLOCK.count; i < n; i++) {
  1603. var index = reader.getUint16();
  1604. var blockName = AnimationClipParser04._strings[index];
  1605. var fn = AnimationClipParser04["READ_" + blockName];
  1606. if (fn == null)
  1607. throw new Error("model file err,no this function:" + index + " " + blockName);
  1608. else
  1609. fn.call(null);
  1610. }
  1611. AnimationClipParser04._version = null;
  1612. AnimationClipParser04._reader = null;
  1613. AnimationClipParser04._animationClip = null;
  1614. }
  1615. static READ_ANIMATIONS() {
  1616. var i, j;
  1617. var node;
  1618. var reader = AnimationClipParser04._reader;
  1619. var buffer = reader.__getBuffer();
  1620. var startTimeTypes = [];
  1621. var startTimeTypeCount = reader.getUint16();
  1622. startTimeTypes.length = startTimeTypeCount;
  1623. for (i = 0; i < startTimeTypeCount; i++)
  1624. startTimeTypes[i] = reader.getFloat32();
  1625. var clip = AnimationClipParser04._animationClip;
  1626. clip.name = AnimationClipParser04._strings[reader.getUint16()];
  1627. var clipDur = clip._duration = reader.getFloat32();
  1628. clip.islooping = !!reader.getByte();
  1629. clip._frameRate = reader.getInt16();
  1630. var nodeCount = reader.getInt16();
  1631. var nodes = clip._nodes;
  1632. nodes.count = nodeCount;
  1633. var nodesMap = clip._nodesMap = {};
  1634. var nodesDic = clip._nodesDic = {};
  1635. for (i = 0; i < nodeCount; i++) {
  1636. node = new KeyframeNode();
  1637. nodes.setNodeByIndex(i, node);
  1638. node._indexInList = i;
  1639. var type = node.type = reader.getUint8();
  1640. var pathLength = reader.getUint16();
  1641. node._setOwnerPathCount(pathLength);
  1642. for (j = 0; j < pathLength; j++)
  1643. node._setOwnerPathByIndex(j, AnimationClipParser04._strings[reader.getUint16()]);
  1644. var nodePath = node._joinOwnerPath("/");
  1645. var mapArray = nodesMap[nodePath];
  1646. (mapArray) || (nodesMap[nodePath] = mapArray = []);
  1647. mapArray.push(node);
  1648. node.propertyOwner = AnimationClipParser04._strings[reader.getUint16()];
  1649. var propertyLength = reader.getUint16();
  1650. node._setPropertyCount(propertyLength);
  1651. for (j = 0; j < propertyLength; j++)
  1652. node._setPropertyByIndex(j, AnimationClipParser04._strings[reader.getUint16()]);
  1653. var fullPath = nodePath + "." + node.propertyOwner + "." + node._joinProperty(".");
  1654. nodesDic[fullPath] = node;
  1655. node.fullPath = fullPath;
  1656. var keyframeCount = reader.getUint16();
  1657. node._setKeyframeCount(keyframeCount);
  1658. var startTime;
  1659. switch (AnimationClipParser04._version) {
  1660. case "LAYAANIMATION:04":
  1661. for (j = 0; j < keyframeCount; j++) {
  1662. switch (type) {
  1663. case 0:
  1664. var floatKeyframe = new FloatKeyframe();
  1665. node._setKeyframeByIndex(j, floatKeyframe);
  1666. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  1667. floatKeyframe.inTangent = reader.getFloat32();
  1668. floatKeyframe.outTangent = reader.getFloat32();
  1669. floatKeyframe.value = reader.getFloat32();
  1670. break;
  1671. case 1:
  1672. case 3:
  1673. case 4:
  1674. var floatArrayKeyframe = new Vector3Keyframe();
  1675. node._setKeyframeByIndex(j, floatArrayKeyframe);
  1676. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  1677. if (Laya.Render.supportWebGLPlusAnimation) {
  1678. var data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  1679. for (var k = 0; k < 3; k++)
  1680. data[k] = reader.getFloat32();
  1681. for (k = 0; k < 3; k++)
  1682. data[3 + k] = reader.getFloat32();
  1683. for (k = 0; k < 3; k++)
  1684. data[6 + k] = reader.getFloat32();
  1685. }
  1686. else {
  1687. var inTangent = floatArrayKeyframe.inTangent;
  1688. var outTangent = floatArrayKeyframe.outTangent;
  1689. var value = floatArrayKeyframe.value;
  1690. inTangent.x = reader.getFloat32();
  1691. inTangent.y = reader.getFloat32();
  1692. inTangent.z = reader.getFloat32();
  1693. outTangent.x = reader.getFloat32();
  1694. outTangent.y = reader.getFloat32();
  1695. outTangent.z = reader.getFloat32();
  1696. value.x = reader.getFloat32();
  1697. value.y = reader.getFloat32();
  1698. value.z = reader.getFloat32();
  1699. }
  1700. break;
  1701. case 2:
  1702. var quaternionKeyframe = new QuaternionKeyframe();
  1703. node._setKeyframeByIndex(j, quaternionKeyframe);
  1704. startTime = quaternionKeyframe.time = startTimeTypes[reader.getUint16()];
  1705. if (Laya.Render.supportWebGLPlusAnimation) {
  1706. data = quaternionKeyframe.data = new Float32Array(3 * 4);
  1707. for (k = 0; k < 4; k++)
  1708. data[k] = reader.getFloat32();
  1709. for (k = 0; k < 4; k++)
  1710. data[4 + k] = reader.getFloat32();
  1711. for (k = 0; k < 4; k++)
  1712. data[8 + k] = reader.getFloat32();
  1713. }
  1714. else {
  1715. var inTangentQua = quaternionKeyframe.inTangent;
  1716. var outTangentQua = quaternionKeyframe.outTangent;
  1717. var valueQua = quaternionKeyframe.value;
  1718. inTangentQua.x = reader.getFloat32();
  1719. inTangentQua.y = reader.getFloat32();
  1720. inTangentQua.z = reader.getFloat32();
  1721. inTangentQua.w = reader.getFloat32();
  1722. outTangentQua.x = reader.getFloat32();
  1723. outTangentQua.y = reader.getFloat32();
  1724. outTangentQua.z = reader.getFloat32();
  1725. outTangentQua.w = reader.getFloat32();
  1726. valueQua.x = reader.getFloat32();
  1727. valueQua.y = reader.getFloat32();
  1728. valueQua.z = reader.getFloat32();
  1729. valueQua.w = reader.getFloat32();
  1730. }
  1731. break;
  1732. default:
  1733. throw "AnimationClipParser04:unknown type.";
  1734. }
  1735. }
  1736. break;
  1737. case "LAYAANIMATION:COMPRESSION_04":
  1738. for (j = 0; j < keyframeCount; j++) {
  1739. switch (type) {
  1740. case 0:
  1741. floatKeyframe = new FloatKeyframe();
  1742. node._setKeyframeByIndex(j, floatKeyframe);
  1743. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  1744. floatKeyframe.inTangent = HalfFloatUtils.convertToNumber(reader.getUint16());
  1745. floatKeyframe.outTangent = HalfFloatUtils.convertToNumber(reader.getUint16());
  1746. floatKeyframe.value = HalfFloatUtils.convertToNumber(reader.getUint16());
  1747. break;
  1748. case 1:
  1749. case 3:
  1750. case 4:
  1751. floatArrayKeyframe = new Vector3Keyframe();
  1752. node._setKeyframeByIndex(j, floatArrayKeyframe);
  1753. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  1754. if (Laya.Render.supportWebGLPlusAnimation) {
  1755. data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  1756. for (k = 0; k < 3; k++)
  1757. data[k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  1758. for (k = 0; k < 3; k++)
  1759. data[3 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  1760. for (k = 0; k < 3; k++)
  1761. data[6 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  1762. }
  1763. else {
  1764. inTangent = floatArrayKeyframe.inTangent;
  1765. outTangent = floatArrayKeyframe.outTangent;
  1766. value = floatArrayKeyframe.value;
  1767. inTangent.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  1768. inTangent.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  1769. inTangent.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  1770. outTangent.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  1771. outTangent.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  1772. outTangent.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  1773. value.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  1774. value.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  1775. value.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  1776. }
  1777. break;
  1778. case 2:
  1779. quaternionKeyframe = new QuaternionKeyframe();
  1780. node._setKeyframeByIndex(j, quaternionKeyframe);
  1781. startTime = quaternionKeyframe.time = startTimeTypes[reader.getUint16()];
  1782. if (Laya.Render.supportWebGLPlusAnimation) {
  1783. data = quaternionKeyframe.data = new Float32Array(3 * 4);
  1784. for (k = 0; k < 4; k++)
  1785. data[k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  1786. for (k = 0; k < 4; k++)
  1787. data[4 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  1788. for (k = 0; k < 4; k++)
  1789. data[8 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  1790. }
  1791. else {
  1792. inTangentQua = quaternionKeyframe.inTangent;
  1793. outTangentQua = quaternionKeyframe.outTangent;
  1794. valueQua = quaternionKeyframe.value;
  1795. inTangentQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  1796. inTangentQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  1797. inTangentQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  1798. inTangentQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  1799. outTangentQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  1800. outTangentQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  1801. outTangentQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  1802. outTangentQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  1803. valueQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  1804. valueQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  1805. valueQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  1806. valueQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  1807. }
  1808. break;
  1809. default:
  1810. throw "AnimationClipParser04:unknown type.";
  1811. }
  1812. }
  1813. break;
  1814. }
  1815. }
  1816. var eventCount = reader.getUint16();
  1817. for (i = 0; i < eventCount; i++) {
  1818. var event = new AnimationEvent();
  1819. event.time = Math.min(clipDur, reader.getFloat32());
  1820. event.eventName = AnimationClipParser04._strings[reader.getUint16()];
  1821. var params;
  1822. var paramCount = reader.getUint16();
  1823. (paramCount > 0) && (event.params = params = []);
  1824. for (j = 0; j < paramCount; j++) {
  1825. var eventType = reader.getByte();
  1826. switch (eventType) {
  1827. case 0:
  1828. params.push(!!reader.getByte());
  1829. break;
  1830. case 1:
  1831. params.push(reader.getInt32());
  1832. break;
  1833. case 2:
  1834. params.push(reader.getFloat32());
  1835. break;
  1836. case 3:
  1837. params.push(AnimationClipParser04._strings[reader.getUint16()]);
  1838. break;
  1839. default:
  1840. throw new Error("unknown type.");
  1841. }
  1842. }
  1843. clip.addEvent(event);
  1844. }
  1845. }
  1846. }
  1847. AnimationClipParser04._strings = [];
  1848. AnimationClipParser04._BLOCK = { count: 0 };
  1849. AnimationClipParser04._DATA = { offset: 0, size: 0 };
  1850. class KeyframeNodeList {
  1851. constructor() {
  1852. this._nodes = [];
  1853. }
  1854. get count() {
  1855. return this._nodes.length;
  1856. }
  1857. set count(value) {
  1858. this._nodes.length = value;
  1859. }
  1860. getNodeByIndex(index) {
  1861. return this._nodes[index];
  1862. }
  1863. setNodeByIndex(index, node) {
  1864. this._nodes[index] = node;
  1865. }
  1866. }
  1867. class TextureGenerator {
  1868. constructor() {
  1869. }
  1870. static lightAttenTexture(x, y, maxX, maxY, index, data) {
  1871. var sqrRange = x / maxX;
  1872. var atten = 1.0 / (1.0 + 25.0 * sqrRange);
  1873. if (sqrRange >= 0.64) {
  1874. if (sqrRange > 1.0) {
  1875. atten = 0;
  1876. }
  1877. else {
  1878. atten *= 1 - (sqrRange - 0.64) / (1 - 0.64);
  1879. }
  1880. }
  1881. data[index] = Math.floor(atten * 255.0 + 0.5);
  1882. }
  1883. static haloTexture(x, y, maxX, maxY, index, data) {
  1884. maxX >>= 1;
  1885. maxY >>= 1;
  1886. var xFac = (x - maxX) / maxX;
  1887. var yFac = (y - maxY) / maxY;
  1888. var sqrRange = xFac * xFac + yFac * yFac;
  1889. if (sqrRange > 1.0) {
  1890. sqrRange = 1.0;
  1891. }
  1892. data[index] = Math.floor((1.0 - sqrRange) * 255.0 + 0.5);
  1893. }
  1894. static _generateTexture2D(texture, textureWidth, textureHeight, func) {
  1895. var index = 0;
  1896. var size = 0;
  1897. switch (texture.format) {
  1898. case Laya.TextureFormat.R8G8B8:
  1899. size = 3;
  1900. break;
  1901. case Laya.TextureFormat.R8G8B8A8:
  1902. size = 4;
  1903. break;
  1904. case Laya.TextureFormat.Alpha8:
  1905. size = 1;
  1906. break;
  1907. default:
  1908. throw "GeneratedTexture._generateTexture: unkonw texture format.";
  1909. }
  1910. var data = new Uint8Array(textureWidth * textureHeight * size);
  1911. for (var y = 0; y < textureHeight; y++) {
  1912. for (var x = 0; x < textureWidth; x++) {
  1913. func(x, y, textureWidth, textureHeight, index, data);
  1914. index += size;
  1915. }
  1916. }
  1917. texture.setPixels(data);
  1918. }
  1919. }
  1920. class Physics3D {
  1921. }
  1922. Physics3D._bullet = null;
  1923. Physics3D._enablePhysics = false;
  1924. class Utils3D {
  1925. static _createFloatTextureBuffer(width, height) {
  1926. var floatTex = new Laya.Texture2D(width, height, Laya.TextureFormat.R32G32B32A32, false, false);
  1927. floatTex.filterMode = Laya.BaseTexture.FILTERMODE_POINT;
  1928. floatTex.wrapModeU = Laya.BaseTexture.WARPMODE_CLAMP;
  1929. floatTex.wrapModeV = Laya.BaseTexture.WARPMODE_CLAMP;
  1930. floatTex.anisoLevel = 0;
  1931. return floatTex;
  1932. }
  1933. static _convertToLayaVec3(bVector, out, inverseX) {
  1934. var bullet = Physics3D._bullet;
  1935. out.x = inverseX ? -bullet.btVector3_x(bVector) : bullet.btVector3_x(bVector);
  1936. out.y = bullet.btVector3_y(bVector);
  1937. out.z = bullet.btVector3_z(bVector);
  1938. }
  1939. static _convertToBulletVec3(lVector, out, inverseX) {
  1940. Physics3D._bullet.btVector3_setValue(out, inverseX ? -lVector.x : lVector.x, lVector.y, lVector.z);
  1941. }
  1942. static _rotationTransformScaleSkinAnimation(tx, ty, tz, qx, qy, qz, qw, sx, sy, sz, outArray, outOffset) {
  1943. var re = Utils3D._tempArray16_0;
  1944. var se = Utils3D._tempArray16_1;
  1945. var tse = Utils3D._tempArray16_2;
  1946. var x2 = qx + qx;
  1947. var y2 = qy + qy;
  1948. var z2 = qz + qz;
  1949. var xx = qx * x2;
  1950. var yx = qy * x2;
  1951. var yy = qy * y2;
  1952. var zx = qz * x2;
  1953. var zy = qz * y2;
  1954. var zz = qz * z2;
  1955. var wx = qw * x2;
  1956. var wy = qw * y2;
  1957. var wz = qw * z2;
  1958. re[15] = 1;
  1959. re[0] = 1 - yy - zz;
  1960. re[1] = yx + wz;
  1961. re[2] = zx - wy;
  1962. re[4] = yx - wz;
  1963. re[5] = 1 - xx - zz;
  1964. re[6] = zy + wx;
  1965. re[8] = zx + wy;
  1966. re[9] = zy - wx;
  1967. re[10] = 1 - xx - yy;
  1968. se[15] = 1;
  1969. se[0] = sx;
  1970. se[5] = sy;
  1971. se[10] = sz;
  1972. var i, ai0, ai1, ai2, ai3;
  1973. for (i = 0; i < 4; i++) {
  1974. ai0 = re[i];
  1975. ai1 = re[i + 4];
  1976. ai2 = re[i + 8];
  1977. ai3 = re[i + 12];
  1978. tse[i] = ai0;
  1979. tse[i + 4] = ai1;
  1980. tse[i + 8] = ai2;
  1981. tse[i + 12] = ai0 * tx + ai1 * ty + ai2 * tz + ai3;
  1982. }
  1983. for (i = 0; i < 4; i++) {
  1984. ai0 = tse[i];
  1985. ai1 = tse[i + 4];
  1986. ai2 = tse[i + 8];
  1987. ai3 = tse[i + 12];
  1988. outArray[i + outOffset] = ai0 * se[0] + ai1 * se[1] + ai2 * se[2] + ai3 * se[3];
  1989. outArray[i + outOffset + 4] = ai0 * se[4] + ai1 * se[5] + ai2 * se[6] + ai3 * se[7];
  1990. outArray[i + outOffset + 8] = ai0 * se[8] + ai1 * se[9] + ai2 * se[10] + ai3 * se[11];
  1991. outArray[i + outOffset + 12] = ai0 * se[12] + ai1 * se[13] + ai2 * se[14] + ai3 * se[15];
  1992. }
  1993. }
  1994. static _computeBoneAndAnimationDatasByBindPoseMatrxix(bones, curData, inverGlobalBindPose, outBonesDatas, outAnimationDatas, boneIndexToMesh) {
  1995. var offset = 0;
  1996. var matOffset = 0;
  1997. var i;
  1998. var parentOffset;
  1999. var boneLength = bones.length;
  2000. for (i = 0; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++) {
  2001. Utils3D._rotationTransformScaleSkinAnimation(curData[offset + 0], curData[offset + 1], curData[offset + 2], curData[offset + 3], curData[offset + 4], curData[offset + 5], curData[offset + 6], curData[offset + 7], curData[offset + 8], curData[offset + 9], outBonesDatas, matOffset);
  2002. if (i != 0) {
  2003. parentOffset = bones[i].parentIndex * 16;
  2004. Utils3D.mulMatrixByArray(outBonesDatas, parentOffset, outBonesDatas, matOffset, outBonesDatas, matOffset);
  2005. }
  2006. }
  2007. var n = inverGlobalBindPose.length;
  2008. for (i = 0; i < n; i++) {
  2009. Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas, boneIndexToMesh[i] * 16, inverGlobalBindPose[i], outAnimationDatas, i * 16);
  2010. }
  2011. }
  2012. static _computeAnimationDatasByArrayAndMatrixFast(inverGlobalBindPose, bonesDatas, outAnimationDatas, boneIndexToMesh) {
  2013. for (var i = 0, n = inverGlobalBindPose.length; i < n; i++)
  2014. Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas, boneIndexToMesh[i] * 16, inverGlobalBindPose[i], outAnimationDatas, i * 16);
  2015. }
  2016. static _computeBoneAndAnimationDatasByBindPoseMatrxixOld(bones, curData, inverGlobalBindPose, outBonesDatas, outAnimationDatas) {
  2017. var offset = 0;
  2018. var matOffset = 0;
  2019. var i;
  2020. var parentOffset;
  2021. var boneLength = bones.length;
  2022. for (i = 0; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++) {
  2023. Utils3D._rotationTransformScaleSkinAnimation(curData[offset + 7], curData[offset + 8], curData[offset + 9], curData[offset + 3], curData[offset + 4], curData[offset + 5], curData[offset + 6], curData[offset + 0], curData[offset + 1], curData[offset + 2], outBonesDatas, matOffset);
  2024. if (i != 0) {
  2025. parentOffset = bones[i].parentIndex * 16;
  2026. Utils3D.mulMatrixByArray(outBonesDatas, parentOffset, outBonesDatas, matOffset, outBonesDatas, matOffset);
  2027. }
  2028. }
  2029. var n = inverGlobalBindPose.length;
  2030. for (i = 0; i < n; i++) {
  2031. var arrayOffset = i * 16;
  2032. Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas, arrayOffset, inverGlobalBindPose[i], outAnimationDatas, arrayOffset);
  2033. }
  2034. }
  2035. static _computeAnimationDatasByArrayAndMatrixFastOld(inverGlobalBindPose, bonesDatas, outAnimationDatas) {
  2036. var n = inverGlobalBindPose.length;
  2037. for (var i = 0; i < n; i++) {
  2038. var arrayOffset = i * 16;
  2039. Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas, arrayOffset, inverGlobalBindPose[i], outAnimationDatas, arrayOffset);
  2040. }
  2041. }
  2042. static _computeRootAnimationData(bones, curData, animationDatas) {
  2043. for (var i = 0, offset = 0, matOffset = 0, boneLength = bones.length; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++)
  2044. Utils3D.createAffineTransformationArray(curData[offset + 0], curData[offset + 1], curData[offset + 2], curData[offset + 3], curData[offset + 4], curData[offset + 5], curData[offset + 6], curData[offset + 7], curData[offset + 8], curData[offset + 9], animationDatas, matOffset);
  2045. }
  2046. static transformVector3ArrayByQuat(sourceArray, sourceOffset, rotation, outArray, outOffset) {
  2047. var x = sourceArray[sourceOffset], y = sourceArray[sourceOffset + 1], z = sourceArray[sourceOffset + 2], qx = rotation.x, qy = rotation.y, qz = rotation.z, qw = rotation.w, ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  2048. outArray[outOffset] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2049. outArray[outOffset + 1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2050. outArray[outOffset + 2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2051. }
  2052. static mulMatrixByArray(leftArray, leftOffset, rightArray, rightOffset, outArray, outOffset) {
  2053. var i, ai0, ai1, ai2, ai3;
  2054. if (outArray === rightArray) {
  2055. rightArray = Utils3D._tempArray16_3;
  2056. for (i = 0; i < 16; ++i) {
  2057. rightArray[i] = outArray[outOffset + i];
  2058. }
  2059. rightOffset = 0;
  2060. }
  2061. for (i = 0; i < 4; i++) {
  2062. ai0 = leftArray[leftOffset + i];
  2063. ai1 = leftArray[leftOffset + i + 4];
  2064. ai2 = leftArray[leftOffset + i + 8];
  2065. ai3 = leftArray[leftOffset + i + 12];
  2066. outArray[outOffset + i] = ai0 * rightArray[rightOffset + 0] + ai1 * rightArray[rightOffset + 1] + ai2 * rightArray[rightOffset + 2] + ai3 * rightArray[rightOffset + 3];
  2067. outArray[outOffset + i + 4] = ai0 * rightArray[rightOffset + 4] + ai1 * rightArray[rightOffset + 5] + ai2 * rightArray[rightOffset + 6] + ai3 * rightArray[rightOffset + 7];
  2068. outArray[outOffset + i + 8] = ai0 * rightArray[rightOffset + 8] + ai1 * rightArray[rightOffset + 9] + ai2 * rightArray[rightOffset + 10] + ai3 * rightArray[rightOffset + 11];
  2069. outArray[outOffset + i + 12] = ai0 * rightArray[rightOffset + 12] + ai1 * rightArray[rightOffset + 13] + ai2 * rightArray[rightOffset + 14] + ai3 * rightArray[rightOffset + 15];
  2070. }
  2071. }
  2072. static mulMatrixByArrayFast(leftArray, leftOffset, rightArray, rightOffset, outArray, outOffset) {
  2073. var i, ai0, ai1, ai2, ai3;
  2074. for (i = 0; i < 4; i++) {
  2075. ai0 = leftArray[leftOffset + i];
  2076. ai1 = leftArray[leftOffset + i + 4];
  2077. ai2 = leftArray[leftOffset + i + 8];
  2078. ai3 = leftArray[leftOffset + i + 12];
  2079. outArray[outOffset + i] = ai0 * rightArray[rightOffset + 0] + ai1 * rightArray[rightOffset + 1] + ai2 * rightArray[rightOffset + 2] + ai3 * rightArray[rightOffset + 3];
  2080. outArray[outOffset + i + 4] = ai0 * rightArray[rightOffset + 4] + ai1 * rightArray[rightOffset + 5] + ai2 * rightArray[rightOffset + 6] + ai3 * rightArray[rightOffset + 7];
  2081. outArray[outOffset + i + 8] = ai0 * rightArray[rightOffset + 8] + ai1 * rightArray[rightOffset + 9] + ai2 * rightArray[rightOffset + 10] + ai3 * rightArray[rightOffset + 11];
  2082. outArray[outOffset + i + 12] = ai0 * rightArray[rightOffset + 12] + ai1 * rightArray[rightOffset + 13] + ai2 * rightArray[rightOffset + 14] + ai3 * rightArray[rightOffset + 15];
  2083. }
  2084. }
  2085. static mulMatrixByArrayAndMatrixFast(leftArray, leftOffset, rightMatrix, outArray, outOffset) {
  2086. var i, ai0, ai1, ai2, ai3;
  2087. var rightMatrixE = rightMatrix.elements;
  2088. var m11 = rightMatrixE[0], m12 = rightMatrixE[1], m13 = rightMatrixE[2], m14 = rightMatrixE[3];
  2089. var m21 = rightMatrixE[4], m22 = rightMatrixE[5], m23 = rightMatrixE[6], m24 = rightMatrixE[7];
  2090. var m31 = rightMatrixE[8], m32 = rightMatrixE[9], m33 = rightMatrixE[10], m34 = rightMatrixE[11];
  2091. var m41 = rightMatrixE[12], m42 = rightMatrixE[13], m43 = rightMatrixE[14], m44 = rightMatrixE[15];
  2092. var ai0LeftOffset = leftOffset;
  2093. var ai1LeftOffset = leftOffset + 4;
  2094. var ai2LeftOffset = leftOffset + 8;
  2095. var ai3LeftOffset = leftOffset + 12;
  2096. var ai0OutOffset = outOffset;
  2097. var ai1OutOffset = outOffset + 4;
  2098. var ai2OutOffset = outOffset + 8;
  2099. var ai3OutOffset = outOffset + 12;
  2100. for (i = 0; i < 4; i++) {
  2101. ai0 = leftArray[ai0LeftOffset + i];
  2102. ai1 = leftArray[ai1LeftOffset + i];
  2103. ai2 = leftArray[ai2LeftOffset + i];
  2104. ai3 = leftArray[ai3LeftOffset + i];
  2105. outArray[ai0OutOffset + i] = ai0 * m11 + ai1 * m12 + ai2 * m13 + ai3 * m14;
  2106. outArray[ai1OutOffset + i] = ai0 * m21 + ai1 * m22 + ai2 * m23 + ai3 * m24;
  2107. outArray[ai2OutOffset + i] = ai0 * m31 + ai1 * m32 + ai2 * m33 + ai3 * m34;
  2108. outArray[ai3OutOffset + i] = ai0 * m41 + ai1 * m42 + ai2 * m43 + ai3 * m44;
  2109. }
  2110. }
  2111. static createAffineTransformationArray(tX, tY, tZ, rX, rY, rZ, rW, sX, sY, sZ, outArray, outOffset) {
  2112. var x2 = rX + rX, y2 = rY + rY, z2 = rZ + rZ;
  2113. var xx = rX * x2, xy = rX * y2, xz = rX * z2, yy = rY * y2, yz = rY * z2, zz = rZ * z2;
  2114. var wx = rW * x2, wy = rW * y2, wz = rW * z2;
  2115. outArray[outOffset + 0] = (1 - (yy + zz)) * sX;
  2116. outArray[outOffset + 1] = (xy + wz) * sX;
  2117. outArray[outOffset + 2] = (xz - wy) * sX;
  2118. outArray[outOffset + 3] = 0;
  2119. outArray[outOffset + 4] = (xy - wz) * sY;
  2120. outArray[outOffset + 5] = (1 - (xx + zz)) * sY;
  2121. outArray[outOffset + 6] = (yz + wx) * sY;
  2122. outArray[outOffset + 7] = 0;
  2123. outArray[outOffset + 8] = (xz + wy) * sZ;
  2124. outArray[outOffset + 9] = (yz - wx) * sZ;
  2125. outArray[outOffset + 10] = (1 - (xx + yy)) * sZ;
  2126. outArray[outOffset + 11] = 0;
  2127. outArray[outOffset + 12] = tX;
  2128. outArray[outOffset + 13] = tY;
  2129. outArray[outOffset + 14] = tZ;
  2130. outArray[outOffset + 15] = 1;
  2131. }
  2132. static transformVector3ArrayToVector3ArrayCoordinate(source, sourceOffset, transform, result, resultOffset) {
  2133. var coordinateX = source[sourceOffset + 0];
  2134. var coordinateY = source[sourceOffset + 1];
  2135. var coordinateZ = source[sourceOffset + 2];
  2136. var transformElem = transform.elements;
  2137. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  2138. result[resultOffset] = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  2139. result[resultOffset + 1] = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  2140. result[resultOffset + 2] = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  2141. }
  2142. static transformVector3ArrayToVector3ArrayNormal(source, sourceOffset, transform, result, resultOffset) {
  2143. var coordinateX = source[sourceOffset + 0];
  2144. var coordinateY = source[sourceOffset + 1];
  2145. var coordinateZ = source[sourceOffset + 2];
  2146. var transformElem = transform.elements;
  2147. result[resultOffset] = coordinateX * transformElem[0] + coordinateY * transformElem[4] + coordinateZ * transformElem[8];
  2148. result[resultOffset + 1] = coordinateX * transformElem[1] + coordinateY * transformElem[5] + coordinateZ * transformElem[9];
  2149. result[resultOffset + 2] = coordinateX * transformElem[2] + coordinateY * transformElem[6] + coordinateZ * transformElem[10];
  2150. }
  2151. static transformLightingMapTexcoordArray(source, sourceOffset, lightingMapScaleOffset, result, resultOffset) {
  2152. result[resultOffset + 0] = source[sourceOffset + 0] * lightingMapScaleOffset.x + lightingMapScaleOffset.z;
  2153. result[resultOffset + 1] = 1.0 - ((1.0 - source[sourceOffset + 1]) * lightingMapScaleOffset.y + lightingMapScaleOffset.w);
  2154. }
  2155. static getURLVerion(url) {
  2156. var index = url.indexOf("?");
  2157. return index >= 0 ? url.substr(index) : null;
  2158. }
  2159. static _createAffineTransformationArray(trans, rot, scale, outE) {
  2160. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  2161. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  2162. var wx = w * x2, wy = w * y2, wz = w * z2, sx = scale.x, sy = scale.y, sz = scale.z;
  2163. outE[0] = (1 - (yy + zz)) * sx;
  2164. outE[1] = (xy + wz) * sx;
  2165. outE[2] = (xz - wy) * sx;
  2166. outE[3] = 0;
  2167. outE[4] = (xy - wz) * sy;
  2168. outE[5] = (1 - (xx + zz)) * sy;
  2169. outE[6] = (yz + wx) * sy;
  2170. outE[7] = 0;
  2171. outE[8] = (xz + wy) * sz;
  2172. outE[9] = (yz - wx) * sz;
  2173. outE[10] = (1 - (xx + yy)) * sz;
  2174. outE[11] = 0;
  2175. outE[12] = trans.x;
  2176. outE[13] = trans.y;
  2177. outE[14] = trans.z;
  2178. outE[15] = 1;
  2179. }
  2180. static _mulMatrixArray(leftMatrixE, rightMatrix, outArray, outOffset) {
  2181. var i, ai0, ai1, ai2, ai3;
  2182. var rightMatrixE = rightMatrix.elements;
  2183. var m11 = rightMatrixE[0], m12 = rightMatrixE[1], m13 = rightMatrixE[2], m14 = rightMatrixE[3];
  2184. var m21 = rightMatrixE[4], m22 = rightMatrixE[5], m23 = rightMatrixE[6], m24 = rightMatrixE[7];
  2185. var m31 = rightMatrixE[8], m32 = rightMatrixE[9], m33 = rightMatrixE[10], m34 = rightMatrixE[11];
  2186. var m41 = rightMatrixE[12], m42 = rightMatrixE[13], m43 = rightMatrixE[14], m44 = rightMatrixE[15];
  2187. var ai0OutOffset = outOffset;
  2188. var ai1OutOffset = outOffset + 4;
  2189. var ai2OutOffset = outOffset + 8;
  2190. var ai3OutOffset = outOffset + 12;
  2191. for (i = 0; i < 4; i++) {
  2192. ai0 = leftMatrixE[i];
  2193. ai1 = leftMatrixE[i + 4];
  2194. ai2 = leftMatrixE[i + 8];
  2195. ai3 = leftMatrixE[i + 12];
  2196. outArray[ai0OutOffset + i] = ai0 * m11 + ai1 * m12 + ai2 * m13 + ai3 * m14;
  2197. outArray[ai1OutOffset + i] = ai0 * m21 + ai1 * m22 + ai2 * m23 + ai3 * m24;
  2198. outArray[ai2OutOffset + i] = ai0 * m31 + ai1 * m32 + ai2 * m33 + ai3 * m34;
  2199. outArray[ai3OutOffset + i] = ai0 * m41 + ai1 * m42 + ai2 * m43 + ai3 * m44;
  2200. }
  2201. }
  2202. static arcTanAngle(x, y) {
  2203. if (x == 0) {
  2204. if (y == 1)
  2205. return Math.PI / 2;
  2206. return -Math.PI / 2;
  2207. }
  2208. if (x > 0)
  2209. return Math.atan(y / x);
  2210. if (x < 0) {
  2211. if (y > 0)
  2212. return Math.atan(y / x) + Math.PI;
  2213. return Math.atan(y / x) - Math.PI;
  2214. }
  2215. return 0;
  2216. }
  2217. static angleTo(from, location, angle) {
  2218. Vector3.subtract(location, from, Quaternion.TEMPVector30);
  2219. Vector3.normalize(Quaternion.TEMPVector30, Quaternion.TEMPVector30);
  2220. angle.x = Math.asin(Quaternion.TEMPVector30.y);
  2221. angle.y = Utils3D.arcTanAngle(-Quaternion.TEMPVector30.z, -Quaternion.TEMPVector30.x);
  2222. }
  2223. static transformQuat(source, rotation, out) {
  2224. var re = rotation;
  2225. var x = source.x, y = source.y, z = source.z, qx = re[0], qy = re[1], qz = re[2], qw = re[3], ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  2226. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2227. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2228. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2229. }
  2230. static quaternionWeight(f, weight, e) {
  2231. e.x = f.x * weight;
  2232. e.y = f.y * weight;
  2233. e.z = f.z * weight;
  2234. e.w = f.w;
  2235. }
  2236. static quaternionConjugate(value, result) {
  2237. result.x = -value.x;
  2238. result.y = -value.y;
  2239. result.z = -value.z;
  2240. result.w = value.w;
  2241. }
  2242. static scaleWeight(s, w, out) {
  2243. var sX = s.x, sY = s.y, sZ = s.z;
  2244. out.x = sX > 0 ? Math.pow(Math.abs(sX), w) : -Math.pow(Math.abs(sX), w);
  2245. out.y = sY > 0 ? Math.pow(Math.abs(sY), w) : -Math.pow(Math.abs(sY), w);
  2246. out.z = sZ > 0 ? Math.pow(Math.abs(sZ), w) : -Math.pow(Math.abs(sZ), w);
  2247. }
  2248. static scaleBlend(sa, sb, w, out) {
  2249. var saw = Utils3D._tempVector3_0;
  2250. var sbw = Utils3D._tempVector3_1;
  2251. Utils3D.scaleWeight(sa, 1.0 - w, saw);
  2252. Utils3D.scaleWeight(sb, w, sbw);
  2253. var sng = w > 0.5 ? sb : sa;
  2254. out.x = sng.x > 0 ? Math.abs(saw.x * sbw.x) : -Math.abs(saw.x * sbw.x);
  2255. out.y = sng.y > 0 ? Math.abs(saw.y * sbw.y) : -Math.abs(saw.y * sbw.y);
  2256. out.z = sng.z > 0 ? Math.abs(saw.z * sbw.z) : -Math.abs(saw.z * sbw.z);
  2257. }
  2258. static matrix4x4MultiplyFFF(a, b, e) {
  2259. var i, ai0, ai1, ai2, ai3;
  2260. if (e === b) {
  2261. b = new Float32Array(16);
  2262. for (i = 0; i < 16; ++i) {
  2263. b[i] = e[i];
  2264. }
  2265. }
  2266. var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
  2267. var b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7];
  2268. var b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11];
  2269. var b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
  2270. for (i = 0; i < 4; i++) {
  2271. ai0 = a[i];
  2272. ai1 = a[i + 4];
  2273. ai2 = a[i + 8];
  2274. ai3 = a[i + 12];
  2275. e[i] = ai0 * b0 + ai1 * b1 + ai2 * b2 + ai3 * b3;
  2276. e[i + 4] = ai0 * b4 + ai1 * b5 + ai2 * b6 + ai3 * b7;
  2277. e[i + 8] = ai0 * b8 + ai1 * b9 + ai2 * b10 + ai3 * b11;
  2278. e[i + 12] = ai0 * b12 + ai1 * b13 + ai2 * b14 + ai3 * b15;
  2279. }
  2280. }
  2281. static matrix4x4MultiplyFFFForNative(a, b, e) {
  2282. Laya.LayaGL.instance.matrix4x4Multiply(a, b, e);
  2283. }
  2284. static matrix4x4MultiplyMFM(left, right, out) {
  2285. Utils3D.matrix4x4MultiplyFFF(left.elements, right, out.elements);
  2286. }
  2287. static _buildTexture2D(width, height, format, colorFunc, mipmaps = false) {
  2288. var texture = new Laya.Texture2D(width, height, format, mipmaps, true);
  2289. texture.anisoLevel = 1;
  2290. texture.filterMode = Laya.BaseTexture.FILTERMODE_POINT;
  2291. TextureGenerator._generateTexture2D(texture, width, height, colorFunc);
  2292. return texture;
  2293. }
  2294. static _drawBound(debugLine, boundBox, color) {
  2295. if (debugLine.lineCount + 12 > debugLine.maxLineCount)
  2296. debugLine.maxLineCount += 12;
  2297. var start = Utils3D._tempVector3_0;
  2298. var end = Utils3D._tempVector3_1;
  2299. var min = boundBox.min;
  2300. var max = boundBox.max;
  2301. start.setValue(min.x, min.y, min.z);
  2302. end.setValue(max.x, min.y, min.z);
  2303. debugLine.addLine(start, end, color, color);
  2304. start.setValue(min.x, min.y, min.z);
  2305. end.setValue(min.x, min.y, max.z);
  2306. debugLine.addLine(start, end, color, color);
  2307. start.setValue(max.x, min.y, min.z);
  2308. end.setValue(max.x, min.y, max.z);
  2309. debugLine.addLine(start, end, color, color);
  2310. start.setValue(min.x, min.y, max.z);
  2311. end.setValue(max.x, min.y, max.z);
  2312. debugLine.addLine(start, end, color, color);
  2313. start.setValue(min.x, min.y, min.z);
  2314. end.setValue(min.x, max.y, min.z);
  2315. debugLine.addLine(start, end, color, color);
  2316. start.setValue(min.x, min.y, max.z);
  2317. end.setValue(min.x, max.y, max.z);
  2318. debugLine.addLine(start, end, color, color);
  2319. start.setValue(max.x, min.y, min.z);
  2320. end.setValue(max.x, max.y, min.z);
  2321. debugLine.addLine(start, end, color, color);
  2322. start.setValue(max.x, min.y, max.z);
  2323. end.setValue(max.x, max.y, max.z);
  2324. debugLine.addLine(start, end, color, color);
  2325. start.setValue(min.x, max.y, min.z);
  2326. end.setValue(max.x, max.y, min.z);
  2327. debugLine.addLine(start, end, color, color);
  2328. start.setValue(min.x, max.y, min.z);
  2329. end.setValue(min.x, max.y, max.z);
  2330. debugLine.addLine(start, end, color, color);
  2331. start.setValue(max.x, max.y, min.z);
  2332. end.setValue(max.x, max.y, max.z);
  2333. debugLine.addLine(start, end, color, color);
  2334. start.setValue(min.x, max.y, max.z);
  2335. end.setValue(max.x, max.y, max.z);
  2336. debugLine.addLine(start, end, color, color);
  2337. }
  2338. static _getHierarchyPath(rootSprite, checkSprite, path) {
  2339. path.length = 0;
  2340. var sprite = checkSprite;
  2341. while (sprite !== rootSprite) {
  2342. var parent = sprite._parent;
  2343. if (parent)
  2344. path.push(parent.getChildIndex(sprite));
  2345. else
  2346. return null;
  2347. sprite = parent;
  2348. }
  2349. return path;
  2350. }
  2351. static _getNodeByHierarchyPath(rootSprite, invPath) {
  2352. var sprite = rootSprite;
  2353. for (var i = invPath.length - 1; i >= 0; i--) {
  2354. sprite = sprite.getChildAt(invPath[i]);
  2355. }
  2356. return sprite;
  2357. }
  2358. }
  2359. Utils3D._tempVector3_0 = new Vector3();
  2360. Utils3D._tempVector3_1 = new Vector3();
  2361. Utils3D._tempArray16_0 = new Float32Array(16);
  2362. Utils3D._tempArray16_1 = new Float32Array(16);
  2363. Utils3D._tempArray16_2 = new Float32Array(16);
  2364. Utils3D._tempArray16_3 = new Float32Array(16);
  2365. Utils3D._compIdToNode = new Object();
  2366. class AnimationClip extends Laya.Resource {
  2367. constructor() {
  2368. super();
  2369. this._nodes = new KeyframeNodeList();
  2370. this._animationEvents = [];
  2371. }
  2372. static _parse(data, propertyParams = null, constructParams = null) {
  2373. var clip = new AnimationClip();
  2374. var reader = new Laya.Byte(data);
  2375. var version = reader.readUTFString();
  2376. switch (version) {
  2377. case "LAYAANIMATION:03":
  2378. AnimationClipParser03.parse(clip, reader);
  2379. break;
  2380. case "LAYAANIMATION:04":
  2381. case "LAYAANIMATION:COMPRESSION_04":
  2382. AnimationClipParser04.parse(clip, reader, version);
  2383. break;
  2384. default:
  2385. throw "unknown animationClip version.";
  2386. }
  2387. return clip;
  2388. }
  2389. static load(url, complete) {
  2390. Laya.ILaya.loader.create(url, complete, null, AnimationClip.ANIMATIONCLIP);
  2391. }
  2392. duration() {
  2393. return this._duration;
  2394. }
  2395. _hermiteInterpolate(frame, nextFrame, t, dur) {
  2396. var t0 = frame.outTangent, t1 = nextFrame.inTangent;
  2397. if (Number.isFinite(t0) && Number.isFinite(t1)) {
  2398. var t2 = t * t;
  2399. var t3 = t2 * t;
  2400. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  2401. var b = t3 - 2.0 * t2 + t;
  2402. var c = t3 - t2;
  2403. var d = -2.0 * t3 + 3.0 * t2;
  2404. return a * frame.value + b * t0 * dur + c * t1 * dur + d * nextFrame.value;
  2405. }
  2406. else
  2407. return frame.value;
  2408. }
  2409. _hermiteInterpolateVector3(frame, nextFrame, t, dur, out) {
  2410. var p0 = frame.value;
  2411. var tan0 = frame.outTangent;
  2412. var p1 = nextFrame.value;
  2413. var tan1 = nextFrame.inTangent;
  2414. var t2 = t * t;
  2415. var t3 = t2 * t;
  2416. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  2417. var b = t3 - 2.0 * t2 + t;
  2418. var c = t3 - t2;
  2419. var d = -2.0 * t3 + 3.0 * t2;
  2420. var t0 = tan0.x, t1 = tan1.x;
  2421. if (Number.isFinite(t0) && Number.isFinite(t1))
  2422. out.x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x;
  2423. else
  2424. out.x = p0.x;
  2425. t0 = tan0.y, t1 = tan1.y;
  2426. if (Number.isFinite(t0) && Number.isFinite(t1))
  2427. out.y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y;
  2428. else
  2429. out.y = p0.y;
  2430. t0 = tan0.z, t1 = tan1.z;
  2431. if (Number.isFinite(t0) && Number.isFinite(t1))
  2432. out.z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z;
  2433. else
  2434. out.z = p0.z;
  2435. }
  2436. _hermiteInterpolateQuaternion(frame, nextFrame, t, dur, out) {
  2437. var p0 = frame.value;
  2438. var tan0 = frame.outTangent;
  2439. var p1 = nextFrame.value;
  2440. var tan1 = nextFrame.inTangent;
  2441. var t2 = t * t;
  2442. var t3 = t2 * t;
  2443. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  2444. var b = t3 - 2.0 * t2 + t;
  2445. var c = t3 - t2;
  2446. var d = -2.0 * t3 + 3.0 * t2;
  2447. var t0 = tan0.x, t1 = tan1.x;
  2448. if (Number.isFinite(t0) && Number.isFinite(t1))
  2449. out.x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x;
  2450. else
  2451. out.x = p0.x;
  2452. t0 = tan0.y, t1 = tan1.y;
  2453. if (Number.isFinite(t0) && Number.isFinite(t1))
  2454. out.y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y;
  2455. else
  2456. out.y = p0.y;
  2457. t0 = tan0.z, t1 = tan1.z;
  2458. if (Number.isFinite(t0) && Number.isFinite(t1))
  2459. out.z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z;
  2460. else
  2461. out.z = p0.z;
  2462. t0 = tan0.w, t1 = tan1.w;
  2463. if (Number.isFinite(t0) && Number.isFinite(t1))
  2464. out.w = a * p0.w + b * t0 * dur + c * t1 * dur + d * p1.w;
  2465. else
  2466. out.w = p0.w;
  2467. }
  2468. _evaluateClipDatasRealTime(nodes, playCurTime, realTimeCurrentFrameIndexes, addtive, frontPlay, outDatas) {
  2469. for (var i = 0, n = nodes.count; i < n; i++) {
  2470. var node = nodes.getNodeByIndex(i);
  2471. var type = node.type;
  2472. var nextFrameIndex;
  2473. var keyFrames = node._keyFrames;
  2474. var keyFramesCount = keyFrames.length;
  2475. var frameIndex = realTimeCurrentFrameIndexes[i];
  2476. if (frontPlay) {
  2477. if ((frameIndex !== -1) && (playCurTime < keyFrames[frameIndex].time)) {
  2478. frameIndex = -1;
  2479. realTimeCurrentFrameIndexes[i] = frameIndex;
  2480. }
  2481. nextFrameIndex = frameIndex + 1;
  2482. while (nextFrameIndex < keyFramesCount) {
  2483. if (keyFrames[nextFrameIndex].time > playCurTime)
  2484. break;
  2485. frameIndex++;
  2486. nextFrameIndex++;
  2487. realTimeCurrentFrameIndexes[i] = frameIndex;
  2488. }
  2489. }
  2490. else {
  2491. nextFrameIndex = frameIndex + 1;
  2492. if ((nextFrameIndex !== keyFramesCount) && (playCurTime > keyFrames[nextFrameIndex].time)) {
  2493. frameIndex = keyFramesCount - 1;
  2494. realTimeCurrentFrameIndexes[i] = frameIndex;
  2495. }
  2496. nextFrameIndex = frameIndex + 1;
  2497. while (frameIndex > -1) {
  2498. if (keyFrames[frameIndex].time < playCurTime)
  2499. break;
  2500. frameIndex--;
  2501. nextFrameIndex--;
  2502. realTimeCurrentFrameIndexes[i] = frameIndex;
  2503. }
  2504. }
  2505. var isEnd = nextFrameIndex === keyFramesCount;
  2506. switch (type) {
  2507. case 0:
  2508. if (frameIndex !== -1) {
  2509. var frame = keyFrames[frameIndex];
  2510. if (isEnd) {
  2511. outDatas[i] = frame.value;
  2512. }
  2513. else {
  2514. var nextFarme = keyFrames[nextFrameIndex];
  2515. var d = nextFarme.time - frame.time;
  2516. var t;
  2517. if (d !== 0)
  2518. t = (playCurTime - frame.time) / d;
  2519. else
  2520. t = 0;
  2521. outDatas[i] = this._hermiteInterpolate(frame, nextFarme, t, d);
  2522. }
  2523. }
  2524. else {
  2525. outDatas[i] = keyFrames[0].value;
  2526. }
  2527. if (addtive)
  2528. outDatas[i] = outDatas[i] - keyFrames[0].value;
  2529. break;
  2530. case 1:
  2531. case 4:
  2532. var clipData = outDatas[i];
  2533. this._evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipData);
  2534. if (addtive) {
  2535. var firstFrameValue = keyFrames[0].value;
  2536. clipData.x -= firstFrameValue.x;
  2537. clipData.y -= firstFrameValue.y;
  2538. clipData.z -= firstFrameValue.z;
  2539. }
  2540. break;
  2541. case 2:
  2542. var clipQuat = outDatas[i];
  2543. this._evaluateFrameNodeQuaternionDatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipQuat);
  2544. if (addtive) {
  2545. var tempQuat = AnimationClip._tempQuaternion0;
  2546. var firstFrameValueQua = keyFrames[0].value;
  2547. Utils3D.quaternionConjugate(firstFrameValueQua, tempQuat);
  2548. Quaternion.multiply(tempQuat, clipQuat, clipQuat);
  2549. }
  2550. break;
  2551. case 3:
  2552. clipData = outDatas[i];
  2553. this._evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipData);
  2554. if (addtive) {
  2555. firstFrameValue = keyFrames[0].value;
  2556. clipData.x /= firstFrameValue.x;
  2557. clipData.y /= firstFrameValue.y;
  2558. clipData.z /= firstFrameValue.z;
  2559. }
  2560. break;
  2561. default:
  2562. throw "AnimationClip:unknown node type.";
  2563. }
  2564. }
  2565. }
  2566. _evaluateClipDatasRealTimeForNative(nodes, playCurTime, realTimeCurrentFrameIndexes, addtive) {
  2567. Laya.LayaGL.instance.evaluateClipDatasRealTime(nodes._nativeObj, playCurTime, realTimeCurrentFrameIndexes, addtive);
  2568. }
  2569. _evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, outDatas) {
  2570. if (frameIndex !== -1) {
  2571. var frame = keyFrames[frameIndex];
  2572. if (isEnd) {
  2573. var frameData = frame.value;
  2574. outDatas.x = frameData.x;
  2575. outDatas.y = frameData.y;
  2576. outDatas.z = frameData.z;
  2577. }
  2578. else {
  2579. var nextKeyFrame = keyFrames[frameIndex + 1];
  2580. var t;
  2581. var startTime = frame.time;
  2582. var d = nextKeyFrame.time - startTime;
  2583. if (d !== 0)
  2584. t = (playCurTime - startTime) / d;
  2585. else
  2586. t = 0;
  2587. this._hermiteInterpolateVector3(frame, nextKeyFrame, t, d, outDatas);
  2588. }
  2589. }
  2590. else {
  2591. var firstFrameDatas = keyFrames[0].value;
  2592. outDatas.x = firstFrameDatas.x;
  2593. outDatas.y = firstFrameDatas.y;
  2594. outDatas.z = firstFrameDatas.z;
  2595. }
  2596. }
  2597. _evaluateFrameNodeQuaternionDatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, outDatas) {
  2598. if (frameIndex !== -1) {
  2599. var frame = keyFrames[frameIndex];
  2600. if (isEnd) {
  2601. var frameData = frame.value;
  2602. outDatas.x = frameData.x;
  2603. outDatas.y = frameData.y;
  2604. outDatas.z = frameData.z;
  2605. outDatas.w = frameData.w;
  2606. }
  2607. else {
  2608. var nextKeyFrame = keyFrames[frameIndex + 1];
  2609. var t;
  2610. var startTime = frame.time;
  2611. var d = nextKeyFrame.time - startTime;
  2612. if (d !== 0)
  2613. t = (playCurTime - startTime) / d;
  2614. else
  2615. t = 0;
  2616. this._hermiteInterpolateQuaternion(frame, nextKeyFrame, t, d, outDatas);
  2617. }
  2618. }
  2619. else {
  2620. var firstFrameDatas = keyFrames[0].value;
  2621. outDatas.x = firstFrameDatas.x;
  2622. outDatas.y = firstFrameDatas.y;
  2623. outDatas.z = firstFrameDatas.z;
  2624. outDatas.w = firstFrameDatas.w;
  2625. }
  2626. }
  2627. _binarySearchEventIndex(time) {
  2628. var start = 0;
  2629. var end = this._animationEvents.length - 1;
  2630. var mid;
  2631. while (start <= end) {
  2632. mid = Math.floor((start + end) / 2);
  2633. var midValue = this._animationEvents[mid].time;
  2634. if (midValue == time)
  2635. return mid;
  2636. else if (midValue > time)
  2637. end = mid - 1;
  2638. else
  2639. start = mid + 1;
  2640. }
  2641. return start;
  2642. }
  2643. addEvent(event) {
  2644. var index = this._binarySearchEventIndex(event.time);
  2645. this._animationEvents.splice(index, 0, event);
  2646. }
  2647. _disposeResource() {
  2648. this._nodes = null;
  2649. this._nodesMap = null;
  2650. }
  2651. }
  2652. AnimationClip.ANIMATIONCLIP = "ANIMATIONCLIP";
  2653. AnimationClip._tempQuaternion0 = new Quaternion();
  2654. class AnimatorPlayState {
  2655. constructor() {
  2656. this._currentState = null;
  2657. }
  2658. get normalizedTime() {
  2659. return this._normalizedTime;
  2660. }
  2661. get duration() {
  2662. return this._duration;
  2663. }
  2664. get animatorState() {
  2665. return this._currentState;
  2666. }
  2667. _resetPlayState(startTime) {
  2668. this._finish = false;
  2669. this._startPlayTime = startTime;
  2670. this._elapsedTime = startTime;
  2671. this._playEventIndex = 0;
  2672. this._lastIsFront = true;
  2673. }
  2674. _cloneTo(dest) {
  2675. dest._finish = this._finish;
  2676. dest._startPlayTime = this._startPlayTime;
  2677. dest._elapsedTime = this._elapsedTime;
  2678. dest._playEventIndex = this._playEventIndex;
  2679. dest._lastIsFront = this._lastIsFront;
  2680. }
  2681. }
  2682. class AnimatorControllerLayer {
  2683. constructor(name) {
  2684. this._defaultState = null;
  2685. this._referenceCount = 0;
  2686. this._playType = -1;
  2687. this._crossDuration = -1;
  2688. this._crossMark = 0;
  2689. this._crossNodesOwnersCount = 0;
  2690. this._crossNodesOwners = [];
  2691. this._crossNodesOwnersIndicesMap = {};
  2692. this._srcCrossClipNodeIndices = [];
  2693. this._destCrossClipNodeIndices = [];
  2694. this._statesMap = {};
  2695. this._states = [];
  2696. this._playStateInfo = new AnimatorPlayState();
  2697. this._crossPlayStateInfo = new AnimatorPlayState();
  2698. this.blendingMode = AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  2699. this.defaultWeight = 1.0;
  2700. this.playOnWake = true;
  2701. this.name = name;
  2702. }
  2703. get defaultState() {
  2704. return this._defaultState;
  2705. }
  2706. set defaultState(value) {
  2707. this._defaultState = value;
  2708. this._statesMap[value.name] = value;
  2709. }
  2710. _removeClip(clipStateInfos, statesMap, index, state) {
  2711. var clip = state._clip;
  2712. var clipStateInfo = clipStateInfos[index];
  2713. clipStateInfos.splice(index, 1);
  2714. delete statesMap[state.name];
  2715. if (this._animator) {
  2716. var frameNodes = clip._nodes;
  2717. var nodeOwners = clipStateInfo._nodeOwners;
  2718. clip._removeReference();
  2719. for (var i = 0, n = frameNodes.count; i < n; i++)
  2720. this._animator._removeKeyframeNodeOwner(nodeOwners, frameNodes.getNodeByIndex(i));
  2721. }
  2722. }
  2723. _getReferenceCount() {
  2724. return this._referenceCount;
  2725. }
  2726. _addReference(count = 1) {
  2727. for (var i = 0, n = this._states.length; i < n; i++)
  2728. this._states[i]._addReference(count);
  2729. this._referenceCount += count;
  2730. }
  2731. _removeReference(count = 1) {
  2732. for (var i = 0, n = this._states.length; i < n; i++)
  2733. this._states[i]._removeReference(count);
  2734. this._referenceCount -= count;
  2735. }
  2736. _clearReference() {
  2737. this._removeReference(-this._referenceCount);
  2738. }
  2739. getCurrentPlayState() {
  2740. return this._playStateInfo;
  2741. }
  2742. getAnimatorState(name) {
  2743. var state = this._statesMap[name];
  2744. return state ? state : null;
  2745. }
  2746. addState(state) {
  2747. var stateName = state.name;
  2748. if (this._statesMap[stateName]) {
  2749. throw "AnimatorControllerLayer:this stat's name has exist.";
  2750. }
  2751. else {
  2752. this._statesMap[stateName] = state;
  2753. this._states.push(state);
  2754. if (this._animator) {
  2755. state._clip._addReference();
  2756. this._animator._getOwnersByClip(state);
  2757. }
  2758. }
  2759. }
  2760. removeState(state) {
  2761. var states = this._states;
  2762. var index = -1;
  2763. for (var i = 0, n = states.length; i < n; i++) {
  2764. if (states[i] === state) {
  2765. index = i;
  2766. break;
  2767. }
  2768. }
  2769. if (index !== -1)
  2770. this._removeClip(states, this._statesMap, index, state);
  2771. }
  2772. destroy() {
  2773. this._clearReference();
  2774. this._statesMap = null;
  2775. this._states = null;
  2776. this._playStateInfo = null;
  2777. this._crossPlayStateInfo = null;
  2778. this._defaultState = null;
  2779. }
  2780. cloneTo(destObject) {
  2781. var dest = destObject;
  2782. dest.name = this.name;
  2783. dest.blendingMode = this.blendingMode;
  2784. dest.defaultWeight = this.defaultWeight;
  2785. dest.playOnWake = this.playOnWake;
  2786. }
  2787. clone() {
  2788. var dest = new AnimatorControllerLayer(this.name);
  2789. this.cloneTo(dest);
  2790. return dest;
  2791. }
  2792. }
  2793. AnimatorControllerLayer.BLENDINGMODE_OVERRIDE = 0;
  2794. AnimatorControllerLayer.BLENDINGMODE_ADDTIVE = 1;
  2795. class ConchVector4 {
  2796. constructor(x = 0, y = 0, z = 0, w = 0) {
  2797. var v = this.elements = new Float32Array(4);
  2798. v[0] = x;
  2799. v[1] = y;
  2800. v[2] = z;
  2801. v[3] = w;
  2802. }
  2803. get x() {
  2804. return this.elements[0];
  2805. }
  2806. set x(value) {
  2807. this.elements[0] = value;
  2808. }
  2809. get y() {
  2810. return this.elements[1];
  2811. }
  2812. set y(value) {
  2813. this.elements[1] = value;
  2814. }
  2815. get z() {
  2816. return this.elements[2];
  2817. }
  2818. set z(value) {
  2819. this.elements[2] = value;
  2820. }
  2821. get w() {
  2822. return this.elements[3];
  2823. }
  2824. set w(value) {
  2825. this.elements[3] = value;
  2826. }
  2827. fromArray(array, offset = 0) {
  2828. this.elements[0] = array[offset + 0];
  2829. this.elements[1] = array[offset + 1];
  2830. this.elements[2] = array[offset + 2];
  2831. this.elements[3] = array[offset + 3];
  2832. }
  2833. cloneTo(destObject) {
  2834. var destVector4 = destObject;
  2835. var destE = destVector4.elements;
  2836. var s = this.elements;
  2837. destE[0] = s[0];
  2838. destE[1] = s[1];
  2839. destE[2] = s[2];
  2840. destE[3] = s[3];
  2841. }
  2842. clone() {
  2843. var destVector4 = new ConchVector4();
  2844. this.cloneTo(destVector4);
  2845. return destVector4;
  2846. }
  2847. static lerp(a, b, t, out) {
  2848. var e = out.elements;
  2849. var f = a.elements;
  2850. var g = b.elements;
  2851. var ax = f[0], ay = f[1], az = f[2], aw = f[3];
  2852. e[0] = ax + t * (g[0] - ax);
  2853. e[1] = ay + t * (g[1] - ay);
  2854. e[2] = az + t * (g[2] - az);
  2855. e[3] = aw + t * (g[3] - aw);
  2856. }
  2857. static transformByM4x4(vector4, m4x4, out) {
  2858. var ve = vector4.elements;
  2859. var vx = ve[0];
  2860. var vy = ve[1];
  2861. var vz = ve[2];
  2862. var vw = ve[3];
  2863. var me = m4x4.elements;
  2864. var oe = out.elements;
  2865. oe[0] = vx * me[0] + vy * me[4] + vz * me[8] + vw * me[12];
  2866. oe[1] = vx * me[1] + vy * me[5] + vz * me[9] + vw * me[13];
  2867. oe[2] = vx * me[2] + vy * me[6] + vz * me[10] + vw * me[14];
  2868. oe[3] = vx * me[3] + vy * me[7] + vz * me[11] + vw * me[15];
  2869. }
  2870. static equals(a, b) {
  2871. var ae = a.elements;
  2872. var be = b.elements;
  2873. return MathUtils3D.nearEqual(Math.abs(ae[0]), Math.abs(be[0])) && MathUtils3D.nearEqual(Math.abs(ae[1]), Math.abs(be[1])) && MathUtils3D.nearEqual(Math.abs(ae[2]), Math.abs(be[2])) && MathUtils3D.nearEqual(Math.abs(ae[3]), Math.abs(be[3]));
  2874. }
  2875. length() {
  2876. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2877. }
  2878. lengthSquared() {
  2879. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2880. }
  2881. static normalize(s, out) {
  2882. var se = s.elements;
  2883. var oe = out.elements;
  2884. var len = s.length();
  2885. if (len > 0) {
  2886. oe[0] = se[0] * len;
  2887. oe[1] = se[1] * len;
  2888. oe[2] = se[2] * len;
  2889. oe[3] = se[3] * len;
  2890. }
  2891. }
  2892. static add(a, b, out) {
  2893. var oe = out.elements;
  2894. var ae = a.elements;
  2895. var be = b.elements;
  2896. oe[0] = ae[0] + be[0];
  2897. oe[1] = ae[1] + be[1];
  2898. oe[2] = ae[2] + be[2];
  2899. oe[3] = ae[3] + be[3];
  2900. }
  2901. static subtract(a, b, out) {
  2902. var oe = out.elements;
  2903. var ae = a.elements;
  2904. var be = b.elements;
  2905. oe[0] = ae[0] - be[0];
  2906. oe[1] = ae[1] - be[1];
  2907. oe[2] = ae[2] - be[2];
  2908. oe[3] = ae[3] - be[3];
  2909. }
  2910. static multiply(a, b, out) {
  2911. var oe = out.elements;
  2912. var ae = a.elements;
  2913. var be = b.elements;
  2914. oe[0] = ae[0] * be[0];
  2915. oe[1] = ae[1] * be[1];
  2916. oe[2] = ae[2] * be[2];
  2917. oe[3] = ae[3] * be[3];
  2918. }
  2919. static scale(a, b, out) {
  2920. var oe = out.elements;
  2921. var ae = a.elements;
  2922. oe[0] = ae[0] * b;
  2923. oe[1] = ae[1] * b;
  2924. oe[2] = ae[2] * b;
  2925. oe[3] = ae[3] * b;
  2926. }
  2927. static Clamp(value, min, max, out) {
  2928. var valuee = value.elements;
  2929. var x = valuee[0];
  2930. var y = valuee[1];
  2931. var z = valuee[2];
  2932. var w = valuee[3];
  2933. var mine = min.elements;
  2934. var mineX = mine[0];
  2935. var mineY = mine[1];
  2936. var mineZ = mine[2];
  2937. var mineW = mine[3];
  2938. var maxe = max.elements;
  2939. var maxeX = maxe[0];
  2940. var maxeY = maxe[1];
  2941. var maxeZ = maxe[2];
  2942. var maxeW = maxe[3];
  2943. var oute = out.elements;
  2944. x = (x > maxeX) ? maxeX : x;
  2945. x = (x < mineX) ? mineX : x;
  2946. y = (y > maxeY) ? maxeY : y;
  2947. y = (y < mineY) ? mineY : y;
  2948. z = (z > maxeZ) ? maxeZ : z;
  2949. z = (z < mineZ) ? mineZ : z;
  2950. w = (w > maxeW) ? maxeW : w;
  2951. w = (w < mineW) ? mineW : w;
  2952. oute[0] = x;
  2953. oute[1] = y;
  2954. oute[2] = z;
  2955. oute[3] = w;
  2956. }
  2957. static distanceSquared(value1, value2) {
  2958. var value1e = value1.elements;
  2959. var value2e = value2.elements;
  2960. var x = value1e[0] - value2e[0];
  2961. var y = value1e[1] - value2e[1];
  2962. var z = value1e[2] - value2e[2];
  2963. var w = value1e[3] - value2e[3];
  2964. return (x * x) + (y * y) + (z * z) + (w * w);
  2965. }
  2966. static distance(value1, value2) {
  2967. var value1e = value1.elements;
  2968. var value2e = value2.elements;
  2969. var x = value1e[0] - value2e[0];
  2970. var y = value1e[1] - value2e[1];
  2971. var z = value1e[2] - value2e[2];
  2972. var w = value1e[3] - value2e[3];
  2973. return Math.sqrt((x * x) + (y * y) + (z * z) + (w * w));
  2974. }
  2975. static dot(a, b) {
  2976. var ae = a.elements;
  2977. var be = b.elements;
  2978. var r = (ae[0] * be[0]) + (ae[1] * be[1]) + (ae[2] * be[2]) + (ae[3] * be[3]);
  2979. return r;
  2980. }
  2981. static min(a, b, out) {
  2982. var e = out.elements;
  2983. var f = a.elements;
  2984. var g = b.elements;
  2985. e[0] = Math.min(f[0], g[0]);
  2986. e[1] = Math.min(f[1], g[1]);
  2987. e[2] = Math.min(f[2], g[2]);
  2988. e[3] = Math.min(f[3], g[3]);
  2989. }
  2990. static max(a, b, out) {
  2991. var e = out.elements;
  2992. var f = a.elements;
  2993. var g = b.elements;
  2994. e[0] = Math.max(f[0], g[0]);
  2995. e[1] = Math.max(f[1], g[1]);
  2996. e[2] = Math.max(f[2], g[2]);
  2997. e[3] = Math.max(f[3], g[3]);
  2998. }
  2999. }
  3000. ConchVector4.ZERO = new ConchVector4();
  3001. ConchVector4.ONE = new ConchVector4(1.0, 1.0, 1.0, 1.0);
  3002. ConchVector4.UnitX = new ConchVector4(1.0, 0.0, 0.0, 0.0);
  3003. ConchVector4.UnitY = new ConchVector4(0.0, 1.0, 0.0, 0.0);
  3004. ConchVector4.UnitZ = new ConchVector4(0.0, 0.0, 1.0, 0.0);
  3005. ConchVector4.UnitW = new ConchVector4(0.0, 0.0, 0.0, 1.0);
  3006. class ConchVector3 {
  3007. constructor(x = 0, y = 0, z = 0, nativeElements = null) {
  3008. var v;
  3009. if (nativeElements) {
  3010. v = nativeElements;
  3011. }
  3012. else {
  3013. v = new Float32Array(3);
  3014. }
  3015. this.elements = v;
  3016. v[0] = x;
  3017. v[1] = y;
  3018. v[2] = z;
  3019. }
  3020. static distanceSquared(value1, value2) {
  3021. var value1e = value1.elements;
  3022. var value2e = value2.elements;
  3023. var x = value1e[0] - value2e[0];
  3024. var y = value1e[1] - value2e[1];
  3025. var z = value1e[2] - value2e[2];
  3026. return (x * x) + (y * y) + (z * z);
  3027. }
  3028. static distance(value1, value2) {
  3029. var value1e = value1.elements;
  3030. var value2e = value2.elements;
  3031. var x = value1e[0] - value2e[0];
  3032. var y = value1e[1] - value2e[1];
  3033. var z = value1e[2] - value2e[2];
  3034. return Math.sqrt((x * x) + (y * y) + (z * z));
  3035. }
  3036. static min(a, b, out) {
  3037. var e = out.elements;
  3038. var f = a.elements;
  3039. var g = b.elements;
  3040. e[0] = Math.min(f[0], g[0]);
  3041. e[1] = Math.min(f[1], g[1]);
  3042. e[2] = Math.min(f[2], g[2]);
  3043. }
  3044. static max(a, b, out) {
  3045. var e = out.elements;
  3046. var f = a.elements;
  3047. var g = b.elements;
  3048. e[0] = Math.max(f[0], g[0]);
  3049. e[1] = Math.max(f[1], g[1]);
  3050. e[2] = Math.max(f[2], g[2]);
  3051. }
  3052. static transformQuat(source, rotation, out) {
  3053. var destination = out.elements;
  3054. var se = source.elements;
  3055. var re = rotation.elements;
  3056. var x = se[0], y = se[1], z = se[2], qx = re[0], qy = re[1], qz = re[2], qw = re[3], ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  3057. destination[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  3058. destination[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  3059. destination[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  3060. }
  3061. static scalarLength(a) {
  3062. var f = a.elements;
  3063. var x = f[0], y = f[1], z = f[2];
  3064. return Math.sqrt(x * x + y * y + z * z);
  3065. }
  3066. static scalarLengthSquared(a) {
  3067. var f = a.elements;
  3068. var x = f[0], y = f[1], z = f[2];
  3069. return x * x + y * y + z * z;
  3070. }
  3071. static normalize(s, out) {
  3072. var se = s.elements;
  3073. var oe = out.elements;
  3074. var x = se[0], y = se[1], z = se[2];
  3075. var len = x * x + y * y + z * z;
  3076. if (len > 0) {
  3077. len = 1 / Math.sqrt(len);
  3078. oe[0] = se[0] * len;
  3079. oe[1] = se[1] * len;
  3080. oe[2] = se[2] * len;
  3081. }
  3082. }
  3083. static multiply(a, b, out) {
  3084. var e = out.elements;
  3085. var f = a.elements;
  3086. var g = b.elements;
  3087. e[0] = f[0] * g[0];
  3088. e[1] = f[1] * g[1];
  3089. e[2] = f[2] * g[2];
  3090. }
  3091. static scale(a, b, out) {
  3092. var e = out.elements;
  3093. var f = a.elements;
  3094. e[0] = f[0] * b;
  3095. e[1] = f[1] * b;
  3096. e[2] = f[2] * b;
  3097. }
  3098. static lerp(a, b, t, out) {
  3099. var e = out.elements;
  3100. var f = a.elements;
  3101. var g = b.elements;
  3102. var ax = f[0], ay = f[1], az = f[2];
  3103. e[0] = ax + t * (g[0] - ax);
  3104. e[1] = ay + t * (g[1] - ay);
  3105. e[2] = az + t * (g[2] - az);
  3106. }
  3107. static transformV3ToV3(vector, transform, result) {
  3108. var intermediate = ConchVector3._tempVector4;
  3109. ConchVector3.transformV3ToV4(vector, transform, intermediate);
  3110. var intermediateElem = intermediate.elements;
  3111. var resultElem = result.elements;
  3112. resultElem[0] = intermediateElem[0];
  3113. resultElem[1] = intermediateElem[1];
  3114. resultElem[2] = intermediateElem[2];
  3115. }
  3116. static transformV3ToV4(vector, transform, result) {
  3117. var vectorElem = vector.elements;
  3118. var vectorX = vectorElem[0];
  3119. var vectorY = vectorElem[1];
  3120. var vectorZ = vectorElem[2];
  3121. var transformElem = transform.elements;
  3122. var resultElem = result.elements;
  3123. resultElem[0] = (vectorX * transformElem[0]) + (vectorY * transformElem[4]) + (vectorZ * transformElem[8]) + transformElem[12];
  3124. resultElem[1] = (vectorX * transformElem[1]) + (vectorY * transformElem[5]) + (vectorZ * transformElem[9]) + transformElem[13];
  3125. resultElem[2] = (vectorX * transformElem[2]) + (vectorY * transformElem[6]) + (vectorZ * transformElem[10]) + transformElem[14];
  3126. resultElem[3] = (vectorX * transformElem[3]) + (vectorY * transformElem[7]) + (vectorZ * transformElem[11]) + transformElem[15];
  3127. }
  3128. static TransformNormal(normal, transform, result) {
  3129. var normalElem = normal.elements;
  3130. var normalX = normalElem[0];
  3131. var normalY = normalElem[1];
  3132. var normalZ = normalElem[2];
  3133. var transformElem = transform.elements;
  3134. var resultElem = result.elements;
  3135. resultElem[0] = (normalX * transformElem[0]) + (normalY * transformElem[4]) + (normalZ * transformElem[8]);
  3136. resultElem[1] = (normalX * transformElem[1]) + (normalY * transformElem[5]) + (normalZ * transformElem[9]);
  3137. resultElem[2] = (normalX * transformElem[2]) + (normalY * transformElem[6]) + (normalZ * transformElem[10]);
  3138. }
  3139. static transformCoordinate(coordinate, transform, result) {
  3140. var coordinateElem = coordinate.elements;
  3141. var coordinateX = coordinateElem[0];
  3142. var coordinateY = coordinateElem[1];
  3143. var coordinateZ = coordinateElem[2];
  3144. var transformElem = transform.elements;
  3145. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  3146. var resultElem = result.elements;
  3147. resultElem[0] = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  3148. resultElem[1] = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  3149. resultElem[2] = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  3150. }
  3151. static Clamp(value, min, max, out) {
  3152. var valuee = value.elements;
  3153. var x = valuee[0];
  3154. var y = valuee[1];
  3155. var z = valuee[2];
  3156. var mine = min.elements;
  3157. var mineX = mine[0];
  3158. var mineY = mine[1];
  3159. var mineZ = mine[2];
  3160. var maxe = max.elements;
  3161. var maxeX = maxe[0];
  3162. var maxeY = maxe[1];
  3163. var maxeZ = maxe[2];
  3164. var oute = out.elements;
  3165. x = (x > maxeX) ? maxeX : x;
  3166. x = (x < mineX) ? mineX : x;
  3167. y = (y > maxeY) ? maxeY : y;
  3168. y = (y < mineY) ? mineY : y;
  3169. z = (z > maxeZ) ? maxeZ : z;
  3170. z = (z < mineZ) ? mineZ : z;
  3171. oute[0] = x;
  3172. oute[1] = y;
  3173. oute[2] = z;
  3174. }
  3175. static add(a, b, out) {
  3176. var e = out.elements;
  3177. var f = a.elements;
  3178. var g = b.elements;
  3179. e[0] = f[0] + g[0];
  3180. e[1] = f[1] + g[1];
  3181. e[2] = f[2] + g[2];
  3182. }
  3183. static subtract(a, b, o) {
  3184. var oe = o.elements;
  3185. var ae = a.elements;
  3186. var be = b.elements;
  3187. oe[0] = ae[0] - be[0];
  3188. oe[1] = ae[1] - be[1];
  3189. oe[2] = ae[2] - be[2];
  3190. }
  3191. static cross(a, b, o) {
  3192. var ae = a.elements;
  3193. var be = b.elements;
  3194. var oe = o.elements;
  3195. var ax = ae[0], ay = ae[1], az = ae[2], bx = be[0], by = be[1], bz = be[2];
  3196. oe[0] = ay * bz - az * by;
  3197. oe[1] = az * bx - ax * bz;
  3198. oe[2] = ax * by - ay * bx;
  3199. }
  3200. static dot(a, b) {
  3201. var ae = a.elements;
  3202. var be = b.elements;
  3203. var r = (ae[0] * be[0]) + (ae[1] * be[1]) + (ae[2] * be[2]);
  3204. return r;
  3205. }
  3206. static equals(a, b) {
  3207. var ae = a.elements;
  3208. var be = b.elements;
  3209. return MathUtils3D.nearEqual(ae[0], be[0]) && MathUtils3D.nearEqual(ae[1], be[1]) && MathUtils3D.nearEqual(ae[2], be[2]);
  3210. }
  3211. get x() {
  3212. return this.elements[0];
  3213. }
  3214. set x(value) {
  3215. this.elements[0] = value;
  3216. }
  3217. get y() {
  3218. return this.elements[1];
  3219. }
  3220. set y(value) {
  3221. this.elements[1] = value;
  3222. }
  3223. get z() {
  3224. return this.elements[2];
  3225. }
  3226. set z(value) {
  3227. this.elements[2] = value;
  3228. }
  3229. setValue(x, y, z) {
  3230. this.elements[0] = x;
  3231. this.elements[1] = y;
  3232. this.elements[2] = z;
  3233. }
  3234. fromArray(array, offset = 0) {
  3235. this.elements[0] = array[offset + 0];
  3236. this.elements[1] = array[offset + 1];
  3237. this.elements[2] = array[offset + 2];
  3238. }
  3239. cloneTo(destObject) {
  3240. var destVector3 = destObject;
  3241. var destE = destVector3.elements;
  3242. var s = this.elements;
  3243. destE[0] = s[0];
  3244. destE[1] = s[1];
  3245. destE[2] = s[2];
  3246. }
  3247. clone() {
  3248. var destVector3 = new ConchVector3();
  3249. this.cloneTo(destVector3);
  3250. return destVector3;
  3251. }
  3252. toDefault() {
  3253. this.elements[0] = 0;
  3254. this.elements[1] = 0;
  3255. this.elements[2] = 0;
  3256. }
  3257. }
  3258. ConchVector3._tempVector4 = new ConchVector4();
  3259. ConchVector3.ZERO = new ConchVector3(0.0, 0.0, 0.0);
  3260. ConchVector3.ONE = new ConchVector3(1.0, 1.0, 1.0);
  3261. ConchVector3.NegativeUnitX = new ConchVector3(-1, 0, 0);
  3262. ConchVector3.UnitX = new ConchVector3(1, 0, 0);
  3263. ConchVector3.UnitY = new ConchVector3(0, 1, 0);
  3264. ConchVector3.UnitZ = new ConchVector3(0, 0, 1);
  3265. ConchVector3.ForwardRH = new ConchVector3(0, 0, -1);
  3266. ConchVector3.ForwardLH = new ConchVector3(0, 0, 1);
  3267. ConchVector3.Up = new ConchVector3(0, 1, 0);
  3268. ConchVector3.NAN = new ConchVector3(NaN, NaN, NaN);
  3269. class Matrix4x4 {
  3270. constructor(m11 = 1, m12 = 0, m13 = 0, m14 = 0, m21 = 0, m22 = 1, m23 = 0, m24 = 0, m31 = 0, m32 = 0, m33 = 1, m34 = 0, m41 = 0, m42 = 0, m43 = 0, m44 = 1, elements = null) {
  3271. var e = elements ? this.elements = elements : this.elements = new Float32Array(16);
  3272. e[0] = m11;
  3273. e[1] = m12;
  3274. e[2] = m13;
  3275. e[3] = m14;
  3276. e[4] = m21;
  3277. e[5] = m22;
  3278. e[6] = m23;
  3279. e[7] = m24;
  3280. e[8] = m31;
  3281. e[9] = m32;
  3282. e[10] = m33;
  3283. e[11] = m34;
  3284. e[12] = m41;
  3285. e[13] = m42;
  3286. e[14] = m43;
  3287. e[15] = m44;
  3288. }
  3289. static createRotationX(rad, out) {
  3290. var oe = out.elements;
  3291. var s = Math.sin(rad), c = Math.cos(rad);
  3292. oe[1] = oe[2] = oe[3] = oe[4] = oe[7] = oe[8] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  3293. oe[0] = oe[15] = 1;
  3294. oe[5] = oe[10] = c;
  3295. oe[6] = s;
  3296. oe[9] = -s;
  3297. }
  3298. static createRotationY(rad, out) {
  3299. var oe = out.elements;
  3300. var s = Math.sin(rad), c = Math.cos(rad);
  3301. oe[1] = oe[3] = oe[4] = oe[6] = oe[7] = oe[9] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  3302. oe[5] = oe[15] = 1;
  3303. oe[0] = oe[10] = c;
  3304. oe[2] = -s;
  3305. oe[8] = s;
  3306. }
  3307. static createRotationZ(rad, out) {
  3308. var oe = out.elements;
  3309. var s = Math.sin(rad), c = Math.cos(rad);
  3310. oe[2] = oe[3] = oe[6] = oe[7] = oe[8] = oe[9] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  3311. oe[10] = oe[15] = 1;
  3312. oe[0] = oe[5] = c;
  3313. oe[1] = s;
  3314. oe[4] = -s;
  3315. }
  3316. static createRotationYawPitchRoll(yaw, pitch, roll, result) {
  3317. Quaternion.createFromYawPitchRoll(yaw, pitch, roll, Matrix4x4._tempQuaternion);
  3318. Matrix4x4.createRotationQuaternion(Matrix4x4._tempQuaternion, result);
  3319. }
  3320. static createRotationAxis(axis, angle, result) {
  3321. var x = axis.x;
  3322. var y = axis.y;
  3323. var z = axis.z;
  3324. var cos = Math.cos(angle);
  3325. var sin = Math.sin(angle);
  3326. var xx = x * x;
  3327. var yy = y * y;
  3328. var zz = z * z;
  3329. var xy = x * y;
  3330. var xz = x * z;
  3331. var yz = y * z;
  3332. var resultE = result.elements;
  3333. resultE[3] = resultE[7] = resultE[11] = resultE[12] = resultE[13] = resultE[14] = 0;
  3334. resultE[15] = 1.0;
  3335. resultE[0] = xx + (cos * (1.0 - xx));
  3336. resultE[1] = (xy - (cos * xy)) + (sin * z);
  3337. resultE[2] = (xz - (cos * xz)) - (sin * y);
  3338. resultE[4] = (xy - (cos * xy)) - (sin * z);
  3339. resultE[5] = yy + (cos * (1.0 - yy));
  3340. resultE[6] = (yz - (cos * yz)) + (sin * x);
  3341. resultE[8] = (xz - (cos * xz)) + (sin * y);
  3342. resultE[9] = (yz - (cos * yz)) - (sin * x);
  3343. resultE[10] = zz + (cos * (1.0 - zz));
  3344. }
  3345. setRotation(rotation) {
  3346. var rotationX = rotation.x;
  3347. var rotationY = rotation.y;
  3348. var rotationZ = rotation.z;
  3349. var rotationW = rotation.w;
  3350. var xx = rotationX * rotationX;
  3351. var yy = rotationY * rotationY;
  3352. var zz = rotationZ * rotationZ;
  3353. var xy = rotationX * rotationY;
  3354. var zw = rotationZ * rotationW;
  3355. var zx = rotationZ * rotationX;
  3356. var yw = rotationY * rotationW;
  3357. var yz = rotationY * rotationZ;
  3358. var xw = rotationX * rotationW;
  3359. var e = this.elements;
  3360. e[0] = 1.0 - (2.0 * (yy + zz));
  3361. e[1] = 2.0 * (xy + zw);
  3362. e[2] = 2.0 * (zx - yw);
  3363. e[4] = 2.0 * (xy - zw);
  3364. e[5] = 1.0 - (2.0 * (zz + xx));
  3365. e[6] = 2.0 * (yz + xw);
  3366. e[8] = 2.0 * (zx + yw);
  3367. e[9] = 2.0 * (yz - xw);
  3368. e[10] = 1.0 - (2.0 * (yy + xx));
  3369. }
  3370. setPosition(position) {
  3371. var e = this.elements;
  3372. e[12] = position.x;
  3373. e[13] = position.y;
  3374. e[14] = position.z;
  3375. }
  3376. static createRotationQuaternion(rotation, result) {
  3377. var resultE = result.elements;
  3378. var rotationX = rotation.x;
  3379. var rotationY = rotation.y;
  3380. var rotationZ = rotation.z;
  3381. var rotationW = rotation.w;
  3382. var xx = rotationX * rotationX;
  3383. var yy = rotationY * rotationY;
  3384. var zz = rotationZ * rotationZ;
  3385. var xy = rotationX * rotationY;
  3386. var zw = rotationZ * rotationW;
  3387. var zx = rotationZ * rotationX;
  3388. var yw = rotationY * rotationW;
  3389. var yz = rotationY * rotationZ;
  3390. var xw = rotationX * rotationW;
  3391. resultE[3] = resultE[7] = resultE[11] = resultE[12] = resultE[13] = resultE[14] = 0;
  3392. resultE[15] = 1.0;
  3393. resultE[0] = 1.0 - (2.0 * (yy + zz));
  3394. resultE[1] = 2.0 * (xy + zw);
  3395. resultE[2] = 2.0 * (zx - yw);
  3396. resultE[4] = 2.0 * (xy - zw);
  3397. resultE[5] = 1.0 - (2.0 * (zz + xx));
  3398. resultE[6] = 2.0 * (yz + xw);
  3399. resultE[8] = 2.0 * (zx + yw);
  3400. resultE[9] = 2.0 * (yz - xw);
  3401. resultE[10] = 1.0 - (2.0 * (yy + xx));
  3402. }
  3403. static createTranslate(trans, out) {
  3404. var oe = out.elements;
  3405. oe[4] = oe[8] = oe[1] = oe[9] = oe[2] = oe[6] = oe[3] = oe[7] = oe[11] = 0;
  3406. oe[0] = oe[5] = oe[10] = oe[15] = 1;
  3407. oe[12] = trans.x;
  3408. oe[13] = trans.y;
  3409. oe[14] = trans.z;
  3410. }
  3411. static createScaling(scale, out) {
  3412. var oe = out.elements;
  3413. oe[0] = scale.x;
  3414. oe[5] = scale.y;
  3415. oe[10] = scale.z;
  3416. oe[1] = oe[4] = oe[8] = oe[12] = oe[9] = oe[13] = oe[2] = oe[6] = oe[14] = oe[3] = oe[7] = oe[11] = 0;
  3417. oe[15] = 1;
  3418. }
  3419. static multiply(left, right, out) {
  3420. var l = right.elements;
  3421. var r = left.elements;
  3422. var e = out.elements;
  3423. var l11 = l[0], l12 = l[1], l13 = l[2], l14 = l[3];
  3424. var l21 = l[4], l22 = l[5], l23 = l[6], l24 = l[7];
  3425. var l31 = l[8], l32 = l[9], l33 = l[10], l34 = l[11];
  3426. var l41 = l[12], l42 = l[13], l43 = l[14], l44 = l[15];
  3427. var r11 = r[0], r12 = r[1], r13 = r[2], r14 = r[3];
  3428. var r21 = r[4], r22 = r[5], r23 = r[6], r24 = r[7];
  3429. var r31 = r[8], r32 = r[9], r33 = r[10], r34 = r[11];
  3430. var r41 = r[12], r42 = r[13], r43 = r[14], r44 = r[15];
  3431. e[0] = (l11 * r11) + (l12 * r21) + (l13 * r31) + (l14 * r41);
  3432. e[1] = (l11 * r12) + (l12 * r22) + (l13 * r32) + (l14 * r42);
  3433. e[2] = (l11 * r13) + (l12 * r23) + (l13 * r33) + (l14 * r43);
  3434. e[3] = (l11 * r14) + (l12 * r24) + (l13 * r34) + (l14 * r44);
  3435. e[4] = (l21 * r11) + (l22 * r21) + (l23 * r31) + (l24 * r41);
  3436. e[5] = (l21 * r12) + (l22 * r22) + (l23 * r32) + (l24 * r42);
  3437. e[6] = (l21 * r13) + (l22 * r23) + (l23 * r33) + (l24 * r43);
  3438. e[7] = (l21 * r14) + (l22 * r24) + (l23 * r34) + (l24 * r44);
  3439. e[8] = (l31 * r11) + (l32 * r21) + (l33 * r31) + (l34 * r41);
  3440. e[9] = (l31 * r12) + (l32 * r22) + (l33 * r32) + (l34 * r42);
  3441. e[10] = (l31 * r13) + (l32 * r23) + (l33 * r33) + (l34 * r43);
  3442. e[11] = (l31 * r14) + (l32 * r24) + (l33 * r34) + (l34 * r44);
  3443. e[12] = (l41 * r11) + (l42 * r21) + (l43 * r31) + (l44 * r41);
  3444. e[13] = (l41 * r12) + (l42 * r22) + (l43 * r32) + (l44 * r42);
  3445. e[14] = (l41 * r13) + (l42 * r23) + (l43 * r33) + (l44 * r43);
  3446. e[15] = (l41 * r14) + (l42 * r24) + (l43 * r34) + (l44 * r44);
  3447. }
  3448. static multiplyForNative(left, right, out) {
  3449. Laya.LayaGL.instance.matrix4x4Multiply(left.elements, right.elements, out.elements);
  3450. }
  3451. static createFromQuaternion(rotation, out) {
  3452. var e = out.elements;
  3453. var x = rotation.x, y = rotation.y, z = rotation.z, w = rotation.w;
  3454. var x2 = x + x;
  3455. var y2 = y + y;
  3456. var z2 = z + z;
  3457. var xx = x * x2;
  3458. var yx = y * x2;
  3459. var yy = y * y2;
  3460. var zx = z * x2;
  3461. var zy = z * y2;
  3462. var zz = z * z2;
  3463. var wx = w * x2;
  3464. var wy = w * y2;
  3465. var wz = w * z2;
  3466. e[0] = 1 - yy - zz;
  3467. e[1] = yx + wz;
  3468. e[2] = zx - wy;
  3469. e[3] = 0;
  3470. e[4] = yx - wz;
  3471. e[5] = 1 - xx - zz;
  3472. e[6] = zy + wx;
  3473. e[7] = 0;
  3474. e[8] = zx + wy;
  3475. e[9] = zy - wx;
  3476. e[10] = 1 - xx - yy;
  3477. e[11] = 0;
  3478. e[12] = 0;
  3479. e[13] = 0;
  3480. e[14] = 0;
  3481. e[15] = 1;
  3482. }
  3483. static createAffineTransformation(trans, rot, scale, out) {
  3484. var oe = out.elements;
  3485. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  3486. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  3487. var wx = w * x2, wy = w * y2, wz = w * z2, sx = scale.x, sy = scale.y, sz = scale.z;
  3488. oe[0] = (1 - (yy + zz)) * sx;
  3489. oe[1] = (xy + wz) * sx;
  3490. oe[2] = (xz - wy) * sx;
  3491. oe[3] = 0;
  3492. oe[4] = (xy - wz) * sy;
  3493. oe[5] = (1 - (xx + zz)) * sy;
  3494. oe[6] = (yz + wx) * sy;
  3495. oe[7] = 0;
  3496. oe[8] = (xz + wy) * sz;
  3497. oe[9] = (yz - wx) * sz;
  3498. oe[10] = (1 - (xx + yy)) * sz;
  3499. oe[11] = 0;
  3500. oe[12] = trans.x;
  3501. oe[13] = trans.y;
  3502. oe[14] = trans.z;
  3503. oe[15] = 1;
  3504. }
  3505. static createLookAt(eye, target, up, out) {
  3506. var oE = out.elements;
  3507. var xaxis = Matrix4x4._tempVector0;
  3508. var yaxis = Matrix4x4._tempVector1;
  3509. var zaxis = Matrix4x4._tempVector2;
  3510. Vector3.subtract(eye, target, zaxis);
  3511. Vector3.normalize(zaxis, zaxis);
  3512. Vector3.cross(up, zaxis, xaxis);
  3513. Vector3.normalize(xaxis, xaxis);
  3514. Vector3.cross(zaxis, xaxis, yaxis);
  3515. out.identity();
  3516. oE[0] = xaxis.x;
  3517. oE[4] = xaxis.y;
  3518. oE[8] = xaxis.z;
  3519. oE[1] = yaxis.x;
  3520. oE[5] = yaxis.y;
  3521. oE[9] = yaxis.z;
  3522. oE[2] = zaxis.x;
  3523. oE[6] = zaxis.y;
  3524. oE[10] = zaxis.z;
  3525. oE[12] = -Vector3.dot(xaxis, eye);
  3526. oE[13] = -Vector3.dot(yaxis, eye);
  3527. oE[14] = -Vector3.dot(zaxis, eye);
  3528. }
  3529. static createPerspective(fov, aspect, znear, zfar, out) {
  3530. var yScale = 1.0 / Math.tan(fov * 0.5);
  3531. var xScale = yScale / aspect;
  3532. var halfWidth = znear / xScale;
  3533. var halfHeight = znear / yScale;
  3534. Matrix4x4.createPerspectiveOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, znear, zfar, out);
  3535. }
  3536. static createPerspectiveOffCenter(left, right, bottom, top, znear, zfar, out) {
  3537. var oe = out.elements;
  3538. var zRange = zfar / (zfar - znear);
  3539. oe[1] = oe[2] = oe[3] = oe[4] = oe[6] = oe[7] = oe[12] = oe[13] = oe[15] = 0;
  3540. oe[0] = 2.0 * znear / (right - left);
  3541. oe[5] = 2.0 * znear / (top - bottom);
  3542. oe[8] = (left + right) / (right - left);
  3543. oe[9] = (top + bottom) / (top - bottom);
  3544. oe[10] = -zRange;
  3545. oe[11] = -1.0;
  3546. oe[14] = -znear * zRange;
  3547. }
  3548. static createOrthoOffCenter(left, right, bottom, top, znear, zfar, out) {
  3549. var oe = out.elements;
  3550. var zRange = 1.0 / (zfar - znear);
  3551. oe[1] = oe[2] = oe[3] = oe[4] = oe[6] = oe[8] = oe[7] = oe[9] = oe[11] = 0;
  3552. oe[15] = 1;
  3553. oe[0] = 2.0 / (right - left);
  3554. oe[5] = 2.0 / (top - bottom);
  3555. oe[10] = -zRange;
  3556. oe[12] = (left + right) / (left - right);
  3557. oe[13] = (top + bottom) / (bottom - top);
  3558. oe[14] = -znear * zRange;
  3559. }
  3560. getElementByRowColumn(row, column) {
  3561. if (row < 0 || row > 3)
  3562. throw new Error("row Rows and columns for matrices run from 0 to 3, inclusive.");
  3563. if (column < 0 || column > 3)
  3564. throw new Error("column Rows and columns for matrices run from 0 to 3, inclusive.");
  3565. return this.elements[(row * 4) + column];
  3566. }
  3567. setElementByRowColumn(row, column, value) {
  3568. if (row < 0 || row > 3)
  3569. throw new Error("row Rows and columns for matrices run from 0 to 3, inclusive.");
  3570. if (column < 0 || column > 3)
  3571. throw new Error("column Rows and columns for matrices run from 0 to 3, inclusive.");
  3572. this.elements[(row * 4) + column] = value;
  3573. }
  3574. equalsOtherMatrix(other) {
  3575. var e = this.elements;
  3576. var oe = other.elements;
  3577. return (MathUtils3D.nearEqual(e[0], oe[0]) && MathUtils3D.nearEqual(e[1], oe[1]) && MathUtils3D.nearEqual(e[2], oe[2]) && MathUtils3D.nearEqual(e[3], oe[3]) && MathUtils3D.nearEqual(e[4], oe[4]) && MathUtils3D.nearEqual(e[5], oe[5]) && MathUtils3D.nearEqual(e[6], oe[6]) && MathUtils3D.nearEqual(e[7], oe[7]) && MathUtils3D.nearEqual(e[8], oe[8]) && MathUtils3D.nearEqual(e[9], oe[9]) && MathUtils3D.nearEqual(e[10], oe[10]) && MathUtils3D.nearEqual(e[11], oe[11]) && MathUtils3D.nearEqual(e[12], oe[12]) && MathUtils3D.nearEqual(e[13], oe[13]) && MathUtils3D.nearEqual(e[14], oe[14]) && MathUtils3D.nearEqual(e[15], oe[15]));
  3578. }
  3579. decomposeTransRotScale(translation, rotation, scale) {
  3580. var rotationMatrix = Matrix4x4._tempMatrix4x4;
  3581. if (this.decomposeTransRotMatScale(translation, rotationMatrix, scale)) {
  3582. Quaternion.createFromMatrix4x4(rotationMatrix, rotation);
  3583. return true;
  3584. }
  3585. else {
  3586. rotation.identity();
  3587. return false;
  3588. }
  3589. }
  3590. decomposeTransRotMatScale(translation, rotationMatrix, scale) {
  3591. var e = this.elements;
  3592. var te = translation;
  3593. var re = rotationMatrix.elements;
  3594. var se = scale;
  3595. te.x = e[12];
  3596. te.y = e[13];
  3597. te.z = e[14];
  3598. var m11 = e[0], m12 = e[1], m13 = e[2];
  3599. var m21 = e[4], m22 = e[5], m23 = e[6];
  3600. var m31 = e[8], m32 = e[9], m33 = e[10];
  3601. var sX = se.x = Math.sqrt((m11 * m11) + (m12 * m12) + (m13 * m13));
  3602. var sY = se.y = Math.sqrt((m21 * m21) + (m22 * m22) + (m23 * m23));
  3603. var sZ = se.z = Math.sqrt((m31 * m31) + (m32 * m32) + (m33 * m33));
  3604. if (MathUtils3D.isZero(sX) || MathUtils3D.isZero(sY) || MathUtils3D.isZero(sZ)) {
  3605. re[1] = re[2] = re[3] = re[4] = re[6] = re[7] = re[8] = re[9] = re[11] = re[12] = re[13] = re[14] = 0;
  3606. re[0] = re[5] = re[10] = re[15] = 1;
  3607. return false;
  3608. }
  3609. var at = Matrix4x4._tempVector0;
  3610. at.x = m31 / sZ;
  3611. at.y = m32 / sZ;
  3612. at.z = m33 / sZ;
  3613. var tempRight = Matrix4x4._tempVector1;
  3614. tempRight.x = m11 / sX;
  3615. tempRight.y = m12 / sX;
  3616. tempRight.z = m13 / sX;
  3617. var up = Matrix4x4._tempVector2;
  3618. Vector3.cross(at, tempRight, up);
  3619. var right = Matrix4x4._tempVector1;
  3620. Vector3.cross(up, at, right);
  3621. re[3] = re[7] = re[11] = re[12] = re[13] = re[14] = 0;
  3622. re[15] = 1;
  3623. re[0] = right.x;
  3624. re[1] = right.y;
  3625. re[2] = right.z;
  3626. re[4] = up.x;
  3627. re[5] = up.y;
  3628. re[6] = up.z;
  3629. re[8] = at.x;
  3630. re[9] = at.y;
  3631. re[10] = at.z;
  3632. ((re[0] * m11 + re[1] * m12 + re[2] * m13) < 0.0) && (se.x = -sX);
  3633. ((re[4] * m21 + re[5] * m22 + re[6] * m23) < 0.0) && (se.y = -sY);
  3634. ((re[8] * m31 + re[9] * m32 + re[10] * m33) < 0.0) && (se.z = -sZ);
  3635. return true;
  3636. }
  3637. decomposeYawPitchRoll(yawPitchRoll) {
  3638. var pitch = Math.asin(-this.elements[9]);
  3639. yawPitchRoll.y = pitch;
  3640. var test = Math.cos(pitch);
  3641. if (test > MathUtils3D.zeroTolerance) {
  3642. yawPitchRoll.z = Math.atan2(this.elements[1], this.elements[5]);
  3643. yawPitchRoll.x = Math.atan2(this.elements[8], this.elements[10]);
  3644. }
  3645. else {
  3646. yawPitchRoll.z = Math.atan2(-this.elements[4], this.elements[0]);
  3647. yawPitchRoll.x = 0.0;
  3648. }
  3649. }
  3650. normalize() {
  3651. var v = this.elements;
  3652. var c = v[0], d = v[1], e = v[2], g = Math.sqrt(c * c + d * d + e * e);
  3653. if (g) {
  3654. if (g == 1)
  3655. return;
  3656. }
  3657. else {
  3658. v[0] = 0;
  3659. v[1] = 0;
  3660. v[2] = 0;
  3661. return;
  3662. }
  3663. g = 1 / g;
  3664. v[0] = c * g;
  3665. v[1] = d * g;
  3666. v[2] = e * g;
  3667. }
  3668. transpose() {
  3669. var e, t;
  3670. e = this.elements;
  3671. t = e[1];
  3672. e[1] = e[4];
  3673. e[4] = t;
  3674. t = e[2];
  3675. e[2] = e[8];
  3676. e[8] = t;
  3677. t = e[3];
  3678. e[3] = e[12];
  3679. e[12] = t;
  3680. t = e[6];
  3681. e[6] = e[9];
  3682. e[9] = t;
  3683. t = e[7];
  3684. e[7] = e[13];
  3685. e[13] = t;
  3686. t = e[11];
  3687. e[11] = e[14];
  3688. e[14] = t;
  3689. return this;
  3690. }
  3691. invert(out) {
  3692. var ae = this.elements;
  3693. var oe = out.elements;
  3694. var a00 = ae[0], a01 = ae[1], a02 = ae[2], a03 = ae[3], a10 = ae[4], a11 = ae[5], a12 = ae[6], a13 = ae[7], a20 = ae[8], a21 = ae[9], a22 = ae[10], a23 = ae[11], a30 = ae[12], a31 = ae[13], a32 = ae[14], a33 = ae[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  3695. if (Math.abs(det) === 0.0) {
  3696. return;
  3697. }
  3698. det = 1.0 / det;
  3699. oe[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  3700. oe[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  3701. oe[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  3702. oe[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  3703. oe[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  3704. oe[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  3705. oe[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  3706. oe[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  3707. oe[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  3708. oe[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  3709. oe[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  3710. oe[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  3711. oe[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  3712. oe[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  3713. oe[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  3714. oe[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  3715. }
  3716. static billboard(objectPosition, cameraPosition, cameraRight, cameraUp, cameraForward, mat) {
  3717. Vector3.subtract(objectPosition, cameraPosition, Matrix4x4._tempVector0);
  3718. var lengthSq = Vector3.scalarLengthSquared(Matrix4x4._tempVector0);
  3719. if (MathUtils3D.isZero(lengthSq)) {
  3720. Vector3.scale(cameraForward, -1, Matrix4x4._tempVector1);
  3721. Matrix4x4._tempVector1.cloneTo(Matrix4x4._tempVector0);
  3722. }
  3723. else {
  3724. Vector3.scale(Matrix4x4._tempVector0, 1 / Math.sqrt(lengthSq), Matrix4x4._tempVector0);
  3725. }
  3726. Vector3.cross(cameraUp, Matrix4x4._tempVector0, Matrix4x4._tempVector2);
  3727. Vector3.normalize(Matrix4x4._tempVector2, Matrix4x4._tempVector2);
  3728. Vector3.cross(Matrix4x4._tempVector0, Matrix4x4._tempVector2, Matrix4x4._tempVector3);
  3729. var crosse = Matrix4x4._tempVector2;
  3730. var finale = Matrix4x4._tempVector3;
  3731. var diffee = Matrix4x4._tempVector0;
  3732. var obpose = objectPosition;
  3733. var mate = mat.elements;
  3734. mate[0] = crosse.x;
  3735. mate[1] = crosse.y;
  3736. mate[2] = crosse.z;
  3737. mate[3] = 0.0;
  3738. mate[4] = finale.x;
  3739. mate[5] = finale.y;
  3740. mate[6] = finale.z;
  3741. mate[7] = 0.0;
  3742. mate[8] = diffee.x;
  3743. mate[9] = diffee.y;
  3744. mate[10] = diffee.z;
  3745. mate[11] = 0.0;
  3746. mate[12] = obpose.x;
  3747. mate[13] = obpose.y;
  3748. mate[14] = obpose.z;
  3749. mate[15] = 1.0;
  3750. }
  3751. identity() {
  3752. var e = this.elements;
  3753. e[1] = e[2] = e[3] = e[4] = e[6] = e[7] = e[8] = e[9] = e[11] = e[12] = e[13] = e[14] = 0;
  3754. e[0] = e[5] = e[10] = e[15] = 1;
  3755. }
  3756. cloneTo(destObject) {
  3757. var i, s, d;
  3758. s = this.elements;
  3759. d = destObject.elements;
  3760. if (s === d) {
  3761. return;
  3762. }
  3763. for (i = 0; i < 16; ++i) {
  3764. d[i] = s[i];
  3765. }
  3766. }
  3767. clone() {
  3768. var dest = new Matrix4x4();
  3769. this.cloneTo(dest);
  3770. return dest;
  3771. }
  3772. static translation(v3, out) {
  3773. var oe = out.elements;
  3774. oe[0] = oe[5] = oe[10] = oe[15] = 1;
  3775. oe[12] = v3.x;
  3776. oe[13] = v3.y;
  3777. oe[14] = v3.z;
  3778. }
  3779. getTranslationVector(out) {
  3780. var me = this.elements;
  3781. out.x = me[12];
  3782. out.y = me[13];
  3783. out.z = me[14];
  3784. }
  3785. setTranslationVector(translate) {
  3786. var me = this.elements;
  3787. var ve = translate;
  3788. me[12] = ve.x;
  3789. me[13] = ve.y;
  3790. me[14] = ve.z;
  3791. }
  3792. getForward(out) {
  3793. var me = this.elements;
  3794. out.x = -me[8];
  3795. out.y = -me[9];
  3796. out.z = -me[10];
  3797. }
  3798. setForward(forward) {
  3799. var me = this.elements;
  3800. me[8] = -forward.x;
  3801. me[9] = -forward.y;
  3802. me[10] = -forward.z;
  3803. }
  3804. }
  3805. Matrix4x4._tempMatrix4x4 = new Matrix4x4();
  3806. Matrix4x4.TEMPMatrix0 = new Matrix4x4();
  3807. Matrix4x4.TEMPMatrix1 = new Matrix4x4();
  3808. Matrix4x4._tempVector0 = new Vector3();
  3809. Matrix4x4._tempVector1 = new Vector3();
  3810. Matrix4x4._tempVector2 = new Vector3();
  3811. Matrix4x4._tempVector3 = new Vector3();
  3812. Matrix4x4._tempQuaternion = new Quaternion();
  3813. Matrix4x4.DEFAULT = new Matrix4x4();
  3814. Matrix4x4.ZERO = new Matrix4x4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3815. class ConchQuaternion {
  3816. constructor(x = 0, y = 0, z = 0, w = 1, nativeElements = null) {
  3817. var v;
  3818. if (nativeElements) {
  3819. v = nativeElements;
  3820. }
  3821. else {
  3822. v = new Float32Array(4);
  3823. }
  3824. v[0] = x;
  3825. v[1] = y;
  3826. v[2] = z;
  3827. v[3] = w;
  3828. this.elements = v;
  3829. }
  3830. static _dotArray(l, r) {
  3831. return l[0] * r[0] + l[1] * r[1] + l[2] * r[2] + l[3] * r[3];
  3832. }
  3833. static _normalizeArray(f, o) {
  3834. var x = f[0], y = f[1], z = f[2], w = f[3];
  3835. var len = x * x + y * y + z * z + w * w;
  3836. if (len > 0) {
  3837. len = 1 / Math.sqrt(len);
  3838. o[0] = x * len;
  3839. o[1] = y * len;
  3840. o[2] = z * len;
  3841. o[3] = w * len;
  3842. }
  3843. }
  3844. static _lerpArray(l, r, amount, o) {
  3845. var inverse = 1.0 - amount;
  3846. if (ConchQuaternion._dotArray(l, r) >= 0) {
  3847. o[0] = (inverse * l[0]) + (amount * r[0]);
  3848. o[1] = (inverse * l[1]) + (amount * r[1]);
  3849. o[2] = (inverse * l[2]) + (amount * r[2]);
  3850. o[3] = (inverse * l[3]) + (amount * r[3]);
  3851. }
  3852. else {
  3853. o[0] = (inverse * l[0]) - (amount * r[0]);
  3854. o[1] = (inverse * l[1]) - (amount * r[1]);
  3855. o[2] = (inverse * l[2]) - (amount * r[2]);
  3856. o[3] = (inverse * l[3]) - (amount * r[3]);
  3857. }
  3858. ConchQuaternion._normalizeArray(o, o);
  3859. }
  3860. static createFromYawPitchRoll(yaw, pitch, roll, out) {
  3861. var halfRoll = roll * 0.5;
  3862. var halfPitch = pitch * 0.5;
  3863. var halfYaw = yaw * 0.5;
  3864. var sinRoll = Math.sin(halfRoll);
  3865. var cosRoll = Math.cos(halfRoll);
  3866. var sinPitch = Math.sin(halfPitch);
  3867. var cosPitch = Math.cos(halfPitch);
  3868. var sinYaw = Math.sin(halfYaw);
  3869. var cosYaw = Math.cos(halfYaw);
  3870. var oe = out.elements;
  3871. oe[0] = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3872. oe[1] = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3873. oe[2] = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3874. oe[3] = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3875. }
  3876. static multiply(left, right, out) {
  3877. var le = left.elements;
  3878. var re = right.elements;
  3879. var oe = out.elements;
  3880. var lx = le[0];
  3881. var ly = le[1];
  3882. var lz = le[2];
  3883. var lw = le[3];
  3884. var rx = re[0];
  3885. var ry = re[1];
  3886. var rz = re[2];
  3887. var rw = re[3];
  3888. var a = (ly * rz - lz * ry);
  3889. var b = (lz * rx - lx * rz);
  3890. var c = (lx * ry - ly * rx);
  3891. var d = (lx * rx + ly * ry + lz * rz);
  3892. oe[0] = (lx * rw + rx * lw) + a;
  3893. oe[1] = (ly * rw + ry * lw) + b;
  3894. oe[2] = (lz * rw + rz * lw) + c;
  3895. oe[3] = lw * rw - d;
  3896. }
  3897. static arcTanAngle(x, y) {
  3898. if (x == 0) {
  3899. if (y == 1)
  3900. return Math.PI / 2;
  3901. return -Math.PI / 2;
  3902. }
  3903. if (x > 0)
  3904. return Math.atan(y / x);
  3905. if (x < 0) {
  3906. if (y > 0)
  3907. return Math.atan(y / x) + Math.PI;
  3908. return Math.atan(y / x) - Math.PI;
  3909. }
  3910. return 0;
  3911. }
  3912. static angleTo(from, location, angle) {
  3913. ConchVector3.subtract(location, from, ConchQuaternion.TEMPVector30);
  3914. ConchVector3.normalize(ConchQuaternion.TEMPVector30, ConchQuaternion.TEMPVector30);
  3915. angle.elements[0] = Math.asin(ConchQuaternion.TEMPVector30.y);
  3916. angle.elements[1] = ConchQuaternion.arcTanAngle(-ConchQuaternion.TEMPVector30.z, -ConchQuaternion.TEMPVector30.x);
  3917. }
  3918. static createFromAxisAngle(axis, rad, out) {
  3919. var e = out.elements;
  3920. var f = axis.elements;
  3921. rad = rad * 0.5;
  3922. var s = Math.sin(rad);
  3923. e[0] = s * f[0];
  3924. e[1] = s * f[1];
  3925. e[2] = s * f[2];
  3926. e[3] = Math.cos(rad);
  3927. }
  3928. static createFromMatrix3x3(sou, out) {
  3929. var e = out.elements;
  3930. var f = sou.elements;
  3931. var fTrace = f[0] + f[4] + f[8];
  3932. var fRoot;
  3933. if (fTrace > 0.0) {
  3934. fRoot = Math.sqrt(fTrace + 1.0);
  3935. e[3] = 0.5 * fRoot;
  3936. fRoot = 0.5 / fRoot;
  3937. e[0] = (f[5] - f[7]) * fRoot;
  3938. e[1] = (f[6] - f[2]) * fRoot;
  3939. e[2] = (f[1] - f[3]) * fRoot;
  3940. }
  3941. else {
  3942. var i = 0;
  3943. if (f[4] > f[0])
  3944. i = 1;
  3945. if (f[8] > f[i * 3 + i])
  3946. i = 2;
  3947. var j = (i + 1) % 3;
  3948. var k = (i + 2) % 3;
  3949. fRoot = Math.sqrt(f[i * 3 + i] - f[j * 3 + j] - f[k * 3 + k] + 1.0);
  3950. e[i] = 0.5 * fRoot;
  3951. fRoot = 0.5 / fRoot;
  3952. e[3] = (f[j * 3 + k] - f[k * 3 + j]) * fRoot;
  3953. e[j] = (f[j * 3 + i] + f[i * 3 + j]) * fRoot;
  3954. e[k] = (f[k * 3 + i] + f[i * 3 + k]) * fRoot;
  3955. }
  3956. return;
  3957. }
  3958. static createFromMatrix4x4(mat, out) {
  3959. var me = mat.elements;
  3960. var oe = out.elements;
  3961. var sqrt;
  3962. var half;
  3963. var scale = me[0] + me[5] + me[10];
  3964. if (scale > 0.0) {
  3965. sqrt = Math.sqrt(scale + 1.0);
  3966. oe[3] = sqrt * 0.5;
  3967. sqrt = 0.5 / sqrt;
  3968. oe[0] = (me[6] - me[9]) * sqrt;
  3969. oe[1] = (me[8] - me[2]) * sqrt;
  3970. oe[2] = (me[1] - me[4]) * sqrt;
  3971. }
  3972. else if ((me[0] >= me[5]) && (me[0] >= me[10])) {
  3973. sqrt = Math.sqrt(1.0 + me[0] - me[5] - me[10]);
  3974. half = 0.5 / sqrt;
  3975. oe[0] = 0.5 * sqrt;
  3976. oe[1] = (me[1] + me[4]) * half;
  3977. oe[2] = (me[2] + me[8]) * half;
  3978. oe[3] = (me[6] - me[9]) * half;
  3979. }
  3980. else if (me[5] > me[10]) {
  3981. sqrt = Math.sqrt(1.0 + me[5] - me[0] - me[10]);
  3982. half = 0.5 / sqrt;
  3983. oe[0] = (me[4] + me[1]) * half;
  3984. oe[1] = 0.5 * sqrt;
  3985. oe[2] = (me[9] + me[6]) * half;
  3986. oe[3] = (me[8] - me[2]) * half;
  3987. }
  3988. else {
  3989. sqrt = Math.sqrt(1.0 + me[10] - me[0] - me[5]);
  3990. half = 0.5 / sqrt;
  3991. oe[0] = (me[8] + me[2]) * half;
  3992. oe[1] = (me[9] + me[6]) * half;
  3993. oe[2] = 0.5 * sqrt;
  3994. oe[3] = (me[1] - me[4]) * half;
  3995. }
  3996. }
  3997. static slerp(left, right, t, out) {
  3998. var a = left.elements;
  3999. var b = right.elements;
  4000. var oe = out.elements;
  4001. var ax = a[0], ay = a[1], az = a[2], aw = a[3], bx = b[0], by = b[1], bz = b[2], bw = b[3];
  4002. var omega, cosom, sinom, scale0, scale1;
  4003. cosom = ax * bx + ay * by + az * bz + aw * bw;
  4004. if (cosom < 0.0) {
  4005. cosom = -cosom;
  4006. bx = -bx;
  4007. by = -by;
  4008. bz = -bz;
  4009. bw = -bw;
  4010. }
  4011. if ((1.0 - cosom) > 0.000001) {
  4012. omega = Math.acos(cosom);
  4013. sinom = Math.sin(omega);
  4014. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  4015. scale1 = Math.sin(t * omega) / sinom;
  4016. }
  4017. else {
  4018. scale0 = 1.0 - t;
  4019. scale1 = t;
  4020. }
  4021. oe[0] = scale0 * ax + scale1 * bx;
  4022. oe[1] = scale0 * ay + scale1 * by;
  4023. oe[2] = scale0 * az + scale1 * bz;
  4024. oe[3] = scale0 * aw + scale1 * bw;
  4025. return oe;
  4026. }
  4027. static lerp(left, right, amount, out) {
  4028. ConchQuaternion._lerpArray(left.elements, right.elements, amount, out.elements);
  4029. }
  4030. static add(left, right, out) {
  4031. var e = out.elements;
  4032. var f = left.elements;
  4033. var g = right.elements;
  4034. e[0] = f[0] + g[0];
  4035. e[1] = f[1] + g[1];
  4036. e[2] = f[2] + g[2];
  4037. e[3] = f[3] + g[3];
  4038. }
  4039. static dot(left, right) {
  4040. return ConchQuaternion._dotArray(left.elements, right.elements);
  4041. }
  4042. get x() {
  4043. return this.elements[0];
  4044. }
  4045. set x(value) {
  4046. this.elements[0] = value;
  4047. }
  4048. get y() {
  4049. return this.elements[1];
  4050. }
  4051. set y(value) {
  4052. this.elements[1] = value;
  4053. }
  4054. get z() {
  4055. return this.elements[2];
  4056. }
  4057. set z(value) {
  4058. this.elements[2] = value;
  4059. }
  4060. get w() {
  4061. return this.elements[3];
  4062. }
  4063. set w(value) {
  4064. this.elements[3] = value;
  4065. }
  4066. scaling(scaling, out) {
  4067. var e = out.elements;
  4068. var f = this.elements;
  4069. e[0] = f[0] * scaling;
  4070. e[1] = f[1] * scaling;
  4071. e[2] = f[2] * scaling;
  4072. e[3] = f[3] * scaling;
  4073. }
  4074. normalize(out) {
  4075. ConchQuaternion._normalizeArray(this.elements, out.elements);
  4076. }
  4077. length() {
  4078. var f = this.elements;
  4079. var x = f[0], y = f[1], z = f[2], w = f[3];
  4080. return Math.sqrt(x * x + y * y + z * z + w * w);
  4081. }
  4082. rotateX(rad, out) {
  4083. var e = out.elements;
  4084. var f = this.elements;
  4085. rad *= 0.5;
  4086. var ax = f[0], ay = f[1], az = f[2], aw = f[3];
  4087. var bx = Math.sin(rad), bw = Math.cos(rad);
  4088. e[0] = ax * bw + aw * bx;
  4089. e[1] = ay * bw + az * bx;
  4090. e[2] = az * bw - ay * bx;
  4091. e[3] = aw * bw - ax * bx;
  4092. }
  4093. rotateY(rad, out) {
  4094. var e = out.elements;
  4095. var f = this.elements;
  4096. rad *= 0.5;
  4097. var ax = f[0], ay = f[1], az = f[2], aw = f[3], by = Math.sin(rad), bw = Math.cos(rad);
  4098. e[0] = ax * bw - az * by;
  4099. e[1] = ay * bw + aw * by;
  4100. e[2] = az * bw + ax * by;
  4101. e[3] = aw * bw - ay * by;
  4102. }
  4103. rotateZ(rad, out) {
  4104. var e = out.elements;
  4105. var f = this.elements;
  4106. rad *= 0.5;
  4107. var ax = f[0], ay = f[1], az = f[2], aw = f[3], bz = Math.sin(rad), bw = Math.cos(rad);
  4108. e[0] = ax * bw + ay * bz;
  4109. e[1] = ay * bw - ax * bz;
  4110. e[2] = az * bw + aw * bz;
  4111. e[3] = aw * bw - az * bz;
  4112. }
  4113. getYawPitchRoll(out) {
  4114. ConchVector3.transformQuat(ConchVector3.ForwardRH, this, ConchQuaternion.TEMPVector31);
  4115. ConchVector3.transformQuat(ConchVector3.Up, this, ConchQuaternion.TEMPVector32);
  4116. var upe = ConchQuaternion.TEMPVector32.elements;
  4117. ConchQuaternion.angleTo(ConchVector3.ZERO, ConchQuaternion.TEMPVector31, ConchQuaternion.TEMPVector33);
  4118. var anglee = ConchQuaternion.TEMPVector33.elements;
  4119. if (anglee[0] == Math.PI / 2) {
  4120. anglee[1] = ConchQuaternion.arcTanAngle(upe[2], upe[0]);
  4121. anglee[2] = 0;
  4122. }
  4123. else if (anglee[0] == -Math.PI / 2) {
  4124. anglee[1] = ConchQuaternion.arcTanAngle(-upe[2], -upe[0]);
  4125. anglee[2] = 0;
  4126. }
  4127. else {
  4128. Matrix4x4.createRotationY(-anglee[1], ConchQuaternion.TEMPMatrix0);
  4129. Matrix4x4.createRotationX(-anglee[0], ConchQuaternion.TEMPMatrix1);
  4130. ConchVector3.transformCoordinate(ConchQuaternion.TEMPVector32, ConchQuaternion.TEMPMatrix0, ConchQuaternion.TEMPVector32);
  4131. ConchVector3.transformCoordinate(ConchQuaternion.TEMPVector32, ConchQuaternion.TEMPMatrix1, ConchQuaternion.TEMPVector32);
  4132. anglee[2] = ConchQuaternion.arcTanAngle(upe[1], -upe[0]);
  4133. }
  4134. if (anglee[1] <= -Math.PI)
  4135. anglee[1] = Math.PI;
  4136. if (anglee[2] <= -Math.PI)
  4137. anglee[2] = Math.PI;
  4138. if (anglee[1] >= Math.PI && anglee[2] >= Math.PI) {
  4139. anglee[1] = 0;
  4140. anglee[2] = 0;
  4141. anglee[0] = Math.PI - anglee[0];
  4142. }
  4143. var oe = out.elements;
  4144. oe[0] = anglee[1];
  4145. oe[1] = anglee[0];
  4146. oe[2] = anglee[2];
  4147. }
  4148. invert(out) {
  4149. var e = out.elements;
  4150. var f = this.elements;
  4151. var a0 = f[0], a1 = f[1], a2 = f[2], a3 = f[3];
  4152. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  4153. var invDot = dot ? 1.0 / dot : 0;
  4154. e[0] = -a0 * invDot;
  4155. e[1] = -a1 * invDot;
  4156. e[2] = -a2 * invDot;
  4157. e[3] = a3 * invDot;
  4158. }
  4159. identity() {
  4160. var e = this.elements;
  4161. e[0] = 0;
  4162. e[1] = 0;
  4163. e[2] = 0;
  4164. e[3] = 1;
  4165. }
  4166. fromArray(array, offset = 0) {
  4167. this.elements[0] = array[offset + 0];
  4168. this.elements[1] = array[offset + 1];
  4169. this.elements[2] = array[offset + 2];
  4170. this.elements[3] = array[offset + 3];
  4171. }
  4172. cloneTo(destObject) {
  4173. var i, s, d;
  4174. s = this.elements;
  4175. d = destObject.elements;
  4176. if (s === d) {
  4177. return;
  4178. }
  4179. for (i = 0; i < 4; ++i) {
  4180. d[i] = s[i];
  4181. }
  4182. }
  4183. clone() {
  4184. var dest = new ConchQuaternion();
  4185. this.cloneTo(dest);
  4186. return dest;
  4187. }
  4188. equals(b) {
  4189. var ae = this.elements;
  4190. var be = b.elements;
  4191. return MathUtils3D.nearEqual(ae[0], be[0]) && MathUtils3D.nearEqual(ae[1], be[1]) && MathUtils3D.nearEqual(ae[2], be[2]) && MathUtils3D.nearEqual(ae[3], be[3]);
  4192. }
  4193. static rotationLookAt(forward, up, out) {
  4194. ConchQuaternion.lookAt(ConchVector3.ZERO, forward, up, out);
  4195. }
  4196. static lookAt(eye, target, up, out) {
  4197. Matrix3x3.lookAt(eye, target, up, ConchQuaternion._tempMatrix3x3);
  4198. ConchQuaternion.rotationMatrix(ConchQuaternion._tempMatrix3x3, out);
  4199. }
  4200. lengthSquared() {
  4201. var x = this.elements[0];
  4202. var y = this.elements[1];
  4203. var z = this.elements[2];
  4204. var w = this.elements[3];
  4205. return (x * x) + (y * y) + (z * z) + (w * w);
  4206. }
  4207. static invert(value, out) {
  4208. var vE = value.elements;
  4209. var oE = out.elements;
  4210. var lengthSq = value.lengthSquared();
  4211. if (!MathUtils3D.isZero(lengthSq)) {
  4212. lengthSq = 1.0 / lengthSq;
  4213. oE[0] = -vE[0] * lengthSq;
  4214. oE[1] = -vE[1] * lengthSq;
  4215. oE[2] = -vE[2] * lengthSq;
  4216. oE[3] = vE[3] * lengthSq;
  4217. }
  4218. }
  4219. static rotationMatrix(matrix3x3, out) {
  4220. var me = matrix3x3.elements;
  4221. var m11 = me[0];
  4222. var m12 = me[1];
  4223. var m13 = me[2];
  4224. var m21 = me[3];
  4225. var m22 = me[4];
  4226. var m23 = me[5];
  4227. var m31 = me[6];
  4228. var m32 = me[7];
  4229. var m33 = me[8];
  4230. var oe = out.elements;
  4231. var sqrt, half;
  4232. var scale = m11 + m22 + m33;
  4233. if (scale > 0) {
  4234. sqrt = Math.sqrt(scale + 1);
  4235. oe[3] = sqrt * 0.5;
  4236. sqrt = 0.5 / sqrt;
  4237. oe[0] = (m23 - m32) * sqrt;
  4238. oe[1] = (m31 - m13) * sqrt;
  4239. oe[2] = (m12 - m21) * sqrt;
  4240. }
  4241. else if ((m11 >= m22) && (m11 >= m33)) {
  4242. sqrt = Math.sqrt(1 + m11 - m22 - m33);
  4243. half = 0.5 / sqrt;
  4244. oe[0] = 0.5 * sqrt;
  4245. oe[1] = (m12 + m21) * half;
  4246. oe[2] = (m13 + m31) * half;
  4247. oe[3] = (m23 - m32) * half;
  4248. }
  4249. else if (m22 > m33) {
  4250. sqrt = Math.sqrt(1 + m22 - m11 - m33);
  4251. half = 0.5 / sqrt;
  4252. oe[0] = (m21 + m12) * half;
  4253. oe[1] = 0.5 * sqrt;
  4254. oe[2] = (m32 + m23) * half;
  4255. oe[3] = (m31 - m13) * half;
  4256. }
  4257. else {
  4258. sqrt = Math.sqrt(1 + m33 - m11 - m22);
  4259. half = 0.5 / sqrt;
  4260. oe[0] = (m31 + m13) * half;
  4261. oe[1] = (m32 + m23) * half;
  4262. oe[2] = 0.5 * sqrt;
  4263. oe[3] = (m12 - m21) * half;
  4264. }
  4265. }
  4266. }
  4267. ConchQuaternion.TEMPVector30 = new ConchVector3();
  4268. ConchQuaternion.TEMPVector31 = new ConchVector3();
  4269. ConchQuaternion.TEMPVector32 = new ConchVector3();
  4270. ConchQuaternion.TEMPVector33 = new ConchVector3();
  4271. ConchQuaternion.TEMPMatrix0 = new Matrix4x4();
  4272. ConchQuaternion.TEMPMatrix1 = new Matrix4x4();
  4273. ConchQuaternion._tempMatrix3x3 = new Matrix3x3();
  4274. ConchQuaternion.DEFAULT = new ConchQuaternion();
  4275. ConchQuaternion.NAN = new ConchQuaternion(NaN, NaN, NaN, NaN);
  4276. class AnimatorState {
  4277. constructor() {
  4278. this._referenceCount = 0;
  4279. this._clip = null;
  4280. this._nodeOwners = [];
  4281. this._currentFrameIndices = null;
  4282. this._realtimeDatas = [];
  4283. this._scripts = null;
  4284. this.speed = 1.0;
  4285. this.clipStart = 0.0;
  4286. this.clipEnd = 1.0;
  4287. }
  4288. get clip() {
  4289. return this._clip;
  4290. }
  4291. set clip(value) {
  4292. if (this._clip !== value) {
  4293. if (this._clip)
  4294. (this._referenceCount > 0) && (this._clip._removeReference(this._referenceCount));
  4295. if (value) {
  4296. var realtimeDatas = this._realtimeDatas;
  4297. var clipNodes = value._nodes;
  4298. var count = clipNodes.count;
  4299. this._currentFrameIndices = new Int16Array(count);
  4300. this._resetFrameIndices();
  4301. (this._referenceCount > 0) && (value._addReference(this._referenceCount));
  4302. this._realtimeDatas.length = count;
  4303. for (var i = 0; i < count; i++) {
  4304. switch (clipNodes.getNodeByIndex(i).type) {
  4305. case 0:
  4306. break;
  4307. case 1:
  4308. case 3:
  4309. case 4:
  4310. realtimeDatas[i] = Laya.Render.supportWebGLPlusAnimation ? new ConchVector3 : new Vector3();
  4311. break;
  4312. case 2:
  4313. realtimeDatas[i] = Laya.Render.supportWebGLPlusAnimation ? new ConchQuaternion : new Quaternion();
  4314. break;
  4315. default:
  4316. throw "AnimationClipParser04:unknown type.";
  4317. }
  4318. }
  4319. }
  4320. this._clip = value;
  4321. }
  4322. }
  4323. _getReferenceCount() {
  4324. return this._referenceCount;
  4325. }
  4326. _addReference(count = 1) {
  4327. (this._clip) && (this._clip._addReference(count));
  4328. this._referenceCount += count;
  4329. }
  4330. _removeReference(count = 1) {
  4331. (this._clip) && (this._clip._removeReference(count));
  4332. this._referenceCount -= count;
  4333. }
  4334. _clearReference() {
  4335. this._removeReference(-this._referenceCount);
  4336. }
  4337. _resetFrameIndices() {
  4338. for (var i = 0, n = this._currentFrameIndices.length; i < n; i++)
  4339. this._currentFrameIndices[i] = -1;
  4340. }
  4341. addScript(type) {
  4342. var script = new type();
  4343. this._scripts = this._scripts || [];
  4344. this._scripts.push(script);
  4345. return script;
  4346. }
  4347. getScript(type) {
  4348. if (this._scripts) {
  4349. for (var i = 0, n = this._scripts.length; i < n; i++) {
  4350. var script = this._scripts[i];
  4351. if (script instanceof type)
  4352. return script;
  4353. }
  4354. }
  4355. return null;
  4356. }
  4357. getScripts(type) {
  4358. var coms;
  4359. if (this._scripts) {
  4360. for (var i = 0, n = this._scripts.length; i < n; i++) {
  4361. var script = this._scripts[i];
  4362. if (script instanceof type) {
  4363. coms = coms || [];
  4364. coms.push(script);
  4365. }
  4366. }
  4367. }
  4368. return coms;
  4369. }
  4370. cloneTo(destObject) {
  4371. var dest = destObject;
  4372. dest.name = this.name;
  4373. dest.speed = this.speed;
  4374. dest.clipStart = this.clipStart;
  4375. dest.clipEnd = this.clipEnd;
  4376. dest.clip = this._clip;
  4377. }
  4378. clone() {
  4379. var dest = new AnimatorState();
  4380. this.cloneTo(dest);
  4381. return dest;
  4382. }
  4383. }
  4384. class KeyframeNodeOwner {
  4385. constructor() {
  4386. this.indexInList = -1;
  4387. this.referenceCount = 0;
  4388. this.updateMark = -1;
  4389. this.type = -1;
  4390. this.fullPath = null;
  4391. this.propertyOwner = null;
  4392. this.property = null;
  4393. this.defaultValue = null;
  4394. this.crossFixedValue = null;
  4395. }
  4396. saveCrossFixedValue() {
  4397. var pro = this.propertyOwner;
  4398. if (pro) {
  4399. switch (this.type) {
  4400. case 0:
  4401. var proPat = this.property;
  4402. var m = proPat.length - 1;
  4403. for (var j = 0; j < m; j++) {
  4404. pro = pro[proPat[j]];
  4405. if (!pro)
  4406. break;
  4407. }
  4408. this.crossFixedValue = pro[proPat[m]];
  4409. break;
  4410. case 1:
  4411. var locPos = pro.localPosition;
  4412. this.crossFixedValue || (this.crossFixedValue = new Vector3());
  4413. this.crossFixedValue.x = locPos.x;
  4414. this.crossFixedValue.y = locPos.y;
  4415. this.crossFixedValue.z = locPos.z;
  4416. break;
  4417. case 2:
  4418. var locRot = pro.localRotation;
  4419. this.crossFixedValue || (this.crossFixedValue = new Quaternion());
  4420. this.crossFixedValue.x = locRot.x;
  4421. this.crossFixedValue.y = locRot.y;
  4422. this.crossFixedValue.z = locRot.z;
  4423. this.crossFixedValue.w = locRot.w;
  4424. break;
  4425. case 3:
  4426. var locSca = pro.localScale;
  4427. this.crossFixedValue || (this.crossFixedValue = new Vector3());
  4428. this.crossFixedValue.x = locSca.x;
  4429. this.crossFixedValue.y = locSca.y;
  4430. this.crossFixedValue.z = locSca.z;
  4431. break;
  4432. case 4:
  4433. var locEul = pro.localRotationEuler;
  4434. this.crossFixedValue || (this.crossFixedValue = new Vector3());
  4435. this.crossFixedValue.x = locEul.x;
  4436. this.crossFixedValue.y = locEul.y;
  4437. this.crossFixedValue.z = locEul.z;
  4438. break;
  4439. default:
  4440. throw "Animator:unknown type.";
  4441. }
  4442. }
  4443. }
  4444. }
  4445. class Animator extends Laya.Component {
  4446. constructor() {
  4447. super();
  4448. this._keyframeNodeOwners = [];
  4449. this._linkAvatarSpritesData = {};
  4450. this._linkAvatarSprites = [];
  4451. this._renderableSprites = [];
  4452. this.cullingMode = Animator.CULLINGMODE_CULLCOMPLETELY;
  4453. this._controllerLayers = [];
  4454. this._linkSprites = {};
  4455. this._speed = 1.0;
  4456. this._keyframeNodeOwnerMap = {};
  4457. this._updateMark = 0;
  4458. }
  4459. static _update(scene) {
  4460. var pool = scene._animatorPool;
  4461. var elements = pool.elements;
  4462. for (var i = 0, n = pool.length; i < n; i++) {
  4463. var animator = elements[i];
  4464. (animator && animator.enabled) && (animator._update());
  4465. }
  4466. }
  4467. get speed() {
  4468. return this._speed;
  4469. }
  4470. set speed(value) {
  4471. this._speed = value;
  4472. }
  4473. _linkToSprites(linkSprites) {
  4474. for (var k in linkSprites) {
  4475. var nodeOwner = this.owner;
  4476. var path = linkSprites[k];
  4477. for (var j = 0, m = path.length; j < m; j++) {
  4478. var p = path[j];
  4479. if (p === "") {
  4480. break;
  4481. }
  4482. else {
  4483. nodeOwner = nodeOwner.getChildByName(p);
  4484. if (!nodeOwner)
  4485. break;
  4486. }
  4487. }
  4488. (nodeOwner) && (this.linkSprite3DToAvatarNode(k, nodeOwner));
  4489. }
  4490. }
  4491. _addKeyframeNodeOwner(clipOwners, node, propertyOwner) {
  4492. var nodeIndex = node._indexInList;
  4493. var fullPath = node.fullPath;
  4494. var keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath];
  4495. if (keyframeNodeOwner) {
  4496. keyframeNodeOwner.referenceCount++;
  4497. clipOwners[nodeIndex] = keyframeNodeOwner;
  4498. }
  4499. else {
  4500. var property = propertyOwner;
  4501. for (var i = 0, n = node.propertyCount; i < n; i++) {
  4502. property = property[node.getPropertyByIndex(i)];
  4503. if (!property)
  4504. break;
  4505. }
  4506. keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath] = new KeyframeNodeOwner();
  4507. keyframeNodeOwner.fullPath = fullPath;
  4508. keyframeNodeOwner.indexInList = this._keyframeNodeOwners.length;
  4509. keyframeNodeOwner.referenceCount = 1;
  4510. keyframeNodeOwner.propertyOwner = propertyOwner;
  4511. var propertyCount = node.propertyCount;
  4512. var propertys = [];
  4513. for (i = 0; i < propertyCount; i++)
  4514. propertys[i] = node.getPropertyByIndex(i);
  4515. keyframeNodeOwner.property = propertys;
  4516. keyframeNodeOwner.type = node.type;
  4517. if (property) {
  4518. if (node.type === 0) {
  4519. keyframeNodeOwner.defaultValue = property;
  4520. }
  4521. else {
  4522. var defaultValue = new property.constructor();
  4523. property.cloneTo(defaultValue);
  4524. keyframeNodeOwner.defaultValue = defaultValue;
  4525. }
  4526. }
  4527. this._keyframeNodeOwners.push(keyframeNodeOwner);
  4528. clipOwners[nodeIndex] = keyframeNodeOwner;
  4529. }
  4530. }
  4531. _removeKeyframeNodeOwner(nodeOwners, node) {
  4532. var fullPath = node.fullPath;
  4533. var keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath];
  4534. if (keyframeNodeOwner) {
  4535. keyframeNodeOwner.referenceCount--;
  4536. if (keyframeNodeOwner.referenceCount === 0) {
  4537. delete this._keyframeNodeOwnerMap[fullPath];
  4538. this._keyframeNodeOwners.splice(this._keyframeNodeOwners.indexOf(keyframeNodeOwner), 1);
  4539. }
  4540. nodeOwners[node._indexInList] = null;
  4541. }
  4542. }
  4543. _getOwnersByClip(clipStateInfo) {
  4544. var frameNodes = clipStateInfo._clip._nodes;
  4545. var frameNodesCount = frameNodes.count;
  4546. var nodeOwners = clipStateInfo._nodeOwners;
  4547. nodeOwners.length = frameNodesCount;
  4548. for (var i = 0; i < frameNodesCount; i++) {
  4549. var node = frameNodes.getNodeByIndex(i);
  4550. var property = this._avatar ? this._avatarNodeMap[this._avatar._rootNode.name] : this.owner;
  4551. for (var j = 0, m = node.ownerPathCount; j < m; j++) {
  4552. var ownPat = node.getOwnerPathByIndex(j);
  4553. if (ownPat === "") {
  4554. break;
  4555. }
  4556. else {
  4557. property = property.getChildByName(ownPat);
  4558. if (!property)
  4559. break;
  4560. }
  4561. }
  4562. if (property) {
  4563. var propertyOwner = node.propertyOwner;
  4564. (propertyOwner) && (property = property[propertyOwner]);
  4565. property && this._addKeyframeNodeOwner(nodeOwners, node, property);
  4566. }
  4567. }
  4568. }
  4569. _updatePlayer(animatorState, playState, elapsedTime, islooping) {
  4570. var clipDuration = animatorState._clip._duration * (animatorState.clipEnd - animatorState.clipStart);
  4571. var lastElapsedTime = playState._elapsedTime;
  4572. var elapsedPlaybackTime = lastElapsedTime + elapsedTime;
  4573. playState._lastElapsedTime = lastElapsedTime;
  4574. playState._elapsedTime = elapsedPlaybackTime;
  4575. var normalizedTime = elapsedPlaybackTime / clipDuration;
  4576. playState._normalizedTime = normalizedTime;
  4577. var playTime = normalizedTime % 1.0;
  4578. playState._normalizedPlayTime = playTime < 0 ? playTime + 1.0 : playTime;
  4579. playState._duration = clipDuration;
  4580. var scripts = animatorState._scripts;
  4581. if ((!islooping && elapsedPlaybackTime >= clipDuration)) {
  4582. playState._finish = true;
  4583. playState._elapsedTime = clipDuration;
  4584. playState._normalizedPlayTime = 1.0;
  4585. if (scripts) {
  4586. for (var i = 0, n = scripts.length; i < n; i++)
  4587. scripts[i].onStateExit();
  4588. }
  4589. return;
  4590. }
  4591. if (scripts) {
  4592. for (i = 0, n = scripts.length; i < n; i++)
  4593. scripts[i].onStateUpdate();
  4594. }
  4595. }
  4596. _eventScript(scripts, events, eventIndex, endTime, front) {
  4597. if (front) {
  4598. for (var n = events.length; eventIndex < n; eventIndex++) {
  4599. var event = events[eventIndex];
  4600. if (event.time <= endTime) {
  4601. for (var j = 0, m = scripts.length; j < m; j++) {
  4602. var script = scripts[j];
  4603. var fun = script[event.eventName];
  4604. (fun) && (fun.apply(script, event.params));
  4605. }
  4606. }
  4607. else {
  4608. break;
  4609. }
  4610. }
  4611. }
  4612. else {
  4613. for (; eventIndex >= 0; eventIndex--) {
  4614. event = events[eventIndex];
  4615. if (event.time >= endTime) {
  4616. for (j = 0, m = scripts.length; j < m; j++) {
  4617. script = scripts[j];
  4618. fun = script[event.eventName];
  4619. (fun) && (fun.apply(script, event.params));
  4620. }
  4621. }
  4622. else {
  4623. break;
  4624. }
  4625. }
  4626. }
  4627. return eventIndex;
  4628. }
  4629. _updateEventScript(stateInfo, playStateInfo) {
  4630. var scripts = this.owner._scripts;
  4631. if (scripts) {
  4632. var clip = stateInfo._clip;
  4633. var events = clip._animationEvents;
  4634. var clipDuration = clip._duration;
  4635. var elapsedTime = playStateInfo._elapsedTime;
  4636. var time = elapsedTime % clipDuration;
  4637. var loopCount = Math.abs(Math.floor(elapsedTime / clipDuration) - Math.floor(playStateInfo._lastElapsedTime / clipDuration));
  4638. var frontPlay = playStateInfo._elapsedTime >= playStateInfo._lastElapsedTime;
  4639. if (playStateInfo._lastIsFront !== frontPlay) {
  4640. if (frontPlay)
  4641. playStateInfo._playEventIndex++;
  4642. else
  4643. playStateInfo._playEventIndex--;
  4644. playStateInfo._lastIsFront = frontPlay;
  4645. }
  4646. if (frontPlay) {
  4647. playStateInfo._playEventIndex = this._eventScript(scripts, events, playStateInfo._playEventIndex, loopCount > 0 ? clipDuration : time, true);
  4648. for (var i = 0, n = loopCount - 1; i < n; i++)
  4649. this._eventScript(scripts, events, 0, clipDuration, true);
  4650. (loopCount > 0 && time > 0) && (playStateInfo._playEventIndex = this._eventScript(scripts, events, 0, time, true));
  4651. }
  4652. else {
  4653. playStateInfo._playEventIndex = this._eventScript(scripts, events, playStateInfo._playEventIndex, loopCount > 0 ? 0 : time, false);
  4654. var eventIndex = events.length - 1;
  4655. for (i = 0, n = loopCount - 1; i < n; i++)
  4656. this._eventScript(scripts, events, eventIndex, 0, false);
  4657. (loopCount > 0 && time > 0) && (playStateInfo._playEventIndex = this._eventScript(scripts, events, eventIndex, time, false));
  4658. }
  4659. }
  4660. }
  4661. _updateClipDatas(animatorState, addtive, playStateInfo, scale) {
  4662. var clip = animatorState._clip;
  4663. var clipDuration = clip._duration;
  4664. var curPlayTime = animatorState.clipStart * clipDuration + playStateInfo._normalizedPlayTime * playStateInfo._duration;
  4665. var currentFrameIndices = animatorState._currentFrameIndices;
  4666. var frontPlay = playStateInfo._elapsedTime > playStateInfo._lastElapsedTime;
  4667. clip._evaluateClipDatasRealTime(clip._nodes, curPlayTime, currentFrameIndices, addtive, frontPlay, animatorState._realtimeDatas);
  4668. }
  4669. _applyFloat(pro, proName, nodeOwner, additive, weight, isFirstLayer, data) {
  4670. if (nodeOwner.updateMark === this._updateMark) {
  4671. if (additive) {
  4672. pro[proName] += weight * (data);
  4673. }
  4674. else {
  4675. var oriValue = pro[proName];
  4676. pro[proName] = oriValue + weight * (data - oriValue);
  4677. }
  4678. }
  4679. else {
  4680. if (isFirstLayer) {
  4681. if (additive)
  4682. pro[proName] = nodeOwner.defaultValue + data;
  4683. else
  4684. pro[proName] = data;
  4685. }
  4686. else {
  4687. if (additive) {
  4688. pro[proName] = nodeOwner.defaultValue + weight * (data);
  4689. }
  4690. else {
  4691. var defValue = nodeOwner.defaultValue;
  4692. pro[proName] = defValue + weight * (data - defValue);
  4693. }
  4694. }
  4695. }
  4696. }
  4697. _applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, data, out) {
  4698. if (nodeOwner.updateMark === this._updateMark) {
  4699. if (additive) {
  4700. out.x += weight * data.x;
  4701. out.y += weight * data.y;
  4702. out.z += weight * data.z;
  4703. }
  4704. else {
  4705. var oriX = out.x;
  4706. var oriY = out.y;
  4707. var oriZ = out.z;
  4708. out.x = oriX + weight * (data.x - oriX);
  4709. out.y = oriY + weight * (data.y - oriY);
  4710. out.z = oriZ + weight * (data.z - oriZ);
  4711. }
  4712. }
  4713. else {
  4714. if (isFirstLayer) {
  4715. if (additive) {
  4716. var defValue = nodeOwner.defaultValue;
  4717. out.x = defValue.x + data.x;
  4718. out.y = defValue.y + data.y;
  4719. out.z = defValue.z + data.z;
  4720. }
  4721. else {
  4722. out.x = data.x;
  4723. out.y = data.y;
  4724. out.z = data.z;
  4725. }
  4726. }
  4727. else {
  4728. defValue = nodeOwner.defaultValue;
  4729. if (additive) {
  4730. out.x = defValue.x + weight * data.x;
  4731. out.y = defValue.y + weight * data.y;
  4732. out.z = defValue.z + weight * data.z;
  4733. }
  4734. else {
  4735. var defX = defValue.x;
  4736. var defY = defValue.y;
  4737. var defZ = defValue.z;
  4738. out.x = defX + weight * (data.x - defX);
  4739. out.y = defY + weight * (data.y - defY);
  4740. out.z = defZ + weight * (data.z - defZ);
  4741. }
  4742. }
  4743. }
  4744. }
  4745. _applyRotation(nodeOwner, additive, weight, isFirstLayer, clipRot, localRotation) {
  4746. if (nodeOwner.updateMark === this._updateMark) {
  4747. if (additive) {
  4748. var tempQuat = Animator._tempQuaternion1;
  4749. Utils3D.quaternionWeight(clipRot, weight, tempQuat);
  4750. tempQuat.normalize(tempQuat);
  4751. Quaternion.multiply(localRotation, tempQuat, localRotation);
  4752. }
  4753. else {
  4754. Quaternion.lerp(localRotation, clipRot, weight, localRotation);
  4755. }
  4756. }
  4757. else {
  4758. if (isFirstLayer) {
  4759. if (additive) {
  4760. var defaultRot = nodeOwner.defaultValue;
  4761. Quaternion.multiply(defaultRot, clipRot, localRotation);
  4762. }
  4763. else {
  4764. localRotation.x = clipRot.x;
  4765. localRotation.y = clipRot.y;
  4766. localRotation.z = clipRot.z;
  4767. localRotation.w = clipRot.w;
  4768. }
  4769. }
  4770. else {
  4771. defaultRot = nodeOwner.defaultValue;
  4772. if (additive) {
  4773. tempQuat = Animator._tempQuaternion1;
  4774. Utils3D.quaternionWeight(clipRot, weight, tempQuat);
  4775. tempQuat.normalize(tempQuat);
  4776. Quaternion.multiply(defaultRot, tempQuat, localRotation);
  4777. }
  4778. else {
  4779. Quaternion.lerp(defaultRot, clipRot, weight, localRotation);
  4780. }
  4781. }
  4782. }
  4783. }
  4784. _applyScale(nodeOwner, additive, weight, isFirstLayer, clipSca, localScale) {
  4785. if (nodeOwner.updateMark === this._updateMark) {
  4786. if (additive) {
  4787. var scale = Animator._tempVector31;
  4788. Utils3D.scaleWeight(clipSca, weight, scale);
  4789. localScale.x = localScale.x * scale.x;
  4790. localScale.y = localScale.y * scale.y;
  4791. localScale.z = localScale.z * scale.z;
  4792. }
  4793. else {
  4794. Utils3D.scaleBlend(localScale, clipSca, weight, localScale);
  4795. }
  4796. }
  4797. else {
  4798. if (isFirstLayer) {
  4799. if (additive) {
  4800. var defaultSca = nodeOwner.defaultValue;
  4801. localScale.x = defaultSca.x * clipSca.x;
  4802. localScale.y = defaultSca.y * clipSca.y;
  4803. localScale.z = defaultSca.z * clipSca.z;
  4804. }
  4805. else {
  4806. localScale.x = clipSca.x;
  4807. localScale.y = clipSca.y;
  4808. localScale.z = clipSca.z;
  4809. }
  4810. }
  4811. else {
  4812. defaultSca = nodeOwner.defaultValue;
  4813. if (additive) {
  4814. scale = Animator._tempVector31;
  4815. Utils3D.scaleWeight(clipSca, weight, scale);
  4816. localScale.x = defaultSca.x * scale.x;
  4817. localScale.y = defaultSca.y * scale.y;
  4818. localScale.z = defaultSca.z * scale.z;
  4819. }
  4820. else {
  4821. Utils3D.scaleBlend(defaultSca, clipSca, weight, localScale);
  4822. }
  4823. }
  4824. }
  4825. }
  4826. _applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight) {
  4827. var pro = nodeOwner.propertyOwner;
  4828. if (pro) {
  4829. switch (nodeOwner.type) {
  4830. case 0:
  4831. var proPat = nodeOwner.property;
  4832. var m = proPat.length - 1;
  4833. for (var j = 0; j < m; j++) {
  4834. pro = pro[proPat[j]];
  4835. if (!pro)
  4836. break;
  4837. }
  4838. var crossValue = srcValue + crossWeight * (desValue - srcValue);
  4839. this._applyFloat(pro, proPat[m], nodeOwner, additive, weight, isFirstLayer, crossValue);
  4840. break;
  4841. case 1:
  4842. var localPos = pro.localPosition;
  4843. var position = Animator._tempVector30;
  4844. var srcX = srcValue.x, srcY = srcValue.y, srcZ = srcValue.z;
  4845. position.x = srcX + crossWeight * (desValue.x - srcX);
  4846. position.y = srcY + crossWeight * (desValue.y - srcY);
  4847. position.z = srcZ + crossWeight * (desValue.z - srcZ);
  4848. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, position, localPos);
  4849. pro.localPosition = localPos;
  4850. break;
  4851. case 2:
  4852. var localRot = pro.localRotation;
  4853. var rotation = Animator._tempQuaternion0;
  4854. Quaternion.lerp(srcValue, desValue, crossWeight, rotation);
  4855. this._applyRotation(nodeOwner, additive, weight, isFirstLayer, rotation, localRot);
  4856. pro.localRotation = localRot;
  4857. break;
  4858. case 3:
  4859. var localSca = pro.localScale;
  4860. var scale = Animator._tempVector30;
  4861. Utils3D.scaleBlend(srcValue, desValue, crossWeight, scale);
  4862. this._applyScale(nodeOwner, additive, weight, isFirstLayer, scale, localSca);
  4863. pro.localScale = localSca;
  4864. break;
  4865. case 4:
  4866. var localEuler = pro.localRotationEuler;
  4867. var rotationEuler = Animator._tempVector30;
  4868. srcX = srcValue.x, srcY = srcValue.y, srcZ = srcValue.z;
  4869. rotationEuler.x = srcX + crossWeight * (desValue.x - srcX);
  4870. rotationEuler.y = srcY + crossWeight * (desValue.y - srcY);
  4871. rotationEuler.z = srcZ + crossWeight * (desValue.z - srcZ);
  4872. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, rotationEuler, localEuler);
  4873. pro.localRotationEuler = localEuler;
  4874. break;
  4875. }
  4876. nodeOwner.updateMark = this._updateMark;
  4877. }
  4878. }
  4879. _setClipDatasToNode(stateInfo, additive, weight, isFirstLayer) {
  4880. var realtimeDatas = stateInfo._realtimeDatas;
  4881. var nodes = stateInfo._clip._nodes;
  4882. var nodeOwners = stateInfo._nodeOwners;
  4883. for (var i = 0, n = nodes.count; i < n; i++) {
  4884. var nodeOwner = nodeOwners[i];
  4885. if (nodeOwner) {
  4886. var pro = nodeOwner.propertyOwner;
  4887. if (pro) {
  4888. switch (nodeOwner.type) {
  4889. case 0:
  4890. var proPat = nodeOwner.property;
  4891. var m = proPat.length - 1;
  4892. for (var j = 0; j < m; j++) {
  4893. pro = pro[proPat[j]];
  4894. if (!pro)
  4895. break;
  4896. }
  4897. this._applyFloat(pro, proPat[m], nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i]);
  4898. break;
  4899. case 1:
  4900. var localPos = pro.localPosition;
  4901. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localPos);
  4902. pro.localPosition = localPos;
  4903. break;
  4904. case 2:
  4905. var localRot = pro.localRotation;
  4906. this._applyRotation(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localRot);
  4907. pro.localRotation = localRot;
  4908. break;
  4909. case 3:
  4910. var localSca = pro.localScale;
  4911. this._applyScale(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localSca);
  4912. pro.localScale = localSca;
  4913. break;
  4914. case 4:
  4915. var localEuler = pro.localRotationEuler;
  4916. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localEuler);
  4917. pro.localRotationEuler = localEuler;
  4918. break;
  4919. }
  4920. nodeOwner.updateMark = this._updateMark;
  4921. }
  4922. }
  4923. }
  4924. }
  4925. _setCrossClipDatasToNode(controllerLayer, srcState, destState, crossWeight, isFirstLayer) {
  4926. var nodeOwners = controllerLayer._crossNodesOwners;
  4927. var ownerCount = controllerLayer._crossNodesOwnersCount;
  4928. var additive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  4929. var weight = controllerLayer.defaultWeight;
  4930. var destRealtimeDatas = destState._realtimeDatas;
  4931. var destDataIndices = controllerLayer._destCrossClipNodeIndices;
  4932. var destNodeOwners = destState._nodeOwners;
  4933. var srcRealtimeDatas = srcState._realtimeDatas;
  4934. var srcDataIndices = controllerLayer._srcCrossClipNodeIndices;
  4935. var srcNodeOwners = srcState._nodeOwners;
  4936. for (var i = 0; i < ownerCount; i++) {
  4937. var nodeOwner = nodeOwners[i];
  4938. if (nodeOwner) {
  4939. var srcIndex = srcDataIndices[i];
  4940. var destIndex = destDataIndices[i];
  4941. var srcValue = srcIndex !== -1 ? srcRealtimeDatas[srcIndex] : destNodeOwners[destIndex].defaultValue;
  4942. var desValue = destIndex !== -1 ? destRealtimeDatas[destIndex] : srcNodeOwners[srcIndex].defaultValue;
  4943. this._applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight);
  4944. }
  4945. }
  4946. }
  4947. _setFixedCrossClipDatasToNode(controllerLayer, destState, crossWeight, isFirstLayer) {
  4948. var nodeOwners = controllerLayer._crossNodesOwners;
  4949. var ownerCount = controllerLayer._crossNodesOwnersCount;
  4950. var additive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  4951. var weight = controllerLayer.defaultWeight;
  4952. var destRealtimeDatas = destState._realtimeDatas;
  4953. var destDataIndices = controllerLayer._destCrossClipNodeIndices;
  4954. for (var i = 0; i < ownerCount; i++) {
  4955. var nodeOwner = nodeOwners[i];
  4956. if (nodeOwner) {
  4957. var destIndex = destDataIndices[i];
  4958. var srcValue = nodeOwner.crossFixedValue;
  4959. var desValue = destIndex !== -1 ? destRealtimeDatas[destIndex] : nodeOwner.defaultValue;
  4960. this._applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight);
  4961. }
  4962. }
  4963. }
  4964. _revertDefaultKeyframeNodes(clipStateInfo) {
  4965. var nodeOwners = clipStateInfo._nodeOwners;
  4966. for (var i = 0, n = nodeOwners.length; i < n; i++) {
  4967. var nodeOwner = nodeOwners[i];
  4968. if (nodeOwner) {
  4969. var pro = nodeOwner.propertyOwner;
  4970. if (pro) {
  4971. switch (nodeOwner.type) {
  4972. case 0:
  4973. var proPat = nodeOwner.property;
  4974. var m = proPat.length - 1;
  4975. for (var j = 0; j < m; j++) {
  4976. pro = pro[proPat[j]];
  4977. if (!pro)
  4978. break;
  4979. }
  4980. pro[proPat[m]] = nodeOwner.defaultValue;
  4981. break;
  4982. case 1:
  4983. var locPos = pro.localPosition;
  4984. var def = nodeOwner.defaultValue;
  4985. locPos.x = def.x;
  4986. locPos.y = def.y;
  4987. locPos.z = def.z;
  4988. pro.localPosition = locPos;
  4989. break;
  4990. case 2:
  4991. var locRot = pro.localRotation;
  4992. var defQua = nodeOwner.defaultValue;
  4993. locRot.x = defQua.x;
  4994. locRot.y = defQua.y;
  4995. locRot.z = defQua.z;
  4996. locRot.w = defQua.w;
  4997. pro.localRotation = locRot;
  4998. break;
  4999. case 3:
  5000. var locSca = pro.localScale;
  5001. def = nodeOwner.defaultValue;
  5002. locSca.x = def.x;
  5003. locSca.y = def.y;
  5004. locSca.z = def.z;
  5005. pro.localScale = locSca;
  5006. break;
  5007. case 4:
  5008. var locEul = pro.localRotationEuler;
  5009. def = nodeOwner.defaultValue;
  5010. locEul.x = def.x;
  5011. locEul.y = def.y;
  5012. locEul.z = def.z;
  5013. pro.localRotationEuler = locEul;
  5014. break;
  5015. default:
  5016. throw "Animator:unknown type.";
  5017. }
  5018. }
  5019. }
  5020. }
  5021. }
  5022. _onAdded() {
  5023. var parent = this.owner._parent;
  5024. this.owner._setHierarchyAnimator(this, parent ? parent._hierarchyAnimator : null);
  5025. this.owner._changeAnimatorToLinkSprite3DNoAvatar(this, true, []);
  5026. }
  5027. _onDestroy() {
  5028. for (var i = 0, n = this._controllerLayers.length; i < n; i++)
  5029. this._controllerLayers[i]._removeReference();
  5030. var parent = this.owner._parent;
  5031. this.owner._clearHierarchyAnimator(this, parent ? parent._hierarchyAnimator : null);
  5032. }
  5033. _onEnable() {
  5034. this.owner._scene._animatorPool.add(this);
  5035. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  5036. if (this._controllerLayers[i].playOnWake) {
  5037. var defaultClip = this.getDefaultState(i);
  5038. (defaultClip) && (this.play(null, i, 0));
  5039. }
  5040. }
  5041. }
  5042. _onDisable() {
  5043. this.owner._scene._animatorPool.remove(this);
  5044. }
  5045. _handleSpriteOwnersBySprite(isLink, path, sprite) {
  5046. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  5047. var clipStateInfos = this._controllerLayers[i]._states;
  5048. for (var j = 0, m = clipStateInfos.length; j < m; j++) {
  5049. var clipStateInfo = clipStateInfos[j];
  5050. var clip = clipStateInfo._clip;
  5051. var nodePath = path.join("/");
  5052. var ownersNodes = clip._nodesMap[nodePath];
  5053. if (ownersNodes) {
  5054. var nodeOwners = clipStateInfo._nodeOwners;
  5055. for (var k = 0, p = ownersNodes.length; k < p; k++) {
  5056. if (isLink)
  5057. this._addKeyframeNodeOwner(nodeOwners, ownersNodes[k], sprite);
  5058. else
  5059. this._removeKeyframeNodeOwner(nodeOwners, ownersNodes[k]);
  5060. }
  5061. }
  5062. }
  5063. }
  5064. }
  5065. _parse(data) {
  5066. var avatarData = data.avatar;
  5067. if (avatarData) {
  5068. this.avatar = Laya.Loader.getRes(avatarData.path);
  5069. var linkSprites = avatarData.linkSprites;
  5070. this._linkSprites = linkSprites;
  5071. this._linkToSprites(linkSprites);
  5072. }
  5073. var clipPaths = data.clipPaths;
  5074. var play = data.playOnWake;
  5075. var layersData = data.layers;
  5076. for (var i = 0; i < layersData.length; i++) {
  5077. var layerData = layersData[i];
  5078. var animatorLayer = new AnimatorControllerLayer(layerData.name);
  5079. if (i === 0)
  5080. animatorLayer.defaultWeight = 1.0;
  5081. else
  5082. animatorLayer.defaultWeight = layerData.weight;
  5083. var blendingModeData = layerData.blendingMode;
  5084. (blendingModeData) && (animatorLayer.blendingMode = blendingModeData);
  5085. this.addControllerLayer(animatorLayer);
  5086. var states = layerData.states;
  5087. for (var j = 0, m = states.length; j < m; j++) {
  5088. var state = states[j];
  5089. var clipPath = state.clipPath;
  5090. if (clipPath) {
  5091. var name = state.name;
  5092. var motion;
  5093. motion = Laya.Loader.getRes(clipPath);
  5094. if (motion) {
  5095. var animatorState = new AnimatorState();
  5096. animatorState.name = name;
  5097. animatorState.clip = motion;
  5098. animatorLayer.addState(animatorState);
  5099. (j === 0) && (this.getControllerLayer(i).defaultState = animatorState);
  5100. }
  5101. }
  5102. }
  5103. (play !== undefined) && (animatorLayer.playOnWake = play);
  5104. }
  5105. var cullingModeData = data.cullingMode;
  5106. (cullingModeData !== undefined) && (this.cullingMode = cullingModeData);
  5107. }
  5108. _update() {
  5109. var timer = this.owner._scene.timer;
  5110. var delta = timer._delta / 1000.0;
  5111. if (this._speed === 0 || delta === 0)
  5112. return;
  5113. var needRender;
  5114. if (this.cullingMode === Animator.CULLINGMODE_CULLCOMPLETELY) {
  5115. needRender = false;
  5116. for (var i = 0, n = this._renderableSprites.length; i < n; i++) {
  5117. if (this._renderableSprites[i]._render._visible) {
  5118. needRender = true;
  5119. break;
  5120. }
  5121. }
  5122. }
  5123. else {
  5124. needRender = true;
  5125. }
  5126. this._updateMark++;
  5127. var timerScale = timer.scale;
  5128. for (i = 0, n = this._controllerLayers.length; i < n; i++) {
  5129. var controllerLayer = this._controllerLayers[i];
  5130. var playStateInfo = controllerLayer._playStateInfo;
  5131. var crossPlayStateInfo = controllerLayer._crossPlayStateInfo;
  5132. addtive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  5133. switch (controllerLayer._playType) {
  5134. case 0:
  5135. var animatorState = playStateInfo._currentState;
  5136. var clip = animatorState._clip;
  5137. var speed = this._speed * animatorState.speed;
  5138. var finish = playStateInfo._finish;
  5139. finish || this._updatePlayer(animatorState, playStateInfo, delta * speed, clip.islooping);
  5140. if (needRender) {
  5141. var addtive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  5142. this._updateClipDatas(animatorState, addtive, playStateInfo, timerScale * speed);
  5143. this._setClipDatasToNode(animatorState, addtive, controllerLayer.defaultWeight, i === 0);
  5144. finish || this._updateEventScript(animatorState, playStateInfo);
  5145. }
  5146. break;
  5147. case 1:
  5148. animatorState = playStateInfo._currentState;
  5149. clip = animatorState._clip;
  5150. var crossState = controllerLayer._crossPlayState;
  5151. var crossClip = crossState._clip;
  5152. var crossDuratuion = controllerLayer._crossDuration;
  5153. var startPlayTime = crossPlayStateInfo._startPlayTime;
  5154. var crossClipDuration = crossClip._duration - startPlayTime;
  5155. var crossScale = crossDuratuion > crossClipDuration ? crossClipDuration / crossDuratuion : 1.0;
  5156. var crossSpeed = this._speed * crossState.speed;
  5157. this._updatePlayer(crossState, crossPlayStateInfo, delta * crossScale * crossSpeed, crossClip.islooping);
  5158. var crossWeight = ((crossPlayStateInfo._elapsedTime - startPlayTime) / crossScale) / crossDuratuion;
  5159. if (crossWeight >= 1.0) {
  5160. if (needRender) {
  5161. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossSpeed);
  5162. this._setClipDatasToNode(crossState, addtive, controllerLayer.defaultWeight, i === 0);
  5163. controllerLayer._playType = 0;
  5164. playStateInfo._currentState = crossState;
  5165. crossPlayStateInfo._cloneTo(playStateInfo);
  5166. }
  5167. }
  5168. else {
  5169. if (!playStateInfo._finish) {
  5170. speed = this._speed * animatorState.speed;
  5171. this._updatePlayer(animatorState, playStateInfo, delta * speed, clip.islooping);
  5172. if (needRender)
  5173. this._updateClipDatas(animatorState, addtive, playStateInfo, timerScale * speed);
  5174. }
  5175. if (needRender) {
  5176. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossScale * crossSpeed);
  5177. this._setCrossClipDatasToNode(controllerLayer, animatorState, crossState, crossWeight, i === 0);
  5178. }
  5179. }
  5180. if (needRender) {
  5181. this._updateEventScript(animatorState, playStateInfo);
  5182. this._updateEventScript(crossState, crossPlayStateInfo);
  5183. }
  5184. break;
  5185. case 2:
  5186. crossState = controllerLayer._crossPlayState;
  5187. crossClip = crossState._clip;
  5188. crossDuratuion = controllerLayer._crossDuration;
  5189. startPlayTime = crossPlayStateInfo._startPlayTime;
  5190. crossClipDuration = crossClip._duration - startPlayTime;
  5191. crossScale = crossDuratuion > crossClipDuration ? crossClipDuration / crossDuratuion : 1.0;
  5192. crossSpeed = this._speed * crossState.speed;
  5193. this._updatePlayer(crossState, crossPlayStateInfo, delta * crossScale * crossSpeed, crossClip.islooping);
  5194. if (needRender) {
  5195. crossWeight = ((crossPlayStateInfo._elapsedTime - startPlayTime) / crossScale) / crossDuratuion;
  5196. if (crossWeight >= 1.0) {
  5197. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossSpeed);
  5198. this._setClipDatasToNode(crossState, addtive, 1.0, i === 0);
  5199. controllerLayer._playType = 0;
  5200. playStateInfo._currentState = crossState;
  5201. crossPlayStateInfo._cloneTo(playStateInfo);
  5202. }
  5203. else {
  5204. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossScale * crossSpeed);
  5205. this._setFixedCrossClipDatasToNode(controllerLayer, crossState, crossWeight, i === 0);
  5206. }
  5207. this._updateEventScript(crossState, crossPlayStateInfo);
  5208. }
  5209. break;
  5210. }
  5211. }
  5212. if (needRender) {
  5213. if (this._avatar) {
  5214. Laya.Render.supportWebGLPlusAnimation && this._updateAnimationNodeWorldMatix(this._animationNodeLocalPositions, this._animationNodeLocalRotations, this._animationNodeLocalScales, this._animationNodeWorldMatrixs, this._animationNodeParentIndices);
  5215. this._updateAvatarNodesToSprite();
  5216. }
  5217. }
  5218. }
  5219. _cloneTo(dest) {
  5220. var animator = dest;
  5221. animator.avatar = this.avatar;
  5222. animator.cullingMode = this.cullingMode;
  5223. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  5224. var controllLayer = this._controllerLayers[i];
  5225. animator.addControllerLayer(controllLayer.clone());
  5226. var animatorStates = controllLayer._states;
  5227. for (var j = 0, m = animatorStates.length; j < m; j++) {
  5228. var state = animatorStates[j].clone();
  5229. var cloneLayer = animator.getControllerLayer(i);
  5230. cloneLayer.addState(state);
  5231. (j == 0) && (cloneLayer.defaultState = state);
  5232. }
  5233. }
  5234. animator._linkSprites = this._linkSprites;
  5235. animator._linkToSprites(this._linkSprites);
  5236. }
  5237. getDefaultState(layerIndex = 0) {
  5238. var controllerLayer = this._controllerLayers[layerIndex];
  5239. return controllerLayer.defaultState;
  5240. }
  5241. addState(state, layerIndex = 0) {
  5242. var controllerLayer = this._controllerLayers[layerIndex];
  5243. controllerLayer.addState(state);
  5244. console.warn("Animator:this function is discard,please use animatorControllerLayer.addState() instead.");
  5245. }
  5246. removeState(state, layerIndex = 0) {
  5247. var controllerLayer = this._controllerLayers[layerIndex];
  5248. controllerLayer.removeState(state);
  5249. console.warn("Animator:this function is discard,please use animatorControllerLayer.removeState() instead.");
  5250. }
  5251. addControllerLayer(controllderLayer) {
  5252. this._controllerLayers.push(controllderLayer);
  5253. controllderLayer._animator = this;
  5254. controllderLayer._addReference();
  5255. var states = controllderLayer._states;
  5256. for (var i = 0, n = states.length; i < n; i++)
  5257. this._getOwnersByClip(states[i]);
  5258. }
  5259. getControllerLayer(layerInex = 0) {
  5260. return this._controllerLayers[layerInex];
  5261. }
  5262. play(name = null, layerIndex = 0, normalizedTime = Number.NEGATIVE_INFINITY) {
  5263. var controllerLayer = this._controllerLayers[layerIndex];
  5264. if (controllerLayer) {
  5265. var defaultState = controllerLayer.defaultState;
  5266. if (!name && !defaultState)
  5267. throw new Error("Animator:must have default clip value,please set clip property.");
  5268. var playStateInfo = controllerLayer._playStateInfo;
  5269. var curPlayState = playStateInfo._currentState;
  5270. var animatorState = name ? controllerLayer._statesMap[name] : defaultState;
  5271. var clipDuration = animatorState._clip._duration;
  5272. if (curPlayState !== animatorState) {
  5273. if (normalizedTime !== Number.NEGATIVE_INFINITY)
  5274. playStateInfo._resetPlayState(clipDuration * normalizedTime);
  5275. else
  5276. playStateInfo._resetPlayState(0.0);
  5277. (curPlayState !== null && curPlayState !== animatorState) && (this._revertDefaultKeyframeNodes(curPlayState));
  5278. controllerLayer._playType = 0;
  5279. playStateInfo._currentState = animatorState;
  5280. }
  5281. else {
  5282. if (normalizedTime !== Number.NEGATIVE_INFINITY) {
  5283. playStateInfo._resetPlayState(clipDuration * normalizedTime);
  5284. controllerLayer._playType = 0;
  5285. }
  5286. }
  5287. var scripts = animatorState._scripts;
  5288. if (scripts) {
  5289. for (var i = 0, n = scripts.length; i < n; i++)
  5290. scripts[i].onStateEnter();
  5291. }
  5292. }
  5293. else {
  5294. console.warn("Invalid layerIndex " + layerIndex + ".");
  5295. }
  5296. }
  5297. crossFade(name, transitionDuration, layerIndex = 0, normalizedTime = Number.NEGATIVE_INFINITY) {
  5298. var controllerLayer = this._controllerLayers[layerIndex];
  5299. if (controllerLayer) {
  5300. var destAnimatorState = controllerLayer._statesMap[name];
  5301. if (destAnimatorState) {
  5302. var playType = controllerLayer._playType;
  5303. if (playType === -1) {
  5304. this.play(name, layerIndex, normalizedTime);
  5305. return;
  5306. }
  5307. var crossPlayStateInfo = controllerLayer._crossPlayStateInfo;
  5308. var crossNodeOwners = controllerLayer._crossNodesOwners;
  5309. var crossNodeOwnerIndicesMap = controllerLayer._crossNodesOwnersIndicesMap;
  5310. var srcAnimatorState = controllerLayer._playStateInfo._currentState;
  5311. var destNodeOwners = destAnimatorState._nodeOwners;
  5312. var destCrossClipNodeIndices = controllerLayer._destCrossClipNodeIndices;
  5313. var destClip = destAnimatorState._clip;
  5314. var destNodes = destClip._nodes;
  5315. var destNodesMap = destClip._nodesDic;
  5316. switch (playType) {
  5317. case 0:
  5318. var srcNodeOwners = srcAnimatorState._nodeOwners;
  5319. var scrCrossClipNodeIndices = controllerLayer._srcCrossClipNodeIndices;
  5320. var srcClip = srcAnimatorState._clip;
  5321. var srcNodes = srcClip._nodes;
  5322. var srcNodesMap = srcClip._nodesDic;
  5323. controllerLayer._playType = 1;
  5324. var crossMark = ++controllerLayer._crossMark;
  5325. var crossCount = controllerLayer._crossNodesOwnersCount = 0;
  5326. for (var i = 0, n = srcNodes.count; i < n; i++) {
  5327. var srcNode = srcNodes.getNodeByIndex(i);
  5328. var srcIndex = srcNode._indexInList;
  5329. var srcNodeOwner = srcNodeOwners[srcIndex];
  5330. if (srcNodeOwner) {
  5331. var srcFullPath = srcNode.fullPath;
  5332. scrCrossClipNodeIndices[crossCount] = srcIndex;
  5333. var destNode = destNodesMap[srcFullPath];
  5334. if (destNode)
  5335. destCrossClipNodeIndices[crossCount] = destNode._indexInList;
  5336. else
  5337. destCrossClipNodeIndices[crossCount] = -1;
  5338. crossNodeOwnerIndicesMap[srcFullPath] = crossMark;
  5339. crossNodeOwners[crossCount] = srcNodeOwner;
  5340. crossCount++;
  5341. }
  5342. }
  5343. for (i = 0, n = destNodes.count; i < n; i++) {
  5344. destNode = destNodes.getNodeByIndex(i);
  5345. var destIndex = destNode._indexInList;
  5346. var destNodeOwner = destNodeOwners[destIndex];
  5347. if (destNodeOwner) {
  5348. var destFullPath = destNode.fullPath;
  5349. if (!srcNodesMap[destFullPath]) {
  5350. scrCrossClipNodeIndices[crossCount] = -1;
  5351. destCrossClipNodeIndices[crossCount] = destIndex;
  5352. crossNodeOwnerIndicesMap[destFullPath] = crossMark;
  5353. crossNodeOwners[crossCount] = destNodeOwner;
  5354. crossCount++;
  5355. }
  5356. }
  5357. }
  5358. break;
  5359. case 1:
  5360. case 2:
  5361. controllerLayer._playType = 2;
  5362. for (i = 0, n = crossNodeOwners.length; i < n; i++) {
  5363. var nodeOwner = crossNodeOwners[i];
  5364. nodeOwner.saveCrossFixedValue();
  5365. destNode = destNodesMap[nodeOwner.fullPath];
  5366. if (destNode)
  5367. destCrossClipNodeIndices[i] = destNode._indexInList;
  5368. else
  5369. destCrossClipNodeIndices[i] = -1;
  5370. }
  5371. crossCount = controllerLayer._crossNodesOwnersCount;
  5372. crossMark = controllerLayer._crossMark;
  5373. for (i = 0, n = destNodes.count; i < n; i++) {
  5374. destNode = destNodes.getNodeByIndex(i);
  5375. destIndex = destNode._indexInList;
  5376. destNodeOwner = destNodeOwners[destIndex];
  5377. if (destNodeOwner) {
  5378. destFullPath = destNode.fullPath;
  5379. if (crossNodeOwnerIndicesMap[destFullPath] !== crossMark) {
  5380. destCrossClipNodeIndices[crossCount] = destIndex;
  5381. crossNodeOwnerIndicesMap[destFullPath] = crossMark;
  5382. nodeOwner = destNodeOwners[destIndex];
  5383. crossNodeOwners[crossCount] = nodeOwner;
  5384. nodeOwner.saveCrossFixedValue();
  5385. crossCount++;
  5386. }
  5387. }
  5388. }
  5389. break;
  5390. default:
  5391. }
  5392. controllerLayer._crossNodesOwnersCount = crossCount;
  5393. controllerLayer._crossPlayState = destAnimatorState;
  5394. controllerLayer._crossDuration = srcAnimatorState._clip._duration * transitionDuration;
  5395. if (normalizedTime !== Number.NEGATIVE_INFINITY)
  5396. crossPlayStateInfo._resetPlayState(destClip._duration * normalizedTime);
  5397. else
  5398. crossPlayStateInfo._resetPlayState(0.0);
  5399. var scripts = destAnimatorState._scripts;
  5400. if (scripts) {
  5401. for (i = 0, n = scripts.length; i < n; i++)
  5402. scripts[i].onStateEnter();
  5403. }
  5404. }
  5405. else {
  5406. console.warn("Invalid name " + layerIndex + ".");
  5407. }
  5408. }
  5409. else {
  5410. console.warn("Invalid layerIndex " + layerIndex + ".");
  5411. }
  5412. }
  5413. get avatar() {
  5414. return this._avatar;
  5415. }
  5416. set avatar(value) {
  5417. if (this._avatar !== value) {
  5418. this._avatar = value;
  5419. if (value) {
  5420. this._getAvatarOwnersAndInitDatasAsync();
  5421. this.owner._changeHierarchyAnimatorAvatar(this, value);
  5422. }
  5423. else {
  5424. var parent = this.owner._parent;
  5425. this.owner._changeHierarchyAnimatorAvatar(this, parent ? parent._hierarchyAnimator._avatar : null);
  5426. }
  5427. }
  5428. }
  5429. _getAvatarOwnersAndInitDatasAsync() {
  5430. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  5431. var clipStateInfos = this._controllerLayers[i]._states;
  5432. for (var j = 0, m = clipStateInfos.length; j < m; j++)
  5433. this._getOwnersByClip(clipStateInfos[j]);
  5434. }
  5435. this._avatar._cloneDatasToAnimator(this);
  5436. for (var k in this._linkAvatarSpritesData) {
  5437. var sprites = this._linkAvatarSpritesData[k];
  5438. if (sprites) {
  5439. for (var c = 0, p = sprites.length; c < p; c++)
  5440. this._isLinkSpriteToAnimationNode(sprites[c], k, true);
  5441. }
  5442. }
  5443. }
  5444. _isLinkSpriteToAnimationNode(sprite, nodeName, isLink) {
  5445. if (this._avatar) {
  5446. var node = this._avatarNodeMap[nodeName];
  5447. if (node) {
  5448. if (isLink) {
  5449. sprite._transform._dummy = node.transform;
  5450. this._linkAvatarSprites.push(sprite);
  5451. var nodeTransform = node.transform;
  5452. var spriteTransform = sprite.transform;
  5453. if (!spriteTransform.owner.isStatic && nodeTransform) {
  5454. var spriteWorldMatrix = spriteTransform.worldMatrix;
  5455. var ownParTra = this.owner._transform._parent;
  5456. if (ownParTra) {
  5457. Utils3D.matrix4x4MultiplyMFM(ownParTra.worldMatrix, nodeTransform.getWorldMatrix(), spriteWorldMatrix);
  5458. }
  5459. else {
  5460. var sprWorE = spriteWorldMatrix.elements;
  5461. var nodWorE = nodeTransform.getWorldMatrix();
  5462. for (var i = 0; i < 16; i++)
  5463. sprWorE[i] = nodWorE[i];
  5464. }
  5465. spriteTransform.worldMatrix = spriteWorldMatrix;
  5466. }
  5467. }
  5468. else {
  5469. sprite._transform._dummy = null;
  5470. this._linkAvatarSprites.splice(this._linkAvatarSprites.indexOf(sprite), 1);
  5471. }
  5472. }
  5473. }
  5474. }
  5475. _isLinkSpriteToAnimationNodeData(sprite, nodeName, isLink) {
  5476. var linkSprites = this._linkAvatarSpritesData[nodeName];
  5477. if (isLink) {
  5478. linkSprites || (this._linkAvatarSpritesData[nodeName] = linkSprites = []);
  5479. linkSprites.push(sprite);
  5480. }
  5481. else {
  5482. var index = linkSprites.indexOf(sprite);
  5483. linkSprites.splice(index, 1);
  5484. }
  5485. }
  5486. _updateAvatarNodesToSprite() {
  5487. for (var i = 0, n = this._linkAvatarSprites.length; i < n; i++) {
  5488. var sprite = this._linkAvatarSprites[i];
  5489. var nodeTransform = sprite.transform._dummy;
  5490. var spriteTransform = sprite.transform;
  5491. if (!spriteTransform.owner.isStatic && nodeTransform) {
  5492. var spriteWorldMatrix = spriteTransform.worldMatrix;
  5493. var ownTra = this.owner._transform;
  5494. Utils3D.matrix4x4MultiplyMFM(ownTra.worldMatrix, nodeTransform.getWorldMatrix(), spriteWorldMatrix);
  5495. spriteTransform.worldMatrix = spriteWorldMatrix;
  5496. }
  5497. }
  5498. }
  5499. linkSprite3DToAvatarNode(nodeName, sprite3D) {
  5500. this._isLinkSpriteToAnimationNodeData(sprite3D, nodeName, true);
  5501. this._isLinkSpriteToAnimationNode(sprite3D, nodeName, true);
  5502. return true;
  5503. }
  5504. unLinkSprite3DToAvatarNode(sprite3D) {
  5505. if (sprite3D._hierarchyAnimator === this) {
  5506. var dummy = sprite3D.transform._dummy;
  5507. if (dummy) {
  5508. var nodeName = dummy._owner.name;
  5509. this._isLinkSpriteToAnimationNodeData(sprite3D, nodeName, false);
  5510. this._isLinkSpriteToAnimationNode(sprite3D, nodeName, false);
  5511. return true;
  5512. }
  5513. else {
  5514. return false;
  5515. }
  5516. }
  5517. else {
  5518. throw ("Animator:sprite3D must belong to this Animator");
  5519. return false;
  5520. }
  5521. }
  5522. getCurrentAnimatorPlayState(layerInex = 0) {
  5523. return this._controllerLayers[layerInex]._playStateInfo;
  5524. }
  5525. _updateAnimationNodeWorldMatix(localPositions, localRotations, localScales, worldMatrixs, parentIndices) {
  5526. Laya.LayaGL.instance.updateAnimationNodeWorldMatix(localPositions, localRotations, localScales, parentIndices, worldMatrixs);
  5527. }
  5528. }
  5529. Animator._tempVector30 = new Vector3();
  5530. Animator._tempVector31 = new Vector3();
  5531. Animator._tempQuaternion0 = new Quaternion();
  5532. Animator._tempQuaternion1 = new Quaternion();
  5533. Animator.CULLINGMODE_ALWAYSANIMATE = 0;
  5534. Animator.CULLINGMODE_CULLCOMPLETELY = 2;
  5535. class PostProcessRenderContext {
  5536. constructor() {
  5537. this.source = null;
  5538. this.destination = null;
  5539. this.camera = null;
  5540. this.compositeShaderData = null;
  5541. this.command = null;
  5542. this.deferredReleaseTextures = [];
  5543. }
  5544. }
  5545. class RenderContext3D {
  5546. constructor() {
  5547. this.invertY = false;
  5548. }
  5549. }
  5550. RenderContext3D._instance = new RenderContext3D();
  5551. class RenderTexture extends Laya.BaseTexture {
  5552. constructor(width, height, format = Laya.RenderTextureFormat.R8G8B8, depthStencilFormat = Laya.RenderTextureDepthFormat.DEPTH_16) {
  5553. super(format, false);
  5554. this._inPool = false;
  5555. this._isCameraTarget = false;
  5556. this._glTextureType = Laya.LayaGL.instance.TEXTURE_2D;
  5557. this._width = width;
  5558. this._height = height;
  5559. this._depthStencilFormat = depthStencilFormat;
  5560. this._create(width, height);
  5561. }
  5562. static get currentActive() {
  5563. return RenderTexture._currentActive;
  5564. }
  5565. static createFromPool(width, height, format = Laya.RenderTextureFormat.R8G8B8, depthStencilFormat = Laya.RenderTextureDepthFormat.DEPTH_16, filterMode = Laya.BaseTexture.FILTERMODE_BILINEAR) {
  5566. var tex;
  5567. for (var i = 0, n = RenderTexture._pool.length; i < n; i++) {
  5568. tex = RenderTexture._pool[i];
  5569. if (tex._width == width && tex._height == height && tex._format == format && tex._depthStencilFormat == depthStencilFormat && tex._filterMode == filterMode) {
  5570. tex._inPool = false;
  5571. var end = RenderTexture._pool[n - 1];
  5572. RenderTexture._pool[i] = end;
  5573. RenderTexture._pool.length -= 1;
  5574. return tex;
  5575. }
  5576. }
  5577. tex = new RenderTexture(width, height, format, depthStencilFormat);
  5578. tex.filterMode = filterMode;
  5579. tex.lock = true;
  5580. return tex;
  5581. }
  5582. static recoverToPool(renderTexture) {
  5583. if (renderTexture._inPool)
  5584. return;
  5585. RenderTexture._pool.push(renderTexture);
  5586. renderTexture._inPool = true;
  5587. }
  5588. get depthStencilFormat() {
  5589. return this._depthStencilFormat;
  5590. }
  5591. get defaulteTexture() {
  5592. return Laya.Texture2D.grayTexture;
  5593. }
  5594. _texImage2D(gl, glTextureType, width, height) {
  5595. switch (this._format) {
  5596. case Laya.RenderTextureFormat.R8G8B8:
  5597. gl.texImage2D(glTextureType, 0, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, null);
  5598. break;
  5599. case Laya.RenderTextureFormat.R8G8B8A8:
  5600. gl.texImage2D(glTextureType, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  5601. break;
  5602. case Laya.RenderTextureFormat.Alpha8:
  5603. gl.texImage2D(glTextureType, 0, gl.ALPHA, width, height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, null);
  5604. break;
  5605. case Laya.RenderTextureFormat.R16G16B16A16:
  5606. if (Laya.LayaGL.layaGPUInstance._isWebGL2)
  5607. gl.texImage2D(this._glTextureType, 0, gl.RGBA16F, width, height, 0, gl.RGBA, gl.HALF_FLOAT, null);
  5608. else
  5609. gl.texImage2D(this._glTextureType, 0, gl.RGBA, width, height, 0, gl.RGBA, Laya.LayaGL.layaGPUInstance._oesTextureHalfFloat.HALF_FLOAT_OES, null);
  5610. break;
  5611. default:
  5612. break;
  5613. }
  5614. }
  5615. _create(width, height) {
  5616. var gl = Laya.LayaGL.instance;
  5617. this._frameBuffer = gl.createFramebuffer();
  5618. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  5619. this._texImage2D(gl, this._glTextureType, width, height);
  5620. this._setGPUMemory(width * height * 4);
  5621. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  5622. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._glTexture, 0);
  5623. if (this._depthStencilFormat !== Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE) {
  5624. this._depthStencilBuffer = gl.createRenderbuffer();
  5625. gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthStencilBuffer);
  5626. switch (this._depthStencilFormat) {
  5627. case Laya.RenderTextureDepthFormat.DEPTH_16:
  5628. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5629. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  5630. break;
  5631. case Laya.RenderTextureDepthFormat.STENCIL_8:
  5632. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
  5633. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  5634. break;
  5635. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_16_8:
  5636. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  5637. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  5638. break;
  5639. default:
  5640. throw "RenderTexture: unkonw depth format.";
  5641. }
  5642. }
  5643. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5644. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5645. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  5646. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  5647. this._setFilterMode(this._filterMode);
  5648. this._setAnisotropy(this._anisoLevel);
  5649. this._readyed = true;
  5650. this._activeResource();
  5651. }
  5652. _start() {
  5653. var gl = Laya.LayaGL.instance;
  5654. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  5655. RenderTexture._currentActive = this;
  5656. (this._isCameraTarget) && (RenderContext3D._instance.invertY = true);
  5657. this._readyed = false;
  5658. }
  5659. _end() {
  5660. var gl = Laya.LayaGL.instance;
  5661. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5662. RenderTexture._currentActive = null;
  5663. (this._isCameraTarget) && (RenderContext3D._instance.invertY = false);
  5664. this._readyed = true;
  5665. }
  5666. getData(x, y, width, height, out) {
  5667. if (Laya.Render.isConchApp && window.conchConfig.threadMode == 2) {
  5668. throw "native 2 thread mode use getDataAsync";
  5669. }
  5670. var gl = Laya.LayaGL.instance;
  5671. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  5672. var canRead = (gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE);
  5673. if (!canRead) {
  5674. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5675. return null;
  5676. }
  5677. gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, out);
  5678. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5679. return out;
  5680. }
  5681. getDataAsync(x, y, width, height, callBack) {
  5682. var gl = Laya.LayaGL.instance;
  5683. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  5684. gl.readPixelsAsync(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, function (data) {
  5685. callBack(new Uint8Array(data));
  5686. });
  5687. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5688. }
  5689. _disposeResource() {
  5690. if (this._frameBuffer) {
  5691. var gl = Laya.LayaGL.instance;
  5692. gl.deleteTexture(this._glTexture);
  5693. gl.deleteFramebuffer(this._frameBuffer);
  5694. gl.deleteRenderbuffer(this._depthStencilBuffer);
  5695. this._glTexture = null;
  5696. this._frameBuffer = null;
  5697. this._depthStencilBuffer = null;
  5698. this._setGPUMemory(0);
  5699. }
  5700. }
  5701. }
  5702. RenderTexture._pool = [];
  5703. class DefineDatas {
  5704. constructor() {
  5705. this._mask = [];
  5706. this._length = 0;
  5707. }
  5708. _intersectionDefineDatas(define) {
  5709. var unionMask = define._mask;
  5710. var mask = this._mask;
  5711. for (var i = this._length - 1; i >= 0; i--) {
  5712. var value = mask[i] & unionMask[i];
  5713. if (value == 0 && i == this._length - 1)
  5714. this._length--;
  5715. else
  5716. mask[i] = value;
  5717. }
  5718. }
  5719. add(define) {
  5720. var index = define._index;
  5721. var size = index + 1;
  5722. var mask = this._mask;
  5723. var maskStart = mask.length;
  5724. if (maskStart < size) {
  5725. mask.length = size;
  5726. for (; maskStart < index; maskStart++)
  5727. mask[maskStart] = 0;
  5728. mask[index] = define._value;
  5729. this._length = size;
  5730. }
  5731. else {
  5732. if (size > this._length) {
  5733. mask[index] = define._value;
  5734. this._length = size;
  5735. }
  5736. else {
  5737. mask[index] |= define._value;
  5738. }
  5739. }
  5740. }
  5741. remove(define) {
  5742. var index = define._index;
  5743. var mask = this._mask;
  5744. var endIndex = this._length - 1;
  5745. if (index > endIndex)
  5746. return;
  5747. var newValue = mask[index] & ~define._value;
  5748. if (index == endIndex && newValue === 0)
  5749. this._length--;
  5750. else
  5751. mask[index] = newValue;
  5752. }
  5753. addDefineDatas(define) {
  5754. var addMask = define._mask;
  5755. var size = define._length;
  5756. var mask = this._mask;
  5757. var maskStart = mask.length;
  5758. if (maskStart < size) {
  5759. mask.length = size;
  5760. for (var i = 0; i < maskStart; i++)
  5761. mask[i] |= addMask[i];
  5762. for (; maskStart < size; maskStart++)
  5763. mask[maskStart] = addMask[maskStart];
  5764. this._length = size;
  5765. }
  5766. else {
  5767. for (var i = 0; i < size; i++)
  5768. mask[i] |= addMask[i];
  5769. this._length = Math.max(this._length, size);
  5770. }
  5771. }
  5772. removeDefineDatas(define) {
  5773. var removeMask = define._mask;
  5774. var mask = this._mask;
  5775. var endIndex = this._length - 1;
  5776. for (var i = define._length - 1; i >= 0; i--) {
  5777. if (i > endIndex)
  5778. continue;
  5779. var newValue = mask[i] & ~removeMask[i];
  5780. if (i == endIndex && newValue === 0) {
  5781. endIndex--;
  5782. this._length--;
  5783. }
  5784. else {
  5785. mask[i] = newValue;
  5786. }
  5787. }
  5788. }
  5789. has(define) {
  5790. var index = define._index;
  5791. if (index >= this._length)
  5792. return false;
  5793. return (this._mask[index] & define._value) !== 0;
  5794. }
  5795. clear() {
  5796. this._length = 0;
  5797. }
  5798. cloneTo(destObject) {
  5799. var destDefineData = destObject;
  5800. var destMask = destDefineData._mask;
  5801. var mask = this._mask;
  5802. var count = this._length;
  5803. destMask.length = count;
  5804. for (var i = 0; i < count; i++)
  5805. destMask[i] = mask[i];
  5806. destDefineData._length = count;
  5807. }
  5808. clone() {
  5809. var dest = new DefineDatas();
  5810. this.cloneTo(dest);
  5811. return dest;
  5812. }
  5813. }
  5814. class ShaderDefine {
  5815. constructor(index, value) {
  5816. this._index = index;
  5817. this._value = value;
  5818. }
  5819. }
  5820. class ShaderVariant {
  5821. constructor(shader, subShaderIndex, passIndex, defines) {
  5822. this._subShaderIndex = 0;
  5823. this._passIndex = 0;
  5824. this.setValue(shader, subShaderIndex, passIndex, defines);
  5825. }
  5826. get shader() {
  5827. return this._shader;
  5828. }
  5829. get subShaderIndex() {
  5830. return this._subShaderIndex;
  5831. }
  5832. get passIndex() {
  5833. return this._passIndex;
  5834. }
  5835. get defineNames() {
  5836. return this._defineNames;
  5837. }
  5838. setValue(shader, subShaderIndex, passIndex, defineNames) {
  5839. if (shader) {
  5840. var subShader = shader.getSubShaderAt(subShaderIndex);
  5841. if (subShader) {
  5842. var pass = subShader._passes[passIndex];
  5843. if (pass) {
  5844. var validDefine = pass._validDefine;
  5845. for (var i = 0, n = defineNames.length; i < n; i++) {
  5846. var defname = defineNames[i];
  5847. if (!validDefine.has(ILaya3D.Shader3D.getDefineByName(defname)))
  5848. throw `ShaderVariantInfo:Invalid defineName ${defname} in ${shader._name} subShaderIndex of ${subShaderIndex} passIndex of ${passIndex}.`;
  5849. }
  5850. }
  5851. else {
  5852. throw `ShaderVariantInfo:Shader don't have passIndex of ${passIndex}.`;
  5853. }
  5854. }
  5855. else {
  5856. throw `ShaderVariantInfo:Shader don't have subShaderIndex of ${subShaderIndex}.`;
  5857. }
  5858. }
  5859. else {
  5860. throw `ShaderVariantInfo:Shader can't be null.`;
  5861. }
  5862. this._shader = shader;
  5863. this._subShaderIndex = subShaderIndex;
  5864. this._passIndex = passIndex;
  5865. this._defineNames = defineNames;
  5866. }
  5867. equal(other) {
  5868. if (this._shader !== other._shader || this._subShaderIndex !== other._subShaderIndex || this._passIndex !== other._passIndex)
  5869. return false;
  5870. var defines = this._defineNames;
  5871. var otherDefines = other._defineNames;
  5872. if (defines.length !== otherDefines.length)
  5873. return false;
  5874. for (var i = 0, n = this._defineNames.length; i < n; i++) {
  5875. if (defines[i] !== otherDefines[i])
  5876. return false;
  5877. }
  5878. return true;
  5879. }
  5880. clone() {
  5881. var dest = new ShaderVariant(this._shader, this._subShaderIndex, this._passIndex, this._defineNames.slice());
  5882. return dest;
  5883. }
  5884. }
  5885. class ShaderVariantCollection {
  5886. constructor() {
  5887. this._allCompiled = false;
  5888. this._variants = [];
  5889. }
  5890. get allCompiled() {
  5891. return this._allCompiled;
  5892. }
  5893. get variantCount() {
  5894. return this._variants.length;
  5895. }
  5896. add(variant) {
  5897. for (var i = 0, n = this._variants.length; i < n; i++) {
  5898. if (this._variants[i].equal(variant))
  5899. return false;
  5900. }
  5901. this._variants.push(variant.clone());
  5902. this._allCompiled = false;
  5903. return true;
  5904. }
  5905. remove(variant) {
  5906. for (var i = 0, n = this._variants.length; i < n; i++) {
  5907. if (this._variants[i].equal(variant)) {
  5908. this._variants.splice(i, 1);
  5909. return true;
  5910. }
  5911. }
  5912. return false;
  5913. }
  5914. contatins(variant) {
  5915. for (var i = 0, n = this._variants.length; i < n; i++) {
  5916. if (this._variants[i].equal(variant))
  5917. return true;
  5918. }
  5919. return false;
  5920. }
  5921. getByIndex(index) {
  5922. return this._variants[index];
  5923. }
  5924. clear() {
  5925. this._variants.length = 0;
  5926. }
  5927. compile() {
  5928. if (!this._allCompiled) {
  5929. var variants = this._variants;
  5930. for (var i = 0, n = variants.length; i < n; i++) {
  5931. var variant = variants[i];
  5932. ILaya3D.Shader3D.compileShaderByDefineNames(variant._shader._name, variant._subShaderIndex, variant._passIndex, variant._defineNames);
  5933. }
  5934. this._allCompiled = true;
  5935. }
  5936. }
  5937. }
  5938. class Shader3D {
  5939. constructor(name, attributeMap, uniformMap, enableInstancing) {
  5940. this._attributeMap = null;
  5941. this._uniformMap = null;
  5942. this._enableInstancing = false;
  5943. this._subShaders = [];
  5944. this._name = name;
  5945. this._attributeMap = attributeMap;
  5946. this._uniformMap = uniformMap;
  5947. this._enableInstancing = enableInstancing;
  5948. }
  5949. static _getNamesByDefineData(defineData, out) {
  5950. var maskMap = Shader3D._maskMap;
  5951. var mask = defineData._mask;
  5952. out.length = 0;
  5953. for (var i = 0, n = defineData._length; i < n; i++) {
  5954. var subMaskMap = maskMap[i];
  5955. var subMask = mask[i];
  5956. for (var j = 0; j < 32; j++) {
  5957. var d = 1 << j;
  5958. if (subMask > 0 && d > subMask)
  5959. break;
  5960. if (subMask & d)
  5961. out.push(subMaskMap[d]);
  5962. }
  5963. }
  5964. }
  5965. static getDefineByName(name) {
  5966. var define = Shader3D._defineMap[name];
  5967. if (!define) {
  5968. var maskMap = Shader3D._maskMap;
  5969. var counter = Shader3D._defineCounter;
  5970. var index = Math.floor(counter / 32);
  5971. var value = 1 << counter % 32;
  5972. define = new ShaderDefine(index, value);
  5973. Shader3D._defineMap[name] = define;
  5974. if (index == maskMap.length) {
  5975. maskMap.length++;
  5976. maskMap[index] = {};
  5977. }
  5978. maskMap[index][value] = name;
  5979. Shader3D._defineCounter++;
  5980. }
  5981. return define;
  5982. }
  5983. static propertyNameToID(name) {
  5984. if (Shader3D._propertyNameMap[name] != null) {
  5985. return Shader3D._propertyNameMap[name];
  5986. }
  5987. else {
  5988. var id = Shader3D._propertyNameCounter++;
  5989. Shader3D._propertyNameMap[name] = id;
  5990. return id;
  5991. }
  5992. }
  5993. static addInclude(fileName, txt) {
  5994. txt = txt.replace(Laya.ShaderCompile._clearCR, "");
  5995. Laya.ShaderCompile.addInclude(fileName, txt);
  5996. }
  5997. static compileShaderByDefineNames(shaderName, subShaderIndex, passIndex, defineNames) {
  5998. var shader = Shader3D.find(shaderName);
  5999. if (shader) {
  6000. var subShader = shader.getSubShaderAt(subShaderIndex);
  6001. if (subShader) {
  6002. var pass = subShader._passes[passIndex];
  6003. if (pass) {
  6004. var compileDefineDatas = Shader3D._compileDefineDatas;
  6005. compileDefineDatas.clear();
  6006. for (var i = 0, n = defineNames.length; i < n; i++)
  6007. compileDefineDatas.add(Shader3D.getDefineByName(defineNames[i]));
  6008. (Config3D._config._multiLighting) || (compileDefineDatas.add(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING));
  6009. pass.withCompile(compileDefineDatas);
  6010. }
  6011. else {
  6012. console.warn("Shader3D: unknown passIndex.");
  6013. }
  6014. }
  6015. else {
  6016. console.warn("Shader3D: unknown subShaderIndex.");
  6017. }
  6018. }
  6019. else {
  6020. console.warn("Shader3D: unknown shader name.");
  6021. }
  6022. }
  6023. static add(name, attributeMap = null, uniformMap = null, enableInstancing = false) {
  6024. return Shader3D._preCompileShader[name] = new Shader3D(name, attributeMap, uniformMap, enableInstancing);
  6025. }
  6026. static find(name) {
  6027. return Shader3D._preCompileShader[name];
  6028. }
  6029. get name() {
  6030. return this._name;
  6031. }
  6032. addSubShader(subShader) {
  6033. this._subShaders.push(subShader);
  6034. subShader._owner = this;
  6035. }
  6036. getSubShaderAt(index) {
  6037. return this._subShaders[index];
  6038. }
  6039. static compileShader(shaderName, subShaderIndex, passIndex, ...defineMask) {
  6040. var shader = Shader3D.find(shaderName);
  6041. if (shader) {
  6042. var subShader = shader.getSubShaderAt(subShaderIndex);
  6043. if (subShader) {
  6044. var pass = subShader._passes[passIndex];
  6045. if (pass) {
  6046. var compileDefineDatas = Shader3D._compileDefineDatas;
  6047. var mask = compileDefineDatas._mask;
  6048. mask.length = 0;
  6049. for (var i = 0, n = defineMask.length; i < n; i++)
  6050. mask.push(defineMask[i]);
  6051. compileDefineDatas._length = defineMask.length;
  6052. (Config3D._config._multiLighting) || (compileDefineDatas.add(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING));
  6053. pass.withCompile(compileDefineDatas);
  6054. }
  6055. else {
  6056. console.warn("Shader3D: unknown passIndex.");
  6057. }
  6058. }
  6059. else {
  6060. console.warn("Shader3D: unknown subShaderIndex.");
  6061. }
  6062. }
  6063. else {
  6064. console.warn("Shader3D: unknown shader name.");
  6065. }
  6066. }
  6067. }
  6068. Shader3D._compileDefineDatas = new DefineDatas();
  6069. Shader3D.RENDER_STATE_CULL = 0;
  6070. Shader3D.RENDER_STATE_BLEND = 1;
  6071. Shader3D.RENDER_STATE_BLEND_SRC = 2;
  6072. Shader3D.RENDER_STATE_BLEND_DST = 3;
  6073. Shader3D.RENDER_STATE_BLEND_SRC_RGB = 4;
  6074. Shader3D.RENDER_STATE_BLEND_DST_RGB = 5;
  6075. Shader3D.RENDER_STATE_BLEND_SRC_ALPHA = 6;
  6076. Shader3D.RENDER_STATE_BLEND_DST_ALPHA = 7;
  6077. Shader3D.RENDER_STATE_BLEND_CONST_COLOR = 8;
  6078. Shader3D.RENDER_STATE_BLEND_EQUATION = 9;
  6079. Shader3D.RENDER_STATE_BLEND_EQUATION_RGB = 10;
  6080. Shader3D.RENDER_STATE_BLEND_EQUATION_ALPHA = 11;
  6081. Shader3D.RENDER_STATE_DEPTH_TEST = 12;
  6082. Shader3D.RENDER_STATE_DEPTH_WRITE = 13;
  6083. Shader3D.PERIOD_CUSTOM = 0;
  6084. Shader3D.PERIOD_MATERIAL = 1;
  6085. Shader3D.PERIOD_SPRITE = 2;
  6086. Shader3D.PERIOD_CAMERA = 3;
  6087. Shader3D.PERIOD_SCENE = 4;
  6088. Shader3D._propertyNameCounter = 0;
  6089. Shader3D._propertyNameMap = {};
  6090. Shader3D._defineCounter = 0;
  6091. Shader3D._defineMap = {};
  6092. Shader3D._preCompileShader = {};
  6093. Shader3D._maskMap = [];
  6094. Shader3D.debugMode = true;
  6095. Shader3D.debugShaderVariantCollection = new ShaderVariantCollection();
  6096. class ShaderData {
  6097. constructor(ownerResource = null) {
  6098. this._ownerResource = null;
  6099. this._data = null;
  6100. this._defineDatas = new DefineDatas();
  6101. this._runtimeCopyValues = [];
  6102. this._ownerResource = ownerResource;
  6103. this._initData();
  6104. }
  6105. _initData() {
  6106. this._data = new Object();
  6107. }
  6108. getData() {
  6109. return this._data;
  6110. }
  6111. addDefine(define) {
  6112. this._defineDatas.add(define);
  6113. }
  6114. removeDefine(define) {
  6115. this._defineDatas.remove(define);
  6116. }
  6117. hasDefine(define) {
  6118. return this._defineDatas.has(define);
  6119. }
  6120. clearDefine() {
  6121. this._defineDatas.clear();
  6122. }
  6123. getBool(index) {
  6124. return this._data[index];
  6125. }
  6126. setBool(index, value) {
  6127. this._data[index] = value;
  6128. }
  6129. getInt(index) {
  6130. return this._data[index];
  6131. }
  6132. setInt(index, value) {
  6133. this._data[index] = value;
  6134. }
  6135. getNumber(index) {
  6136. return this._data[index];
  6137. }
  6138. setNumber(index, value) {
  6139. this._data[index] = value;
  6140. }
  6141. getVector2(index) {
  6142. return this._data[index];
  6143. }
  6144. setVector2(index, value) {
  6145. this._data[index] = value;
  6146. }
  6147. getVector3(index) {
  6148. return this._data[index];
  6149. }
  6150. setVector3(index, value) {
  6151. this._data[index] = value;
  6152. }
  6153. getVector(index) {
  6154. return this._data[index];
  6155. }
  6156. setVector(index, value) {
  6157. this._data[index] = value;
  6158. }
  6159. getQuaternion(index) {
  6160. return this._data[index];
  6161. }
  6162. setQuaternion(index, value) {
  6163. this._data[index] = value;
  6164. }
  6165. getMatrix4x4(index) {
  6166. return this._data[index];
  6167. }
  6168. setMatrix4x4(index, value) {
  6169. this._data[index] = value;
  6170. }
  6171. getBuffer(shaderIndex) {
  6172. return this._data[shaderIndex];
  6173. }
  6174. setBuffer(index, value) {
  6175. this._data[index] = value;
  6176. }
  6177. setTexture(index, value) {
  6178. var lastValue = this._data[index];
  6179. this._data[index] = value;
  6180. if (this._ownerResource && this._ownerResource.referenceCount > 0) {
  6181. (lastValue) && (lastValue._removeReference());
  6182. (value) && (value._addReference());
  6183. }
  6184. }
  6185. getTexture(index) {
  6186. return this._data[index];
  6187. }
  6188. setAttribute(index, value) {
  6189. this._data[index] = value;
  6190. }
  6191. getAttribute(index) {
  6192. return this._data[index];
  6193. }
  6194. getLength() {
  6195. return this._data.length;
  6196. }
  6197. setLength(value) {
  6198. this._data.length = value;
  6199. }
  6200. cloneTo(destObject) {
  6201. var dest = destObject;
  6202. var destData = dest._data;
  6203. for (var k in this._data) {
  6204. var value = this._data[k];
  6205. if (value != null) {
  6206. if (typeof (value) == 'number') {
  6207. destData[k] = value;
  6208. }
  6209. else if (typeof (value) == 'number') {
  6210. destData[k] = value;
  6211. }
  6212. else if (typeof (value) == "boolean") {
  6213. destData[k] = value;
  6214. }
  6215. else if (value instanceof Vector2) {
  6216. var v2 = (destData[k]) || (destData[k] = new Vector2());
  6217. value.cloneTo(v2);
  6218. destData[k] = v2;
  6219. }
  6220. else if (value instanceof Vector3) {
  6221. var v3 = (destData[k]) || (destData[k] = new Vector3());
  6222. value.cloneTo(v3);
  6223. destData[k] = v3;
  6224. }
  6225. else if (value instanceof Vector4) {
  6226. var v4 = (destData[k]) || (destData[k] = new Vector4());
  6227. value.cloneTo(v4);
  6228. destData[k] = v4;
  6229. }
  6230. else if (value instanceof Matrix4x4) {
  6231. var mat = (destData[k]) || (destData[k] = new Matrix4x4());
  6232. value.cloneTo(mat);
  6233. destData[k] = mat;
  6234. }
  6235. else if (value instanceof Laya.BaseTexture) {
  6236. destData[k] = value;
  6237. }
  6238. }
  6239. }
  6240. this._defineDatas.cloneTo(dest._defineDatas);
  6241. }
  6242. clone() {
  6243. var dest = new ShaderData();
  6244. this.cloneTo(dest);
  6245. return dest;
  6246. }
  6247. cloneToForNative(destObject) {
  6248. var dest = destObject;
  6249. var diffSize = this._int32Data.length - dest._int32Data.length;
  6250. if (diffSize > 0) {
  6251. dest.needRenewArrayBufferForNative(this._int32Data.length);
  6252. }
  6253. dest._int32Data.set(this._int32Data, 0);
  6254. var destData = dest._nativeArray;
  6255. var dataCount = this._nativeArray.length;
  6256. destData.length = dataCount;
  6257. for (var i = 0; i < dataCount; i++) {
  6258. var value = this._nativeArray[i];
  6259. if (value) {
  6260. if (typeof (value) == 'number') {
  6261. destData[i] = value;
  6262. dest.setNumber(i, value);
  6263. }
  6264. else if (typeof (value) == 'number') {
  6265. destData[i] = value;
  6266. dest.setInt(i, value);
  6267. }
  6268. else if (typeof (value) == "boolean") {
  6269. destData[i] = value;
  6270. dest.setBool(i, value);
  6271. }
  6272. else if (value instanceof Vector2) {
  6273. var v2 = (destData[i]) || (destData[i] = new Vector2());
  6274. value.cloneTo(v2);
  6275. destData[i] = v2;
  6276. dest.setVector2(i, v2);
  6277. }
  6278. else if (value instanceof Vector3) {
  6279. var v3 = (destData[i]) || (destData[i] = new Vector3());
  6280. value.cloneTo(v3);
  6281. destData[i] = v3;
  6282. dest.setVector3(i, v3);
  6283. }
  6284. else if (value instanceof Vector4) {
  6285. var v4 = (destData[i]) || (destData[i] = new Vector4());
  6286. value.cloneTo(v4);
  6287. destData[i] = v4;
  6288. dest.setVector(i, v4);
  6289. }
  6290. else if (value instanceof Matrix4x4) {
  6291. var mat = (destData[i]) || (destData[i] = new Matrix4x4());
  6292. value.cloneTo(mat);
  6293. destData[i] = mat;
  6294. dest.setMatrix4x4(i, mat);
  6295. }
  6296. else if (value instanceof Laya.BaseTexture) {
  6297. destData[i] = value;
  6298. dest.setTexture(i, value);
  6299. }
  6300. }
  6301. }
  6302. this._defineDatas.cloneTo(dest._defineDatas);
  6303. }
  6304. _initDataForNative() {
  6305. var length = 8;
  6306. this._frameCount = -1;
  6307. this._runtimeCopyValues.length = 0;
  6308. this._nativeArray = [];
  6309. this._data = new ArrayBuffer(length * 4);
  6310. this._int32Data = new Int32Array(this._data);
  6311. this._float32Data = new Float32Array(this._data);
  6312. Laya.LayaGL.instance.createArrayBufferRef(this._data, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true);
  6313. }
  6314. needRenewArrayBufferForNative(index) {
  6315. if (index >= this._int32Data.length) {
  6316. var nByteLen = (index + 1) * 4;
  6317. var pre = this._int32Data;
  6318. var preConchRef = this._data["conchRef"];
  6319. var prePtrID = this._data["_ptrID"];
  6320. this._data = new ArrayBuffer(nByteLen);
  6321. this._int32Data = new Int32Array(this._data);
  6322. this._float32Data = new Float32Array(this._data);
  6323. this._data["conchRef"] = preConchRef;
  6324. this._data["_ptrID"] = prePtrID;
  6325. pre && this._int32Data.set(pre, 0);
  6326. var layagl = Laya.LayaGL.instance;
  6327. if (layagl.updateArrayBufferRef) {
  6328. layagl.updateArrayBufferRef(this._data['_ptrID'], preConchRef.isSyncToRender(), this._data);
  6329. }
  6330. else {
  6331. window.conch.updateArrayBufferRef(this._data['_ptrID'], preConchRef.isSyncToRender(), this._data);
  6332. }
  6333. }
  6334. }
  6335. getDataForNative() {
  6336. return this._nativeArray;
  6337. }
  6338. getIntForNative(index) {
  6339. return this._int32Data[index];
  6340. }
  6341. setIntForNative(index, value) {
  6342. this.needRenewArrayBufferForNative(index);
  6343. this._int32Data[index] = value;
  6344. this._nativeArray[index] = value;
  6345. }
  6346. getBoolForNative(index) {
  6347. return this._int32Data[index] == 1;
  6348. }
  6349. setBoolForNative(index, value) {
  6350. this.needRenewArrayBufferForNative(index);
  6351. this._int32Data[index] = value ? 1 : 0;
  6352. this._nativeArray[index] = value;
  6353. }
  6354. getNumberForNative(index) {
  6355. return this._float32Data[index];
  6356. }
  6357. setNumberForNative(index, value) {
  6358. this.needRenewArrayBufferForNative(index);
  6359. this._float32Data[index] = value;
  6360. this._nativeArray[index] = value;
  6361. }
  6362. getMatrix4x4ForNative(index) {
  6363. return this._nativeArray[index];
  6364. }
  6365. setMatrix4x4ForNative(index, value) {
  6366. this.needRenewArrayBufferForNative(index);
  6367. this._nativeArray[index] = value;
  6368. var nPtrID = this.setReferenceForNative(value.elements);
  6369. this._int32Data[index] = nPtrID;
  6370. }
  6371. getVectorForNative(index) {
  6372. return this._nativeArray[index];
  6373. }
  6374. setVectorForNative(index, value) {
  6375. this.needRenewArrayBufferForNative(index);
  6376. this._nativeArray[index] = value;
  6377. if (!value.elements) {
  6378. value.forNativeElement();
  6379. }
  6380. var nPtrID = this.setReferenceForNative(value.elements);
  6381. this._int32Data[index] = nPtrID;
  6382. }
  6383. getVector2ForNative(index) {
  6384. return this._nativeArray[index];
  6385. }
  6386. setVector2ForNative(index, value) {
  6387. this.needRenewArrayBufferForNative(index);
  6388. this._nativeArray[index] = value;
  6389. if (!value.elements) {
  6390. value.forNativeElement();
  6391. }
  6392. var nPtrID = this.setReferenceForNative(value.elements);
  6393. this._int32Data[index] = nPtrID;
  6394. }
  6395. getVector3ForNative(index) {
  6396. return this._nativeArray[index];
  6397. }
  6398. setVector3ForNative(index, value) {
  6399. this.needRenewArrayBufferForNative(index);
  6400. this._nativeArray[index] = value;
  6401. if (!value.elements) {
  6402. value.forNativeElement();
  6403. }
  6404. var nPtrID = this.setReferenceForNative(value.elements);
  6405. this._int32Data[index] = nPtrID;
  6406. }
  6407. getQuaternionForNative(index) {
  6408. return this._nativeArray[index];
  6409. }
  6410. setQuaternionForNative(index, value) {
  6411. this.needRenewArrayBufferForNative(index);
  6412. this._nativeArray[index] = value;
  6413. if (!value.elements) {
  6414. value.forNativeElement();
  6415. }
  6416. var nPtrID = this.setReferenceForNative(value.elements);
  6417. this._int32Data[index] = nPtrID;
  6418. }
  6419. getBufferForNative(shaderIndex) {
  6420. return this._nativeArray[shaderIndex];
  6421. }
  6422. setBufferForNative(index, value) {
  6423. this.needRenewArrayBufferForNative(index);
  6424. this._nativeArray[index] = value;
  6425. var nPtrID = this.setReferenceForNative(value);
  6426. this._int32Data[index] = nPtrID;
  6427. }
  6428. getAttributeForNative(index) {
  6429. return this._nativeArray[index];
  6430. }
  6431. setAttributeForNative(index, value) {
  6432. this._nativeArray[index] = value;
  6433. if (!value["_ptrID"]) {
  6434. Laya.LayaGL.instance.createArrayBufferRef(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true);
  6435. }
  6436. Laya.LayaGL.instance.syncBufferToRenderThread(value);
  6437. this._int32Data[index] = value["_ptrID"];
  6438. }
  6439. getTextureForNative(index) {
  6440. return this._nativeArray[index];
  6441. }
  6442. setTextureForNative(index, value) {
  6443. if (!value)
  6444. return;
  6445. this.needRenewArrayBufferForNative(index);
  6446. var lastValue = this._nativeArray[index];
  6447. this._nativeArray[index] = value;
  6448. var glTexture = value._getSource() || value.defaulteTexture._getSource();
  6449. this._int32Data[index] = glTexture.id;
  6450. if (this._ownerResource && this._ownerResource.referenceCount > 0) {
  6451. (lastValue) && (lastValue._removeReference());
  6452. (value) && (value._addReference());
  6453. }
  6454. }
  6455. setReferenceForNative(value) {
  6456. this.clearRuntimeCopyArray();
  6457. var nRefID = 0;
  6458. var nPtrID = 0;
  6459. if (ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_) {
  6460. Laya.LayaGL.instance.createArrayBufferRefs(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true, Laya.LayaGL.ARRAY_BUFFER_REF_REFERENCE);
  6461. nRefID = 0;
  6462. nPtrID = value.getPtrID(nRefID);
  6463. }
  6464. else {
  6465. Laya.LayaGL.instance.createArrayBufferRefs(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true, Laya.LayaGL.ARRAY_BUFFER_REF_COPY);
  6466. nRefID = value.getRefNum() - 1;
  6467. nPtrID = value.getPtrID(nRefID);
  6468. this._runtimeCopyValues.push({ "obj": value, "refID": nRefID, "ptrID": nPtrID });
  6469. }
  6470. Laya.LayaGL.instance.syncBufferToRenderThread(value, nRefID);
  6471. return nPtrID;
  6472. }
  6473. static setRuntimeValueMode(bReference) {
  6474. ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_ = bReference;
  6475. }
  6476. clearRuntimeCopyArray() {
  6477. var currentFrame = Laya.Stat.loopCount;
  6478. if (this._frameCount != currentFrame) {
  6479. this._frameCount = currentFrame;
  6480. for (var i = 0, n = this._runtimeCopyValues.length; i < n; i++) {
  6481. var obj = this._runtimeCopyValues[i];
  6482. obj.obj.clearRefNum();
  6483. }
  6484. this._runtimeCopyValues.length = 0;
  6485. }
  6486. }
  6487. }
  6488. ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_ = true;
  6489. class PostProcess {
  6490. constructor() {
  6491. this._compositeShader = Shader3D.find("PostProcessComposite");
  6492. this._compositeShaderData = new ShaderData();
  6493. this._effects = [];
  6494. this._context = null;
  6495. this._context = new PostProcessRenderContext();
  6496. this._context.compositeShaderData = this._compositeShaderData;
  6497. }
  6498. static __init__() {
  6499. PostProcess.SHADERDEFINE_BLOOM_LOW = Shader3D.getDefineByName("BLOOM_LOW");
  6500. PostProcess.SHADERDEFINE_BLOOM = Shader3D.getDefineByName("BLOOM");
  6501. PostProcess.SHADERDEFINE_FINALPASS = Shader3D.getDefineByName("FINALPASS");
  6502. }
  6503. _init(camera, command) {
  6504. this._context.camera = camera;
  6505. this._context.command = command;
  6506. }
  6507. _render() {
  6508. var noteValue = ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_;
  6509. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(false);
  6510. var camera = this._context.camera;
  6511. var viewport = camera.viewport;
  6512. var screenTexture = RenderTexture.createFromPool(RenderContext3D.clientWidth, RenderContext3D.clientHeight, camera._getRenderTextureFormat(), Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE);
  6513. var cameraTarget = camera._internalRenderTexture;
  6514. this._context.command.clear();
  6515. this._context.source = screenTexture;
  6516. this._context.destination = cameraTarget;
  6517. this._context.compositeShaderData.clearDefine();
  6518. this._context.command.blitScreenTriangle(cameraTarget, screenTexture);
  6519. this._context.compositeShaderData.setTexture(PostProcess.SHADERVALUE_AUTOEXPOSURETEX, Laya.Texture2D.whiteTexture);
  6520. for (var i = 0, n = this._effects.length; i < n; i++)
  6521. this._effects[i].render(this._context);
  6522. this._compositeShaderData.addDefine(PostProcess.SHADERDEFINE_FINALPASS);
  6523. var offScreenTex = camera._offScreenRenderTexture;
  6524. var dest = offScreenTex ? offScreenTex : null;
  6525. this._context.destination = dest;
  6526. var canvasWidth = camera._getCanvasWidth(), canvasHeight = camera._getCanvasHeight();
  6527. camera._screenOffsetScale.setValue(viewport.x / canvasWidth, viewport.y / canvasHeight, viewport.width / canvasWidth, viewport.height / canvasHeight);
  6528. this._context.command.blitScreenTriangle(this._context.source, dest, camera._screenOffsetScale, this._compositeShader, this._compositeShaderData);
  6529. RenderTexture.recoverToPool(screenTexture);
  6530. var tempRenderTextures = this._context.deferredReleaseTextures;
  6531. for (i = 0, n = tempRenderTextures.length; i < n; i++)
  6532. RenderTexture.recoverToPool(tempRenderTextures[i]);
  6533. tempRenderTextures.length = 0;
  6534. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(noteValue);
  6535. }
  6536. addEffect(effect) {
  6537. this._effects.push(effect);
  6538. }
  6539. removeEffect(effect) {
  6540. var index = this._effects.indexOf(effect);
  6541. if (index !== -1)
  6542. this._effects.splice(index, 1);
  6543. }
  6544. }
  6545. PostProcess.SHADERVALUE_MAINTEX = Shader3D.propertyNameToID("u_MainTex");
  6546. PostProcess.SHADERVALUE_BLOOMTEX = Shader3D.propertyNameToID("u_BloomTex");
  6547. PostProcess.SHADERVALUE_AUTOEXPOSURETEX = Shader3D.propertyNameToID("u_AutoExposureTex");
  6548. PostProcess.SHADERVALUE_BLOOM_DIRTTEX = Shader3D.propertyNameToID("u_Bloom_DirtTex");
  6549. PostProcess.SHADERVALUE_BLOOMTEX_TEXELSIZE = Shader3D.propertyNameToID("u_BloomTex_TexelSize");
  6550. PostProcess.SHADERVALUE_BLOOM_DIRTTILEOFFSET = Shader3D.propertyNameToID("u_Bloom_DirtTileOffset");
  6551. PostProcess.SHADERVALUE_BLOOM_SETTINGS = Shader3D.propertyNameToID("u_Bloom_Settings");
  6552. PostProcess.SHADERVALUE_BLOOM_COLOR = Shader3D.propertyNameToID("u_Bloom_Color");
  6553. class AnimationTransform3D extends Laya.EventDispatcher {
  6554. constructor(owner, localPosition = null, localRotation = null, localScale = null, worldMatrix = null) {
  6555. super();
  6556. this._owner = owner;
  6557. this._children = [];
  6558. this._localMatrix = new Float32Array(16);
  6559. if (Laya.Render.supportWebGLPlusAnimation) {
  6560. this._localPosition = new ConchVector3(0, 0, 0, localPosition);
  6561. this._localRotation = new ConchQuaternion(0, 0, 0, 1, localRotation);
  6562. this._localScale = new ConchVector3(0, 0, 0, localScale);
  6563. this._worldMatrix = worldMatrix;
  6564. }
  6565. else {
  6566. this._localPosition = new Vector3();
  6567. this._localRotation = new Quaternion();
  6568. this._localScale = new Vector3();
  6569. this._worldMatrix = new Float32Array(16);
  6570. }
  6571. this._localQuaternionUpdate = false;
  6572. this._locaEulerlUpdate = false;
  6573. this._localUpdate = false;
  6574. this._worldUpdate = true;
  6575. }
  6576. _getlocalMatrix() {
  6577. if (this._localUpdate) {
  6578. Utils3D._createAffineTransformationArray(this._localPosition, this._localRotation, this._localScale, this._localMatrix);
  6579. this._localUpdate = false;
  6580. }
  6581. return this._localMatrix;
  6582. }
  6583. _onWorldTransform() {
  6584. if (!this._worldUpdate) {
  6585. this._worldUpdate = true;
  6586. this.event(Laya.Event.TRANSFORM_CHANGED);
  6587. for (var i = 0, n = this._children.length; i < n; i++)
  6588. this._children[i]._onWorldTransform();
  6589. }
  6590. }
  6591. get localPosition() {
  6592. return this._localPosition;
  6593. }
  6594. set localPosition(value) {
  6595. this._localPosition = value;
  6596. this._localUpdate = true;
  6597. this._onWorldTransform();
  6598. }
  6599. get localRotation() {
  6600. if (this._localQuaternionUpdate) {
  6601. var euler = this._localRotationEuler;
  6602. Quaternion.createFromYawPitchRoll(euler.y / AnimationTransform3D._angleToRandin, euler.x / AnimationTransform3D._angleToRandin, euler.z / AnimationTransform3D._angleToRandin, this._localRotation);
  6603. this._localQuaternionUpdate = false;
  6604. }
  6605. return this._localRotation;
  6606. }
  6607. set localRotation(value) {
  6608. this._localRotation = value;
  6609. this._locaEulerlUpdate = true;
  6610. this._localQuaternionUpdate = false;
  6611. this._localUpdate = true;
  6612. this._onWorldTransform();
  6613. }
  6614. get localScale() {
  6615. return this._localScale;
  6616. }
  6617. set localScale(value) {
  6618. this._localScale = value;
  6619. this._localUpdate = true;
  6620. this._onWorldTransform();
  6621. }
  6622. get localRotationEuler() {
  6623. if (this._locaEulerlUpdate) {
  6624. this._localRotation.getYawPitchRoll(AnimationTransform3D._tempVector3);
  6625. var euler = AnimationTransform3D._tempVector3;
  6626. var localRotationEuler = this._localRotationEuler;
  6627. localRotationEuler.x = euler.y * AnimationTransform3D._angleToRandin;
  6628. localRotationEuler.y = euler.x * AnimationTransform3D._angleToRandin;
  6629. localRotationEuler.z = euler.z * AnimationTransform3D._angleToRandin;
  6630. this._locaEulerlUpdate = false;
  6631. }
  6632. return this._localRotationEuler;
  6633. }
  6634. set localRotationEuler(value) {
  6635. this._localRotationEuler = value;
  6636. this._locaEulerlUpdate = false;
  6637. this._localQuaternionUpdate = true;
  6638. this._localUpdate = true;
  6639. this._onWorldTransform();
  6640. }
  6641. getWorldMatrix() {
  6642. if (!Laya.Render.supportWebGLPlusAnimation && this._worldUpdate) {
  6643. if (this._parent != null) {
  6644. Utils3D.matrix4x4MultiplyFFF(this._parent.getWorldMatrix(), this._getlocalMatrix(), this._worldMatrix);
  6645. }
  6646. else {
  6647. var e = this._worldMatrix;
  6648. e[1] = e[2] = e[3] = e[4] = e[6] = e[7] = e[8] = e[9] = e[11] = e[12] = e[13] = e[14] = 0;
  6649. e[0] = e[5] = e[10] = e[15] = 1;
  6650. }
  6651. this._worldUpdate = false;
  6652. }
  6653. if (Laya.Render.supportWebGLPlusAnimation && this._worldUpdate) {
  6654. this._worldUpdate = false;
  6655. }
  6656. return this._worldMatrix;
  6657. }
  6658. setParent(value) {
  6659. if (this._parent !== value) {
  6660. if (this._parent) {
  6661. var parentChilds = this._parent._children;
  6662. var index = parentChilds.indexOf(this);
  6663. parentChilds.splice(index, 1);
  6664. }
  6665. if (value) {
  6666. value._children.push(this);
  6667. (value) && (this._onWorldTransform());
  6668. }
  6669. this._parent = value;
  6670. }
  6671. }
  6672. }
  6673. AnimationTransform3D._tempVector3 = new Vector3();
  6674. AnimationTransform3D._angleToRandin = 180 / Math.PI;
  6675. class AnimationNode {
  6676. constructor(localPosition = null, localRotation = null, localScale = null, worldMatrix = null) {
  6677. this._children = [];
  6678. this.transform = new AnimationTransform3D(this, localPosition, localRotation, localScale, worldMatrix);
  6679. }
  6680. addChild(child) {
  6681. child._parent = this;
  6682. child.transform.setParent(this.transform);
  6683. this._children.push(child);
  6684. }
  6685. removeChild(child) {
  6686. var index = this._children.indexOf(child);
  6687. (index !== -1) && (this._children.splice(index, 1));
  6688. }
  6689. getChildByName(name) {
  6690. for (var i = 0, n = this._children.length; i < n; i++) {
  6691. var child = this._children[i];
  6692. if (child.name === name)
  6693. return child;
  6694. }
  6695. return null;
  6696. }
  6697. getChildByIndex(index) {
  6698. return this._children[index];
  6699. }
  6700. getChildCount() {
  6701. return this._children.length;
  6702. }
  6703. cloneTo(destObject) {
  6704. var destNode = destObject;
  6705. destNode.name = this.name;
  6706. for (var i = 0, n = this._children.length; i < n; i++) {
  6707. var child = this._children[i];
  6708. var destChild = child.clone();
  6709. destNode.addChild(destChild);
  6710. var transform = child.transform;
  6711. var destTransform = destChild.transform;
  6712. var destLocalPosition = destTransform.localPosition;
  6713. var destLocalRotation = destTransform.localRotation;
  6714. var destLocalScale = destTransform.localScale;
  6715. transform.localPosition.cloneTo(destLocalPosition);
  6716. transform.localRotation.cloneTo(destLocalRotation);
  6717. transform.localScale.cloneTo(destLocalScale);
  6718. destTransform.localPosition = destLocalPosition;
  6719. destTransform.localRotation = destLocalRotation;
  6720. destTransform.localScale = destLocalScale;
  6721. }
  6722. }
  6723. clone() {
  6724. var dest = new AnimationNode();
  6725. this.cloneTo(dest);
  6726. return dest;
  6727. }
  6728. _cloneNative(localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar) {
  6729. var curID = avatar._nativeCurCloneCount;
  6730. animationNodeParentIndices[curID] = parentIndex;
  6731. var localPosition = new Float32Array(localPositions.buffer, curID * 3 * 4, 3);
  6732. var localRotation = new Float32Array(localRotations.buffer, curID * 4 * 4, 4);
  6733. var localScale = new Float32Array(localScales.buffer, curID * 3 * 4, 3);
  6734. var worldMatrix = new Float32Array(animationNodeWorldMatrixs.buffer, curID * 16 * 4, 16);
  6735. var dest = new AnimationNode(localPosition, localRotation, localScale, worldMatrix);
  6736. dest._worldMatrixIndex = curID;
  6737. this._cloneToNative(dest, localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, curID, avatar);
  6738. return dest;
  6739. }
  6740. _cloneToNative(destObject, localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar) {
  6741. var destNode = destObject;
  6742. destNode.name = this.name;
  6743. for (var i = 0, n = this._children.length; i < n; i++) {
  6744. var child = this._children[i];
  6745. avatar._nativeCurCloneCount++;
  6746. var destChild = child._cloneNative(localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar);
  6747. destNode.addChild(destChild);
  6748. var transform = child.transform;
  6749. var destTransform = destChild.transform;
  6750. var destLocalPosition = destTransform.localPosition;
  6751. var destLocalRotation = destTransform.localRotation;
  6752. var destLocalScale = destTransform.localScale;
  6753. transform.localPosition.cloneTo(destLocalPosition);
  6754. transform.localRotation.cloneTo(destLocalRotation);
  6755. transform.localScale.cloneTo(destLocalScale);
  6756. destTransform.localPosition = destLocalPosition;
  6757. destTransform.localRotation = destLocalRotation;
  6758. destTransform.localScale = destLocalScale;
  6759. }
  6760. }
  6761. }
  6762. class Avatar extends Laya.Resource {
  6763. constructor() {
  6764. super();
  6765. this._nativeNodeCount = 0;
  6766. this._nativeCurCloneCount = 0;
  6767. }
  6768. static _parse(data, propertyParams = null, constructParams = null) {
  6769. var avatar = new Avatar();
  6770. avatar._rootNode = new AnimationNode(new Float32Array(3), new Float32Array(4), new Float32Array(3), new Float32Array(16));
  6771. if (Laya.Render.supportWebGLPlusAnimation)
  6772. avatar._nativeNodeCount++;
  6773. if (data.version) {
  6774. var rootNode = data.rootNode;
  6775. (rootNode) && (avatar._parseNode(rootNode, avatar._rootNode));
  6776. }
  6777. return avatar;
  6778. }
  6779. static load(url, complete) {
  6780. Laya.ILaya.loader.create(url, complete, null, Avatar.AVATAR);
  6781. }
  6782. _initCloneToAnimator(destNode, destAnimator) {
  6783. destAnimator._avatarNodeMap[destNode.name] = destNode;
  6784. for (var i = 0, n = destNode.getChildCount(); i < n; i++)
  6785. this._initCloneToAnimator(destNode.getChildByIndex(i), destAnimator);
  6786. }
  6787. _parseNode(nodaData, node) {
  6788. var name = nodaData.props.name;
  6789. node.name = name;
  6790. var props = nodaData.props;
  6791. var transform = node.transform;
  6792. var pos = transform.localPosition;
  6793. var rot = transform.localRotation;
  6794. var sca = transform.localScale;
  6795. pos.fromArray(props.translate);
  6796. rot.fromArray(props.rotation);
  6797. sca.fromArray(props.scale);
  6798. transform.localPosition = pos;
  6799. transform.localRotation = rot;
  6800. transform.localScale = sca;
  6801. var childrenData = nodaData.child;
  6802. for (var j = 0, n = childrenData.length; j < n; j++) {
  6803. var childData = childrenData[j];
  6804. var childBone = new AnimationNode(new Float32Array(3), new Float32Array(4), new Float32Array(3), new Float32Array(16));
  6805. node.addChild(childBone);
  6806. if (Laya.Render.supportWebGLPlusAnimation)
  6807. this._nativeNodeCount++;
  6808. this._parseNode(childData, childBone);
  6809. }
  6810. }
  6811. _cloneDatasToAnimator(destAnimator) {
  6812. var destRoot;
  6813. destRoot = this._rootNode.clone();
  6814. var transform = this._rootNode.transform;
  6815. var destTransform = destRoot.transform;
  6816. var destPosition = destTransform.localPosition;
  6817. var destRotation = destTransform.localRotation;
  6818. var destScale = destTransform.localScale;
  6819. transform.localPosition.cloneTo(destPosition);
  6820. transform.localRotation.cloneTo(destRotation);
  6821. transform.localScale.cloneTo(destScale);
  6822. destTransform.localPosition = destPosition;
  6823. destTransform.localRotation = destRotation;
  6824. destTransform.localScale = destScale;
  6825. destAnimator._avatarNodeMap = {};
  6826. this._initCloneToAnimator(destRoot, destAnimator);
  6827. }
  6828. cloneTo(destObject) {
  6829. var destAvatar = destObject;
  6830. var destRoot = this._rootNode.clone();
  6831. destAvatar._rootNode = destRoot;
  6832. }
  6833. clone() {
  6834. var dest = new Avatar();
  6835. this.cloneTo(dest);
  6836. return dest;
  6837. }
  6838. _cloneDatasToAnimatorNative(destAnimator) {
  6839. var animationNodeLocalPositions = new Float32Array(this._nativeNodeCount * 3);
  6840. var animationNodeLocalRotations = new Float32Array(this._nativeNodeCount * 4);
  6841. var animationNodeLocalScales = new Float32Array(this._nativeNodeCount * 3);
  6842. var animationNodeWorldMatrixs = new Float32Array(this._nativeNodeCount * 16);
  6843. var animationNodeParentIndices = new Int16Array(this._nativeNodeCount);
  6844. destAnimator._animationNodeLocalPositions = animationNodeLocalPositions;
  6845. destAnimator._animationNodeLocalRotations = animationNodeLocalRotations;
  6846. destAnimator._animationNodeLocalScales = animationNodeLocalScales;
  6847. destAnimator._animationNodeWorldMatrixs = animationNodeWorldMatrixs;
  6848. destAnimator._animationNodeParentIndices = animationNodeParentIndices;
  6849. this._nativeCurCloneCount = 0;
  6850. var destRoot = this._rootNode._cloneNative(animationNodeLocalPositions, animationNodeLocalRotations, animationNodeLocalScales, animationNodeWorldMatrixs, animationNodeParentIndices, -1, this);
  6851. var transform = this._rootNode.transform;
  6852. var destTransform = destRoot.transform;
  6853. var destPosition = destTransform.localPosition;
  6854. var destRotation = destTransform.localRotation;
  6855. var destScale = destTransform.localScale;
  6856. transform.localPosition.cloneTo(destPosition);
  6857. transform.localRotation.cloneTo(destRotation);
  6858. transform.localScale.cloneTo(destScale);
  6859. destTransform.localPosition = destPosition;
  6860. destTransform.localRotation = destRotation;
  6861. destTransform.localScale = destScale;
  6862. destAnimator._avatarNodeMap = {};
  6863. this._initCloneToAnimator(destRoot, destAnimator);
  6864. }
  6865. }
  6866. Avatar.AVATAR = "AVATAR";
  6867. class Material extends Laya.Resource {
  6868. constructor() {
  6869. super();
  6870. this._shaderValues = null;
  6871. this._disablePublicDefineDatas = new DefineDatas();
  6872. this._shaderValues = new ShaderData(this);
  6873. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  6874. this._alphaTest = false;
  6875. }
  6876. static load(url, complete) {
  6877. Laya.Laya.loader.create(url, complete, null, Material.MATERIAL);
  6878. }
  6879. static __initDefine__() {
  6880. Material.SHADERDEFINE_ALPHATEST = Shader3D.getDefineByName("ALPHATEST");
  6881. }
  6882. static _parse(data, propertyParams = null, constructParams = null) {
  6883. var jsonData = data;
  6884. var props = jsonData.props;
  6885. var material;
  6886. var classType = props.type;
  6887. var clas = Laya.ClassUtils.getRegClass(classType);
  6888. if (clas)
  6889. material = new clas();
  6890. else
  6891. throw ('_getSprite3DHierarchyInnerUrls 错误: ' + data.type + ' 不是类');
  6892. switch (jsonData.version) {
  6893. case "LAYAMATERIAL:01":
  6894. case "LAYAMATERIAL:02":
  6895. var i, n;
  6896. for (var key in props) {
  6897. switch (key) {
  6898. case "vectors":
  6899. var vectors = props[key];
  6900. for (i = 0, n = vectors.length; i < n; i++) {
  6901. var vector = vectors[i];
  6902. var vectorValue = vector.value;
  6903. switch (vectorValue.length) {
  6904. case 2:
  6905. material[vector.name] = new Vector2(vectorValue[0], vectorValue[1]);
  6906. break;
  6907. case 3:
  6908. material[vector.name] = new Vector3(vectorValue[0], vectorValue[1], vectorValue[2]);
  6909. break;
  6910. case 4:
  6911. material[vector.name] = new Vector4(vectorValue[0], vectorValue[1], vectorValue[2], vectorValue[3]);
  6912. break;
  6913. default:
  6914. throw new Error("BaseMaterial:unkonwn color length.");
  6915. }
  6916. }
  6917. break;
  6918. case "textures":
  6919. var textures = props[key];
  6920. for (i = 0, n = textures.length; i < n; i++) {
  6921. var texture = textures[i];
  6922. var path = texture.path;
  6923. (path) && (material[texture.name] = Laya.Loader.getRes(path));
  6924. }
  6925. break;
  6926. case "defines":
  6927. var defineNames = props[key];
  6928. for (i = 0, n = defineNames.length; i < n; i++) {
  6929. var define = Shader3D.getDefineByName(defineNames[i]);
  6930. material._shaderValues.addDefine(define);
  6931. }
  6932. break;
  6933. case "renderStates":
  6934. var renderStatesData = props[key];
  6935. var renderStateData = renderStatesData[0];
  6936. var mat = material;
  6937. mat.blend = renderStateData.blend;
  6938. mat.cull = renderStateData.cull;
  6939. mat.depthTest = renderStateData.depthTest;
  6940. mat.depthWrite = renderStateData.depthWrite;
  6941. mat.blendSrc = renderStateData.srcBlend;
  6942. mat.blendDst = renderStateData.dstBlend;
  6943. break;
  6944. case "cull":
  6945. material.cull = props[key];
  6946. break;
  6947. case "blend":
  6948. material.blend = props[key];
  6949. break;
  6950. case "depthWrite":
  6951. material.depthWrite = props[key];
  6952. break;
  6953. case "srcBlend":
  6954. material.blendSrc = props[key];
  6955. break;
  6956. case "dstBlend":
  6957. material.blendDst = props[key];
  6958. break;
  6959. default:
  6960. material[key] = props[key];
  6961. }
  6962. }
  6963. break;
  6964. default:
  6965. throw new Error("BaseMaterial:unkonwn version.");
  6966. }
  6967. return material;
  6968. }
  6969. get shaderData() {
  6970. return this._shaderValues;
  6971. }
  6972. get alphaTestValue() {
  6973. return this._shaderValues.getNumber(Material.ALPHATESTVALUE);
  6974. }
  6975. set alphaTestValue(value) {
  6976. this._shaderValues.setNumber(Material.ALPHATESTVALUE, value);
  6977. }
  6978. get alphaTest() {
  6979. return this._alphaTest;
  6980. }
  6981. set alphaTest(value) {
  6982. this._alphaTest = value;
  6983. if (value)
  6984. this._shaderValues.addDefine(Material.SHADERDEFINE_ALPHATEST);
  6985. else
  6986. this._shaderValues.removeDefine(Material.SHADERDEFINE_ALPHATEST);
  6987. }
  6988. _removeTetxureReference() {
  6989. var data = this._shaderValues.getData();
  6990. for (var k in data) {
  6991. var value = data[k];
  6992. if (value && value instanceof Laya.BaseTexture)
  6993. value._removeReference();
  6994. }
  6995. }
  6996. _disposeResource() {
  6997. if (this._referenceCount > 0)
  6998. this._removeTetxureReference();
  6999. this._shaderValues = null;
  7000. }
  7001. _addReference(count = 1) {
  7002. super._addReference(count);
  7003. var data = this._shaderValues.getData();
  7004. for (var k in data) {
  7005. var value = data[k];
  7006. if (value && value instanceof Laya.BaseTexture)
  7007. value._addReference();
  7008. }
  7009. }
  7010. _removeReference(count = 1) {
  7011. super._removeReference(count);
  7012. this._removeTetxureReference();
  7013. }
  7014. setShaderName(name) {
  7015. this._shader = Shader3D.find(name);
  7016. if (!this._shader)
  7017. throw new Error("BaseMaterial: unknown shader name.");
  7018. }
  7019. cloneTo(destObject) {
  7020. var destBaseMaterial = destObject;
  7021. destBaseMaterial.name = this.name;
  7022. destBaseMaterial.renderQueue = this.renderQueue;
  7023. this._disablePublicDefineDatas.cloneTo(destBaseMaterial._disablePublicDefineDatas);
  7024. this._shaderValues.cloneTo(destBaseMaterial._shaderValues);
  7025. }
  7026. clone() {
  7027. var dest = new Material();
  7028. this.cloneTo(dest);
  7029. return dest;
  7030. }
  7031. get _defineDatas() {
  7032. return this._shaderValues._defineDatas;
  7033. }
  7034. }
  7035. Material.MATERIAL = "MATERIAL";
  7036. Material.RENDERQUEUE_OPAQUE = 2000;
  7037. Material.RENDERQUEUE_ALPHATEST = 2450;
  7038. Material.RENDERQUEUE_TRANSPARENT = 3000;
  7039. Material.ALPHATESTVALUE = Shader3D.propertyNameToID("u_AlphaTestValue");
  7040. Material.SHADERDEFINE_ALPHATEST = null;
  7041. class BaseMaterial {
  7042. static load(url, complete) {
  7043. Laya.Laya.loader.create(url, complete, null, Material.MATERIAL);
  7044. }
  7045. static __initDefine__() {
  7046. BaseMaterial.SHADERDEFINE_ALPHATEST = Material.SHADERDEFINE_ALPHATEST;
  7047. }
  7048. }
  7049. BaseMaterial.MATERIAL = "MATERIAL";
  7050. BaseMaterial.RENDERQUEUE_OPAQUE = 2000;
  7051. BaseMaterial.RENDERQUEUE_ALPHATEST = 2450;
  7052. BaseMaterial.RENDERQUEUE_TRANSPARENT = 3000;
  7053. BaseMaterial.ALPHATESTVALUE = Shader3D.propertyNameToID("u_AlphaTestValue");
  7054. BaseMaterial.SHADERDEFINE_ALPHATEST = null;
  7055. class Scene3DShaderDeclaration {
  7056. }
  7057. class RenderState {
  7058. constructor() {
  7059. this.cull = RenderState.CULL_BACK;
  7060. this.blend = RenderState.BLEND_DISABLE;
  7061. this.srcBlend = RenderState.BLENDPARAM_ONE;
  7062. this.dstBlend = RenderState.BLENDPARAM_ZERO;
  7063. this.srcBlendRGB = RenderState.BLENDPARAM_ONE;
  7064. this.dstBlendRGB = RenderState.BLENDPARAM_ZERO;
  7065. this.srcBlendAlpha = RenderState.BLENDPARAM_ONE;
  7066. this.dstBlendAlpha = RenderState.BLENDPARAM_ZERO;
  7067. this.blendConstColor = new Vector4(1, 1, 1, 1);
  7068. this.blendEquation = RenderState.BLENDEQUATION_ADD;
  7069. this.blendEquationRGB = RenderState.BLENDEQUATION_ADD;
  7070. this.blendEquationAlpha = RenderState.BLENDEQUATION_ADD;
  7071. this.depthTest = RenderState.DEPTHTEST_LEQUAL;
  7072. this.depthWrite = true;
  7073. }
  7074. cloneTo(dest) {
  7075. var destState = dest;
  7076. destState.cull = this.cull;
  7077. destState.blend = this.blend;
  7078. destState.srcBlend = this.srcBlend;
  7079. destState.dstBlend = this.dstBlend;
  7080. destState.srcBlendRGB = this.srcBlendRGB;
  7081. destState.dstBlendRGB = this.dstBlendRGB;
  7082. destState.srcBlendAlpha = this.srcBlendAlpha;
  7083. destState.dstBlendAlpha = this.dstBlendAlpha;
  7084. this.blendConstColor.cloneTo(destState.blendConstColor);
  7085. destState.blendEquation = this.blendEquation;
  7086. destState.blendEquationRGB = this.blendEquationRGB;
  7087. destState.blendEquationAlpha = this.blendEquationAlpha;
  7088. destState.depthTest = this.depthTest;
  7089. destState.depthWrite = this.depthWrite;
  7090. }
  7091. clone() {
  7092. var dest = new RenderState();
  7093. this.cloneTo(dest);
  7094. return dest;
  7095. }
  7096. }
  7097. RenderState.CULL_NONE = 0;
  7098. RenderState.CULL_FRONT = 1;
  7099. RenderState.CULL_BACK = 2;
  7100. RenderState.BLEND_DISABLE = 0;
  7101. RenderState.BLEND_ENABLE_ALL = 1;
  7102. RenderState.BLEND_ENABLE_SEPERATE = 2;
  7103. RenderState.BLENDPARAM_ZERO = 0;
  7104. RenderState.BLENDPARAM_ONE = 1;
  7105. RenderState.BLENDPARAM_SRC_COLOR = 0x0300;
  7106. RenderState.BLENDPARAM_ONE_MINUS_SRC_COLOR = 0x0301;
  7107. RenderState.BLENDPARAM_DST_COLOR = 0x0306;
  7108. RenderState.BLENDPARAM_ONE_MINUS_DST_COLOR = 0x0307;
  7109. RenderState.BLENDPARAM_SRC_ALPHA = 0x0302;
  7110. RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA = 0x0303;
  7111. RenderState.BLENDPARAM_DST_ALPHA = 0x0304;
  7112. RenderState.BLENDPARAM_ONE_MINUS_DST_ALPHA = 0x0305;
  7113. RenderState.BLENDPARAM_SRC_ALPHA_SATURATE = 0x0308;
  7114. RenderState.BLENDEQUATION_ADD = 0x8006;
  7115. RenderState.BLENDEQUATION_SUBTRACT = 0x800A;
  7116. RenderState.BLENDEQUATION_REVERSE_SUBTRACT = 0x800B;
  7117. RenderState.DEPTHTEST_OFF = 0;
  7118. RenderState.DEPTHTEST_NEVER = 0x0200;
  7119. RenderState.DEPTHTEST_LESS = 0x0201;
  7120. RenderState.DEPTHTEST_EQUAL = 0x0202;
  7121. RenderState.DEPTHTEST_LEQUAL = 0x0203;
  7122. RenderState.DEPTHTEST_GREATER = 0x0204;
  7123. RenderState.DEPTHTEST_NOTEQUAL = 0x0205;
  7124. RenderState.DEPTHTEST_GEQUAL = 0x0206;
  7125. RenderState.DEPTHTEST_ALWAYS = 0x0207;
  7126. class BlinnPhongMaterial extends Material {
  7127. constructor() {
  7128. super();
  7129. this._enableVertexColor = false;
  7130. this.setShaderName("BLINNPHONG");
  7131. this._albedoIntensity = 1.0;
  7132. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  7133. var sv = this._shaderValues;
  7134. sv.setVector(BlinnPhongMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  7135. sv.setVector(BlinnPhongMaterial.MATERIALSPECULAR, new Vector4(1.0, 1.0, 1.0, 1.0));
  7136. sv.setNumber(BlinnPhongMaterial.SHININESS, 0.078125);
  7137. sv.setNumber(Material.ALPHATESTVALUE, 0.5);
  7138. sv.setVector(BlinnPhongMaterial.TILINGOFFSET, new Vector4(1.0, 1.0, 0.0, 0.0));
  7139. this._enableLighting = true;
  7140. this.renderMode = BlinnPhongMaterial.RENDERMODE_OPAQUE;
  7141. }
  7142. static __initDefine__() {
  7143. BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP = Shader3D.getDefineByName("DIFFUSEMAP");
  7144. BlinnPhongMaterial.SHADERDEFINE_NORMALMAP = Shader3D.getDefineByName("NORMALMAP");
  7145. BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP = Shader3D.getDefineByName("SPECULARMAP");
  7146. BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  7147. BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR = Shader3D.getDefineByName("ENABLEVERTEXCOLOR");
  7148. }
  7149. get _ColorR() {
  7150. return this._albedoColor.x;
  7151. }
  7152. set _ColorR(value) {
  7153. this._albedoColor.x = value;
  7154. this.albedoColor = this._albedoColor;
  7155. }
  7156. get _ColorG() {
  7157. return this._albedoColor.y;
  7158. }
  7159. set _ColorG(value) {
  7160. this._albedoColor.y = value;
  7161. this.albedoColor = this._albedoColor;
  7162. }
  7163. get _ColorB() {
  7164. return this._albedoColor.z;
  7165. }
  7166. set _ColorB(value) {
  7167. this._albedoColor.z = value;
  7168. this.albedoColor = this._albedoColor;
  7169. }
  7170. get _ColorA() {
  7171. return this._albedoColor.w;
  7172. }
  7173. set _ColorA(value) {
  7174. this._albedoColor.w = value;
  7175. this.albedoColor = this._albedoColor;
  7176. }
  7177. get _SpecColorR() {
  7178. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).x;
  7179. }
  7180. set _SpecColorR(value) {
  7181. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).x = value;
  7182. }
  7183. get _SpecColorG() {
  7184. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).y;
  7185. }
  7186. set _SpecColorG(value) {
  7187. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).y = value;
  7188. }
  7189. get _SpecColorB() {
  7190. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).z;
  7191. }
  7192. set _SpecColorB(value) {
  7193. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).z = value;
  7194. }
  7195. get _SpecColorA() {
  7196. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).w;
  7197. }
  7198. set _SpecColorA(value) {
  7199. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).w = value;
  7200. }
  7201. get _AlbedoIntensity() {
  7202. return this._albedoIntensity;
  7203. }
  7204. set _AlbedoIntensity(value) {
  7205. if (this._albedoIntensity !== value) {
  7206. var finalAlbedo = this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  7207. Vector4.scale(this._albedoColor, value, finalAlbedo);
  7208. this._albedoIntensity = value;
  7209. this._shaderValues.setVector(BlinnPhongMaterial.ALBEDOCOLOR, finalAlbedo);
  7210. }
  7211. }
  7212. get _Shininess() {
  7213. return this._shaderValues.getNumber(BlinnPhongMaterial.SHININESS);
  7214. }
  7215. set _Shininess(value) {
  7216. value = Math.max(0.0, Math.min(1.0, value));
  7217. this._shaderValues.setNumber(BlinnPhongMaterial.SHININESS, value);
  7218. }
  7219. get _MainTex_STX() {
  7220. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).x;
  7221. }
  7222. set _MainTex_STX(x) {
  7223. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7224. tilOff.x = x;
  7225. this.tilingOffset = tilOff;
  7226. }
  7227. get _MainTex_STY() {
  7228. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).y;
  7229. }
  7230. set _MainTex_STY(y) {
  7231. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7232. tilOff.y = y;
  7233. this.tilingOffset = tilOff;
  7234. }
  7235. get _MainTex_STZ() {
  7236. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).z;
  7237. }
  7238. set _MainTex_STZ(z) {
  7239. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7240. tilOff.z = z;
  7241. this.tilingOffset = tilOff;
  7242. }
  7243. get _MainTex_STW() {
  7244. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).w;
  7245. }
  7246. set _MainTex_STW(w) {
  7247. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7248. tilOff.w = w;
  7249. this.tilingOffset = tilOff;
  7250. }
  7251. get _Cutoff() {
  7252. return this.alphaTestValue;
  7253. }
  7254. set _Cutoff(value) {
  7255. this.alphaTestValue = value;
  7256. }
  7257. set renderMode(value) {
  7258. switch (value) {
  7259. case BlinnPhongMaterial.RENDERMODE_OPAQUE:
  7260. this.alphaTest = false;
  7261. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  7262. this.depthWrite = true;
  7263. this.cull = RenderState.CULL_BACK;
  7264. this.blend = RenderState.BLEND_DISABLE;
  7265. this.depthTest = RenderState.DEPTHTEST_LESS;
  7266. break;
  7267. case BlinnPhongMaterial.RENDERMODE_CUTOUT:
  7268. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  7269. this.alphaTest = true;
  7270. this.depthWrite = true;
  7271. this.cull = RenderState.CULL_BACK;
  7272. this.blend = RenderState.BLEND_DISABLE;
  7273. this.depthTest = RenderState.DEPTHTEST_LESS;
  7274. break;
  7275. case BlinnPhongMaterial.RENDERMODE_TRANSPARENT:
  7276. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  7277. this.alphaTest = false;
  7278. this.depthWrite = false;
  7279. this.cull = RenderState.CULL_BACK;
  7280. this.blend = RenderState.BLEND_ENABLE_ALL;
  7281. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  7282. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  7283. this.depthTest = RenderState.DEPTHTEST_LESS;
  7284. break;
  7285. default:
  7286. throw new Error("Material:renderMode value error.");
  7287. }
  7288. }
  7289. get enableVertexColor() {
  7290. return this._enableVertexColor;
  7291. }
  7292. set enableVertexColor(value) {
  7293. this._enableVertexColor = value;
  7294. if (value)
  7295. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  7296. else
  7297. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  7298. }
  7299. get tilingOffsetX() {
  7300. return this._MainTex_STX;
  7301. }
  7302. set tilingOffsetX(x) {
  7303. this._MainTex_STX = x;
  7304. }
  7305. get tilingOffsetY() {
  7306. return this._MainTex_STY;
  7307. }
  7308. set tilingOffsetY(y) {
  7309. this._MainTex_STY = y;
  7310. }
  7311. get tilingOffsetZ() {
  7312. return this._MainTex_STZ;
  7313. }
  7314. set tilingOffsetZ(z) {
  7315. this._MainTex_STZ = z;
  7316. }
  7317. get tilingOffsetW() {
  7318. return this._MainTex_STW;
  7319. }
  7320. set tilingOffsetW(w) {
  7321. this._MainTex_STW = w;
  7322. }
  7323. get tilingOffset() {
  7324. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  7325. }
  7326. set tilingOffset(value) {
  7327. if (value) {
  7328. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  7329. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  7330. else
  7331. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  7332. }
  7333. else {
  7334. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  7335. }
  7336. this._shaderValues.setVector(BlinnPhongMaterial.TILINGOFFSET, value);
  7337. }
  7338. get albedoColorR() {
  7339. return this._ColorR;
  7340. }
  7341. set albedoColorR(value) {
  7342. this._ColorR = value;
  7343. }
  7344. get albedoColorG() {
  7345. return this._ColorG;
  7346. }
  7347. set albedoColorG(value) {
  7348. this._ColorG = value;
  7349. }
  7350. get albedoColorB() {
  7351. return this._ColorB;
  7352. }
  7353. set albedoColorB(value) {
  7354. this._ColorB = value;
  7355. }
  7356. get albedoColorA() {
  7357. return this._ColorA;
  7358. }
  7359. set albedoColorA(value) {
  7360. this._ColorA = value;
  7361. }
  7362. get albedoColor() {
  7363. return this._albedoColor;
  7364. }
  7365. set albedoColor(value) {
  7366. var finalAlbedo = this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  7367. Vector4.scale(value, this._albedoIntensity, finalAlbedo);
  7368. this._albedoColor = value;
  7369. this._shaderValues.setVector(BlinnPhongMaterial.ALBEDOCOLOR, finalAlbedo);
  7370. }
  7371. get albedoIntensity() {
  7372. return this._albedoIntensity;
  7373. }
  7374. set albedoIntensity(value) {
  7375. this._AlbedoIntensity = value;
  7376. }
  7377. get specularColorR() {
  7378. return this._SpecColorR;
  7379. }
  7380. set specularColorR(value) {
  7381. this._SpecColorR = value;
  7382. }
  7383. get specularColorG() {
  7384. return this._SpecColorG;
  7385. }
  7386. set specularColorG(value) {
  7387. this._SpecColorG = value;
  7388. }
  7389. get specularColorB() {
  7390. return this._SpecColorB;
  7391. }
  7392. set specularColorB(value) {
  7393. this._SpecColorB = value;
  7394. }
  7395. get specularColorA() {
  7396. return this._SpecColorA;
  7397. }
  7398. set specularColorA(value) {
  7399. this._SpecColorA = value;
  7400. }
  7401. get specularColor() {
  7402. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR);
  7403. }
  7404. set specularColor(value) {
  7405. this._shaderValues.setVector(BlinnPhongMaterial.MATERIALSPECULAR, value);
  7406. }
  7407. get shininess() {
  7408. return this._Shininess;
  7409. }
  7410. set shininess(value) {
  7411. this._Shininess = value;
  7412. }
  7413. get albedoTexture() {
  7414. return this._shaderValues.getTexture(BlinnPhongMaterial.ALBEDOTEXTURE);
  7415. }
  7416. set albedoTexture(value) {
  7417. if (value)
  7418. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP);
  7419. else
  7420. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP);
  7421. this._shaderValues.setTexture(BlinnPhongMaterial.ALBEDOTEXTURE, value);
  7422. }
  7423. get normalTexture() {
  7424. return this._shaderValues.getTexture(BlinnPhongMaterial.NORMALTEXTURE);
  7425. }
  7426. set normalTexture(value) {
  7427. if (value)
  7428. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_NORMALMAP);
  7429. else
  7430. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_NORMALMAP);
  7431. this._shaderValues.setTexture(BlinnPhongMaterial.NORMALTEXTURE, value);
  7432. }
  7433. get specularTexture() {
  7434. return this._shaderValues.getTexture(BlinnPhongMaterial.SPECULARTEXTURE);
  7435. }
  7436. set specularTexture(value) {
  7437. if (value)
  7438. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP);
  7439. else
  7440. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP);
  7441. this._shaderValues.setTexture(BlinnPhongMaterial.SPECULARTEXTURE, value);
  7442. }
  7443. get enableLighting() {
  7444. return this._enableLighting;
  7445. }
  7446. set enableLighting(value) {
  7447. if (this._enableLighting !== value) {
  7448. if (value) {
  7449. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  7450. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  7451. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  7452. }
  7453. else {
  7454. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  7455. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  7456. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  7457. }
  7458. this._enableLighting = value;
  7459. }
  7460. }
  7461. get depthWrite() {
  7462. return this._shaderValues.getBool(BlinnPhongMaterial.DEPTH_WRITE);
  7463. }
  7464. set depthWrite(value) {
  7465. this._shaderValues.setBool(BlinnPhongMaterial.DEPTH_WRITE, value);
  7466. }
  7467. get cull() {
  7468. return this._shaderValues.getInt(BlinnPhongMaterial.CULL);
  7469. }
  7470. set cull(value) {
  7471. this._shaderValues.setInt(BlinnPhongMaterial.CULL, value);
  7472. }
  7473. get blend() {
  7474. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND);
  7475. }
  7476. set blend(value) {
  7477. this._shaderValues.setInt(BlinnPhongMaterial.BLEND, value);
  7478. }
  7479. get blendSrc() {
  7480. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND_SRC);
  7481. }
  7482. set blendSrc(value) {
  7483. this._shaderValues.setInt(BlinnPhongMaterial.BLEND_SRC, value);
  7484. }
  7485. get blendDst() {
  7486. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND_DST);
  7487. }
  7488. set blendDst(value) {
  7489. this._shaderValues.setInt(BlinnPhongMaterial.BLEND_DST, value);
  7490. }
  7491. get depthTest() {
  7492. return this._shaderValues.getInt(BlinnPhongMaterial.DEPTH_TEST);
  7493. }
  7494. set depthTest(value) {
  7495. this._shaderValues.setInt(BlinnPhongMaterial.DEPTH_TEST, value);
  7496. }
  7497. clone() {
  7498. var dest = new BlinnPhongMaterial();
  7499. this.cloneTo(dest);
  7500. return dest;
  7501. }
  7502. cloneTo(destObject) {
  7503. super.cloneTo(destObject);
  7504. var destMaterial = destObject;
  7505. destMaterial._enableLighting = this._enableLighting;
  7506. destMaterial._albedoIntensity = this._albedoIntensity;
  7507. destMaterial._enableVertexColor = this._enableVertexColor;
  7508. this._albedoColor.cloneTo(destMaterial._albedoColor);
  7509. }
  7510. }
  7511. BlinnPhongMaterial.RENDERMODE_OPAQUE = 0;
  7512. BlinnPhongMaterial.RENDERMODE_CUTOUT = 1;
  7513. BlinnPhongMaterial.RENDERMODE_TRANSPARENT = 2;
  7514. BlinnPhongMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_DiffuseTexture");
  7515. BlinnPhongMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  7516. BlinnPhongMaterial.SPECULARTEXTURE = Shader3D.propertyNameToID("u_SpecularTexture");
  7517. BlinnPhongMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_DiffuseColor");
  7518. BlinnPhongMaterial.MATERIALSPECULAR = Shader3D.propertyNameToID("u_MaterialSpecular");
  7519. BlinnPhongMaterial.SHININESS = Shader3D.propertyNameToID("u_Shininess");
  7520. BlinnPhongMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  7521. BlinnPhongMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  7522. BlinnPhongMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  7523. BlinnPhongMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  7524. BlinnPhongMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  7525. BlinnPhongMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  7526. BlinnPhongMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  7527. class EffectMaterial extends Material {
  7528. constructor() {
  7529. super();
  7530. this.setShaderName("Effect");
  7531. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  7532. this._shaderValues.setVector(EffectMaterial.TINTCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  7533. this.renderMode = EffectMaterial.RENDERMODE_ADDTIVE;
  7534. }
  7535. static __initDefine__() {
  7536. EffectMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  7537. EffectMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  7538. EffectMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  7539. }
  7540. get _TintColorR() {
  7541. return this._color.x;
  7542. }
  7543. set _TintColorR(value) {
  7544. this._color.x = value;
  7545. this.color = this._color;
  7546. }
  7547. get _TintColorG() {
  7548. return this._color.y;
  7549. }
  7550. set _TintColorG(value) {
  7551. this._color.y = value;
  7552. this.color = this._color;
  7553. }
  7554. get _TintColorB() {
  7555. return this._color.z;
  7556. }
  7557. set _TintColorB(value) {
  7558. this._color.z = value;
  7559. this.color = this._color;
  7560. }
  7561. get _TintColorA() {
  7562. return this._color.w;
  7563. }
  7564. set _TintColorA(value) {
  7565. this._color.w = value;
  7566. this.color = this._color;
  7567. }
  7568. get _MainTex_STX() {
  7569. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).x;
  7570. }
  7571. set _MainTex_STX(x) {
  7572. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7573. tilOff.x = x;
  7574. this.tilingOffset = tilOff;
  7575. }
  7576. get _MainTex_STY() {
  7577. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).y;
  7578. }
  7579. set _MainTex_STY(y) {
  7580. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7581. tilOff.y = y;
  7582. this.tilingOffset = tilOff;
  7583. }
  7584. get _MainTex_STZ() {
  7585. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).z;
  7586. }
  7587. set _MainTex_STZ(z) {
  7588. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7589. tilOff.z = z;
  7590. this.tilingOffset = tilOff;
  7591. }
  7592. get _MainTex_STW() {
  7593. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).w;
  7594. }
  7595. set _MainTex_STW(w) {
  7596. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7597. tilOff.w = w;
  7598. this.tilingOffset = tilOff;
  7599. }
  7600. set renderMode(value) {
  7601. switch (value) {
  7602. case EffectMaterial.RENDERMODE_ADDTIVE:
  7603. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  7604. this.alphaTest = false;
  7605. this.depthWrite = false;
  7606. this.cull = RenderState.CULL_NONE;
  7607. this.blend = RenderState.BLEND_ENABLE_ALL;
  7608. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  7609. this.blendDst = RenderState.BLENDPARAM_ONE;
  7610. this.depthTest = RenderState.DEPTHTEST_LESS;
  7611. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_ADDTIVEFOG);
  7612. break;
  7613. case EffectMaterial.RENDERMODE_ALPHABLENDED:
  7614. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  7615. this.alphaTest = false;
  7616. this.depthWrite = false;
  7617. this.cull = RenderState.CULL_NONE;
  7618. this.blend = RenderState.BLEND_ENABLE_ALL;
  7619. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  7620. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  7621. this.depthTest = RenderState.DEPTHTEST_LESS;
  7622. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_ADDTIVEFOG);
  7623. break;
  7624. default:
  7625. throw new Error("MeshEffectMaterial : renderMode value error.");
  7626. }
  7627. }
  7628. get colorR() {
  7629. return this._TintColorR;
  7630. }
  7631. set colorR(value) {
  7632. this._TintColorR = value;
  7633. }
  7634. get colorG() {
  7635. return this._TintColorG;
  7636. }
  7637. set colorG(value) {
  7638. this._TintColorG = value;
  7639. }
  7640. get colorB() {
  7641. return this._TintColorB;
  7642. }
  7643. set colorB(value) {
  7644. this._TintColorB = value;
  7645. }
  7646. get colorA() {
  7647. return this._TintColorA;
  7648. }
  7649. set colorA(value) {
  7650. this._TintColorA = value;
  7651. }
  7652. get color() {
  7653. return this._shaderValues.getVector(EffectMaterial.TINTCOLOR);
  7654. }
  7655. set color(value) {
  7656. this._shaderValues.setVector(EffectMaterial.TINTCOLOR, value);
  7657. }
  7658. get texture() {
  7659. return this._shaderValues.getTexture(EffectMaterial.MAINTEXTURE);
  7660. }
  7661. set texture(value) {
  7662. if (value)
  7663. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_MAINTEXTURE);
  7664. else
  7665. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_MAINTEXTURE);
  7666. this._shaderValues.setTexture(EffectMaterial.MAINTEXTURE, value);
  7667. }
  7668. get tilingOffsetX() {
  7669. return this._MainTex_STX;
  7670. }
  7671. set tilingOffsetX(x) {
  7672. this._MainTex_STX = x;
  7673. }
  7674. get tilingOffsetY() {
  7675. return this._MainTex_STY;
  7676. }
  7677. set tilingOffsetY(y) {
  7678. this._MainTex_STY = y;
  7679. }
  7680. get tilingOffsetZ() {
  7681. return this._MainTex_STZ;
  7682. }
  7683. set tilingOffsetZ(z) {
  7684. this._MainTex_STZ = z;
  7685. }
  7686. get tilingOffsetW() {
  7687. return this._MainTex_STW;
  7688. }
  7689. set tilingOffsetW(w) {
  7690. this._MainTex_STW = w;
  7691. }
  7692. get tilingOffset() {
  7693. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  7694. }
  7695. set tilingOffset(value) {
  7696. if (value) {
  7697. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  7698. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  7699. else
  7700. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  7701. }
  7702. else {
  7703. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  7704. }
  7705. this._shaderValues.setVector(EffectMaterial.TILINGOFFSET, value);
  7706. }
  7707. get depthWrite() {
  7708. return this._shaderValues.getBool(EffectMaterial.DEPTH_WRITE);
  7709. }
  7710. set depthWrite(value) {
  7711. this._shaderValues.setBool(EffectMaterial.DEPTH_WRITE, value);
  7712. }
  7713. get cull() {
  7714. return this._shaderValues.getInt(EffectMaterial.CULL);
  7715. }
  7716. set cull(value) {
  7717. this._shaderValues.setInt(EffectMaterial.CULL, value);
  7718. }
  7719. get blend() {
  7720. return this._shaderValues.getInt(EffectMaterial.BLEND);
  7721. }
  7722. set blend(value) {
  7723. this._shaderValues.setInt(EffectMaterial.BLEND, value);
  7724. }
  7725. get blendSrc() {
  7726. return this._shaderValues.getInt(EffectMaterial.BLEND_SRC);
  7727. }
  7728. set blendSrc(value) {
  7729. this._shaderValues.setInt(EffectMaterial.BLEND_SRC, value);
  7730. }
  7731. get blendDst() {
  7732. return this._shaderValues.getInt(EffectMaterial.BLEND_DST);
  7733. }
  7734. set blendDst(value) {
  7735. this._shaderValues.setInt(EffectMaterial.BLEND_DST, value);
  7736. }
  7737. get depthTest() {
  7738. return this._shaderValues.getInt(EffectMaterial.DEPTH_TEST);
  7739. }
  7740. set depthTest(value) {
  7741. this._shaderValues.setInt(EffectMaterial.DEPTH_TEST, value);
  7742. }
  7743. clone() {
  7744. var dest = new EffectMaterial();
  7745. this.cloneTo(dest);
  7746. return dest;
  7747. }
  7748. }
  7749. EffectMaterial.RENDERMODE_ADDTIVE = 0;
  7750. EffectMaterial.RENDERMODE_ALPHABLENDED = 1;
  7751. EffectMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  7752. EffectMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  7753. EffectMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  7754. EffectMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  7755. EffectMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  7756. EffectMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  7757. EffectMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  7758. EffectMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  7759. EffectMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  7760. class ExtendTerrainMaterial extends Material {
  7761. constructor() {
  7762. super();
  7763. this._enableLighting = true;
  7764. this.setShaderName("ExtendTerrain");
  7765. this.renderMode = ExtendTerrainMaterial.RENDERMODE_OPAQUE;
  7766. }
  7767. static __initDefine__() {
  7768. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM1");
  7769. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM2");
  7770. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM3");
  7771. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM4");
  7772. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM5");
  7773. }
  7774. get splatAlphaTexture() {
  7775. return this._shaderValues.getTexture(ExtendTerrainMaterial.SPLATALPHATEXTURE);
  7776. }
  7777. set splatAlphaTexture(value) {
  7778. this._shaderValues.setTexture(ExtendTerrainMaterial.SPLATALPHATEXTURE, value);
  7779. }
  7780. get diffuseTexture1() {
  7781. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE1);
  7782. }
  7783. set diffuseTexture1(value) {
  7784. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE1, value);
  7785. this._setDetailNum(1);
  7786. }
  7787. get diffuseTexture2() {
  7788. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE2);
  7789. }
  7790. set diffuseTexture2(value) {
  7791. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE2, value);
  7792. this._setDetailNum(2);
  7793. }
  7794. get diffuseTexture3() {
  7795. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE3);
  7796. }
  7797. set diffuseTexture3(value) {
  7798. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE3, value);
  7799. this._setDetailNum(3);
  7800. }
  7801. get diffuseTexture4() {
  7802. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE4);
  7803. }
  7804. set diffuseTexture4(value) {
  7805. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE4, value);
  7806. this._setDetailNum(4);
  7807. }
  7808. get diffuseTexture5() {
  7809. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE5);
  7810. }
  7811. set diffuseTexture5(value) {
  7812. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE5, value);
  7813. this._setDetailNum(5);
  7814. }
  7815. set diffuseScaleOffset1(scaleOffset1) {
  7816. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET1, scaleOffset1);
  7817. }
  7818. set diffuseScaleOffset2(scaleOffset2) {
  7819. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET2, scaleOffset2);
  7820. }
  7821. set diffuseScaleOffset3(scaleOffset3) {
  7822. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET3, scaleOffset3);
  7823. }
  7824. set diffuseScaleOffset4(scaleOffset4) {
  7825. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET4, scaleOffset4);
  7826. }
  7827. set diffuseScaleOffset5(scaleOffset5) {
  7828. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET5, scaleOffset5);
  7829. }
  7830. get enableLighting() {
  7831. return this._enableLighting;
  7832. }
  7833. set enableLighting(value) {
  7834. if (this._enableLighting !== value) {
  7835. if (value) {
  7836. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  7837. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  7838. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  7839. }
  7840. else {
  7841. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  7842. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  7843. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  7844. }
  7845. this._enableLighting = value;
  7846. }
  7847. }
  7848. set renderMode(value) {
  7849. switch (value) {
  7850. case ExtendTerrainMaterial.RENDERMODE_OPAQUE:
  7851. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  7852. this.depthWrite = true;
  7853. this.cull = RenderState.CULL_BACK;
  7854. this.blend = RenderState.BLEND_DISABLE;
  7855. this.depthTest = RenderState.DEPTHTEST_LESS;
  7856. break;
  7857. case ExtendTerrainMaterial.RENDERMODE_TRANSPARENT:
  7858. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  7859. this.depthWrite = false;
  7860. this.cull = RenderState.CULL_BACK;
  7861. this.blend = RenderState.BLEND_ENABLE_ALL;
  7862. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  7863. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  7864. this.depthTest = RenderState.DEPTHTEST_LEQUAL;
  7865. break;
  7866. default:
  7867. throw new Error("ExtendTerrainMaterial:renderMode value error.");
  7868. }
  7869. }
  7870. get depthWrite() {
  7871. return this._shaderValues.getBool(ExtendTerrainMaterial.DEPTH_WRITE);
  7872. }
  7873. set depthWrite(value) {
  7874. this._shaderValues.setBool(ExtendTerrainMaterial.DEPTH_WRITE, value);
  7875. }
  7876. get cull() {
  7877. return this._shaderValues.getInt(ExtendTerrainMaterial.CULL);
  7878. }
  7879. set cull(value) {
  7880. this._shaderValues.setInt(ExtendTerrainMaterial.CULL, value);
  7881. }
  7882. get blend() {
  7883. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND);
  7884. }
  7885. set blend(value) {
  7886. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND, value);
  7887. }
  7888. get blendSrc() {
  7889. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND_SRC);
  7890. }
  7891. set blendSrc(value) {
  7892. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND_SRC, value);
  7893. }
  7894. get blendDst() {
  7895. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND_DST);
  7896. }
  7897. set blendDst(value) {
  7898. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND_DST, value);
  7899. }
  7900. get depthTest() {
  7901. return this._shaderValues.getInt(ExtendTerrainMaterial.DEPTH_TEST);
  7902. }
  7903. set depthTest(value) {
  7904. this._shaderValues.setInt(ExtendTerrainMaterial.DEPTH_TEST, value);
  7905. }
  7906. _setDetailNum(value) {
  7907. switch (value) {
  7908. case 1:
  7909. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7910. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7911. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7912. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7913. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7914. break;
  7915. case 2:
  7916. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7917. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7918. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7919. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7920. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7921. break;
  7922. case 3:
  7923. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7924. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7925. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7926. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7927. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7928. break;
  7929. case 4:
  7930. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7931. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7932. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7933. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7934. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7935. break;
  7936. case 5:
  7937. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  7938. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  7939. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  7940. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  7941. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  7942. break;
  7943. }
  7944. }
  7945. clone() {
  7946. var dest = new ExtendTerrainMaterial();
  7947. this.cloneTo(dest);
  7948. return dest;
  7949. }
  7950. }
  7951. ExtendTerrainMaterial.RENDERMODE_OPAQUE = 1;
  7952. ExtendTerrainMaterial.RENDERMODE_TRANSPARENT = 2;
  7953. ExtendTerrainMaterial.SPLATALPHATEXTURE = Shader3D.propertyNameToID("u_SplatAlphaTexture");
  7954. ExtendTerrainMaterial.DIFFUSETEXTURE1 = Shader3D.propertyNameToID("u_DiffuseTexture1");
  7955. ExtendTerrainMaterial.DIFFUSETEXTURE2 = Shader3D.propertyNameToID("u_DiffuseTexture2");
  7956. ExtendTerrainMaterial.DIFFUSETEXTURE3 = Shader3D.propertyNameToID("u_DiffuseTexture3");
  7957. ExtendTerrainMaterial.DIFFUSETEXTURE4 = Shader3D.propertyNameToID("u_DiffuseTexture4");
  7958. ExtendTerrainMaterial.DIFFUSETEXTURE5 = Shader3D.propertyNameToID("u_DiffuseTexture5");
  7959. ExtendTerrainMaterial.DIFFUSESCALEOFFSET1 = Shader3D.propertyNameToID("u_DiffuseScaleOffset1");
  7960. ExtendTerrainMaterial.DIFFUSESCALEOFFSET2 = Shader3D.propertyNameToID("u_DiffuseScaleOffset2");
  7961. ExtendTerrainMaterial.DIFFUSESCALEOFFSET3 = Shader3D.propertyNameToID("u_DiffuseScaleOffset3");
  7962. ExtendTerrainMaterial.DIFFUSESCALEOFFSET4 = Shader3D.propertyNameToID("u_DiffuseScaleOffset4");
  7963. ExtendTerrainMaterial.DIFFUSESCALEOFFSET5 = Shader3D.propertyNameToID("u_DiffuseScaleOffset5");
  7964. ExtendTerrainMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  7965. ExtendTerrainMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  7966. ExtendTerrainMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  7967. ExtendTerrainMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  7968. ExtendTerrainMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  7969. ExtendTerrainMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  7970. class PBRSpecularMaterial extends Material {
  7971. constructor() {
  7972. super();
  7973. this.setShaderName("PBRSpecular");
  7974. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  7975. this._shaderValues.setVector(PBRSpecularMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  7976. this._emissionColor = new Vector4(0.0, 0.0, 0.0, 0.0);
  7977. this._shaderValues.setVector(PBRSpecularMaterial.EMISSIONCOLOR, new Vector4(0.0, 0.0, 0.0, 0.0));
  7978. this._specularColor = new Vector4(0.2, 0.2, 0.2, 0.2);
  7979. this._shaderValues.setVector(PBRSpecularMaterial.SPECULARCOLOR, new Vector4(0.2, 0.2, 0.2, 0.2));
  7980. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESS, 0.5);
  7981. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESSSCALE, 1.0);
  7982. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESSSOURCE, 0);
  7983. this._shaderValues.setNumber(PBRSpecularMaterial.OCCLUSIONSTRENGTH, 1.0);
  7984. this._shaderValues.setNumber(PBRSpecularMaterial.NORMALSCALE, 1.0);
  7985. this._shaderValues.setNumber(PBRSpecularMaterial.PARALLAXSCALE, 0.001);
  7986. this._shaderValues.setBool(PBRSpecularMaterial.ENABLEEMISSION, false);
  7987. this._shaderValues.setNumber(Material.ALPHATESTVALUE, 0.5);
  7988. this.renderMode = PBRSpecularMaterial.RENDERMODE_OPAQUE;
  7989. }
  7990. static __initDefine__() {
  7991. PBRSpecularMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  7992. PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE = Shader3D.getDefineByName("SPECULARTEXTURE");
  7993. PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA = Shader3D.getDefineByName("SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA");
  7994. PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  7995. PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE = Shader3D.getDefineByName("PARALLAXTEXTURE");
  7996. PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE = Shader3D.getDefineByName("OCCLUSIONTEXTURE");
  7997. PBRSpecularMaterial.SHADERDEFINE_EMISSION = Shader3D.getDefineByName("EMISSION");
  7998. PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE = Shader3D.getDefineByName("EMISSIONTEXTURE");
  7999. PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  8000. PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY = Shader3D.getDefineByName("ALPHAPREMULTIPLY");
  8001. }
  8002. get _ColorR() {
  8003. return this._albedoColor.x;
  8004. }
  8005. set _ColorR(value) {
  8006. this._albedoColor.x = value;
  8007. this.albedoColor = this._albedoColor;
  8008. }
  8009. get _ColorG() {
  8010. return this._albedoColor.y;
  8011. }
  8012. set _ColorG(value) {
  8013. this._albedoColor.y = value;
  8014. this.albedoColor = this._albedoColor;
  8015. }
  8016. get _ColorB() {
  8017. return this._albedoColor.z;
  8018. }
  8019. set _ColorB(value) {
  8020. this._albedoColor.z = value;
  8021. this.albedoColor = this._albedoColor;
  8022. }
  8023. get _ColorA() {
  8024. return this._albedoColor.w;
  8025. }
  8026. set _ColorA(value) {
  8027. this._albedoColor.w = value;
  8028. this.albedoColor = this._albedoColor;
  8029. }
  8030. get _SpecColorR() {
  8031. return this._specularColor.x;
  8032. }
  8033. set _SpecColorR(value) {
  8034. this._specularColor.x = value;
  8035. this.specularColor = this._specularColor;
  8036. }
  8037. get _SpecColorG() {
  8038. return this._specularColor.y;
  8039. }
  8040. set _SpecColorG(value) {
  8041. this._specularColor.y = value;
  8042. this.specularColor = this._specularColor;
  8043. }
  8044. get _SpecColorB() {
  8045. return this._specularColor.z;
  8046. }
  8047. set _SpecColorB(value) {
  8048. this._specularColor.z = value;
  8049. this.specularColor = this._specularColor;
  8050. }
  8051. get _SpecColorA() {
  8052. return this._specularColor.w;
  8053. }
  8054. set _SpecColorA(value) {
  8055. this._specularColor.w = value;
  8056. this.specularColor = this._specularColor;
  8057. }
  8058. get _Glossiness() {
  8059. return this._shaderValues.getNumber(PBRSpecularMaterial.SMOOTHNESS);
  8060. }
  8061. set _Glossiness(value) {
  8062. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESS, value);
  8063. }
  8064. get _GlossMapScale() {
  8065. return this._shaderValues.getNumber(PBRSpecularMaterial.SMOOTHNESSSCALE);
  8066. }
  8067. set _GlossMapScale(value) {
  8068. this._shaderValues.setNumber(PBRSpecularMaterial.SMOOTHNESSSCALE, value);
  8069. }
  8070. get _BumpScale() {
  8071. return this._shaderValues.getNumber(PBRSpecularMaterial.NORMALSCALE);
  8072. }
  8073. set _BumpScale(value) {
  8074. this._shaderValues.setNumber(PBRSpecularMaterial.NORMALSCALE, value);
  8075. }
  8076. get _Parallax() {
  8077. return this._shaderValues.getNumber(PBRSpecularMaterial.PARALLAXSCALE);
  8078. }
  8079. set _Parallax(value) {
  8080. this._shaderValues.setNumber(PBRSpecularMaterial.PARALLAXSCALE, value);
  8081. }
  8082. get _OcclusionStrength() {
  8083. return this._shaderValues.getNumber(PBRSpecularMaterial.OCCLUSIONSTRENGTH);
  8084. }
  8085. set _OcclusionStrength(value) {
  8086. this._shaderValues.setNumber(PBRSpecularMaterial.OCCLUSIONSTRENGTH, value);
  8087. }
  8088. get _EmissionColorR() {
  8089. return this._emissionColor.x;
  8090. }
  8091. set _EmissionColorR(value) {
  8092. this._emissionColor.x = value;
  8093. this.emissionColor = this._emissionColor;
  8094. }
  8095. get _EmissionColorG() {
  8096. return this._emissionColor.y;
  8097. }
  8098. set _EmissionColorG(value) {
  8099. this._emissionColor.y = value;
  8100. this.emissionColor = this._emissionColor;
  8101. }
  8102. get _EmissionColorB() {
  8103. return this._emissionColor.z;
  8104. }
  8105. set _EmissionColorB(value) {
  8106. this._emissionColor.z = value;
  8107. this.emissionColor = this._emissionColor;
  8108. }
  8109. get _EmissionColorA() {
  8110. return this._emissionColor.w;
  8111. }
  8112. set _EmissionColorA(value) {
  8113. this._emissionColor.w = value;
  8114. this.emissionColor = this._emissionColor;
  8115. }
  8116. get _MainTex_STX() {
  8117. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET).x;
  8118. }
  8119. set _MainTex_STX(x) {
  8120. var tilOff = this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8121. tilOff.x = x;
  8122. this.tilingOffset = tilOff;
  8123. }
  8124. get _MainTex_STY() {
  8125. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET).y;
  8126. }
  8127. set _MainTex_STY(y) {
  8128. var tilOff = this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8129. tilOff.y = y;
  8130. this.tilingOffset = tilOff;
  8131. }
  8132. get _MainTex_STZ() {
  8133. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET).z;
  8134. }
  8135. set _MainTex_STZ(z) {
  8136. var tilOff = this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8137. tilOff.z = z;
  8138. this.tilingOffset = tilOff;
  8139. }
  8140. get _MainTex_STW() {
  8141. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET).w;
  8142. }
  8143. set _MainTex_STW(w) {
  8144. var tilOff = this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8145. tilOff.w = w;
  8146. this.tilingOffset = tilOff;
  8147. }
  8148. get _Cutoff() {
  8149. return this.alphaTestValue;
  8150. }
  8151. set _Cutoff(value) {
  8152. this.alphaTestValue = value;
  8153. }
  8154. get albedoColorR() {
  8155. return this._ColorR;
  8156. }
  8157. set albedoColorR(value) {
  8158. this._ColorR = value;
  8159. }
  8160. get albedoColorG() {
  8161. return this._ColorG;
  8162. }
  8163. set albedoColorG(value) {
  8164. this._ColorG = value;
  8165. }
  8166. get albedoColorB() {
  8167. return this._ColorB;
  8168. }
  8169. set albedoColorB(value) {
  8170. this._ColorB = value;
  8171. }
  8172. get albedoColorA() {
  8173. return this._ColorA;
  8174. }
  8175. set albedoColorA(value) {
  8176. this._ColorA = value;
  8177. }
  8178. get albedoColor() {
  8179. return this._albedoColor;
  8180. }
  8181. set albedoColor(value) {
  8182. this._albedoColor = value;
  8183. this._shaderValues.setVector(PBRSpecularMaterial.ALBEDOCOLOR, value);
  8184. }
  8185. get albedoTexture() {
  8186. return this._shaderValues.getTexture(PBRSpecularMaterial.ALBEDOTEXTURE);
  8187. }
  8188. set albedoTexture(value) {
  8189. if (value) {
  8190. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  8191. }
  8192. else {
  8193. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  8194. }
  8195. this._shaderValues.setTexture(PBRSpecularMaterial.ALBEDOTEXTURE, value);
  8196. }
  8197. get normalTexture() {
  8198. return this._shaderValues.getTexture(PBRSpecularMaterial.NORMALTEXTURE);
  8199. }
  8200. set normalTexture(value) {
  8201. if (value) {
  8202. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE);
  8203. }
  8204. else {
  8205. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE);
  8206. }
  8207. this._shaderValues.setTexture(PBRSpecularMaterial.NORMALTEXTURE, value);
  8208. }
  8209. get normalTextureScale() {
  8210. return this._BumpScale;
  8211. }
  8212. set normalTextureScale(value) {
  8213. this._BumpScale = value;
  8214. }
  8215. get parallaxTexture() {
  8216. return this._shaderValues.getTexture(PBRSpecularMaterial.PARALLAXTEXTURE);
  8217. }
  8218. set parallaxTexture(value) {
  8219. if (value) {
  8220. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  8221. }
  8222. else {
  8223. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  8224. }
  8225. this._shaderValues.setTexture(PBRSpecularMaterial.PARALLAXTEXTURE, value);
  8226. }
  8227. get parallaxTextureScale() {
  8228. return this._Parallax;
  8229. }
  8230. set parallaxTextureScale(value) {
  8231. this._Parallax = Math.max(0.005, Math.min(0.08, value));
  8232. }
  8233. get occlusionTexture() {
  8234. return this._shaderValues.getTexture(PBRSpecularMaterial.OCCLUSIONTEXTURE);
  8235. }
  8236. set occlusionTexture(value) {
  8237. if (value) {
  8238. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  8239. }
  8240. else {
  8241. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  8242. }
  8243. this._shaderValues.setTexture(PBRSpecularMaterial.OCCLUSIONTEXTURE, value);
  8244. }
  8245. get occlusionTextureStrength() {
  8246. return this._OcclusionStrength;
  8247. }
  8248. set occlusionTextureStrength(value) {
  8249. this._OcclusionStrength = Math.max(0.0, Math.min(1.0, value));
  8250. }
  8251. get specularTexture() {
  8252. return this._shaderValues.getTexture(PBRSpecularMaterial.SPECULARTEXTURE);
  8253. }
  8254. set specularTexture(value) {
  8255. if (value) {
  8256. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE);
  8257. }
  8258. else {
  8259. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE);
  8260. }
  8261. this._shaderValues.setTexture(PBRSpecularMaterial.SPECULARTEXTURE, value);
  8262. }
  8263. get specularColorR() {
  8264. return this._SpecColorR;
  8265. }
  8266. set specularColorR(value) {
  8267. this._SpecColorR = value;
  8268. }
  8269. get specularColorG() {
  8270. return this._SpecColorG;
  8271. }
  8272. set specularColorG(value) {
  8273. this._SpecColorG = value;
  8274. }
  8275. get specularColorB() {
  8276. return this._SpecColorB;
  8277. }
  8278. set specularColorB(value) {
  8279. this._SpecColorB = value;
  8280. }
  8281. get specularColorA() {
  8282. return this._SpecColorA;
  8283. }
  8284. set specularColorA(value) {
  8285. this._SpecColorA = value;
  8286. }
  8287. get specularColor() {
  8288. return this._shaderValues.getVector(PBRSpecularMaterial.SPECULARCOLOR);
  8289. }
  8290. set specularColor(value) {
  8291. this._shaderValues.setVector(PBRSpecularMaterial.SPECULARCOLOR, value);
  8292. }
  8293. get smoothness() {
  8294. return this._Glossiness;
  8295. }
  8296. set smoothness(value) {
  8297. this._Glossiness = Math.max(0.0, Math.min(1.0, value));
  8298. }
  8299. get smoothnessTextureScale() {
  8300. return this._GlossMapScale;
  8301. }
  8302. set smoothnessTextureScale(value) {
  8303. this._GlossMapScale = Math.max(0.0, Math.min(1.0, value));
  8304. }
  8305. get smoothnessSource() {
  8306. return this._shaderValues.getInt(PBRSpecularMaterial.SMOOTHNESSSOURCE);
  8307. }
  8308. set smoothnessSource(value) {
  8309. if (value) {
  8310. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  8311. this._shaderValues.setInt(PBRSpecularMaterial.SMOOTHNESSSOURCE, 1);
  8312. }
  8313. else {
  8314. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  8315. this._shaderValues.setInt(PBRSpecularMaterial.SMOOTHNESSSOURCE, 0);
  8316. }
  8317. }
  8318. get enableEmission() {
  8319. return this._shaderValues.getBool(PBRSpecularMaterial.ENABLEEMISSION);
  8320. }
  8321. set enableEmission(value) {
  8322. if (value)
  8323. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_EMISSION);
  8324. else {
  8325. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_EMISSION);
  8326. }
  8327. this._shaderValues.setBool(PBRSpecularMaterial.ENABLEEMISSION, value);
  8328. }
  8329. get emissionColor() {
  8330. return this._shaderValues.getVector(PBRSpecularMaterial.EMISSIONCOLOR);
  8331. }
  8332. set emissionColor(value) {
  8333. this._shaderValues.setVector(PBRSpecularMaterial.EMISSIONCOLOR, value);
  8334. }
  8335. get emissionTexture() {
  8336. return this._shaderValues.getTexture(PBRSpecularMaterial.EMISSIONTEXTURE);
  8337. }
  8338. set emissionTexture(value) {
  8339. if (value)
  8340. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  8341. else
  8342. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  8343. this._shaderValues.setTexture(PBRSpecularMaterial.EMISSIONTEXTURE, value);
  8344. }
  8345. get enableReflection() {
  8346. return this._shaderValues.getBool(PBRSpecularMaterial.ENABLEREFLECT);
  8347. }
  8348. set enableReflection(value) {
  8349. this._shaderValues.setBool(PBRSpecularMaterial.ENABLEREFLECT, true);
  8350. if (value)
  8351. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8352. else
  8353. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8354. }
  8355. get tilingOffsetX() {
  8356. return this._MainTex_STX;
  8357. }
  8358. set tilingOffsetX(x) {
  8359. this._MainTex_STX = x;
  8360. }
  8361. get tilingOffsetY() {
  8362. return this._MainTex_STY;
  8363. }
  8364. set tilingOffsetY(y) {
  8365. this._MainTex_STY = y;
  8366. }
  8367. get tilingOffsetZ() {
  8368. return this._MainTex_STZ;
  8369. }
  8370. set tilingOffsetZ(z) {
  8371. this._MainTex_STZ = z;
  8372. }
  8373. get tilingOffsetW() {
  8374. return this._MainTex_STW;
  8375. }
  8376. set tilingOffsetW(w) {
  8377. this._MainTex_STW = w;
  8378. }
  8379. get tilingOffset() {
  8380. return this._shaderValues.getVector(PBRSpecularMaterial.TILINGOFFSET);
  8381. }
  8382. set tilingOffset(value) {
  8383. if (value) {
  8384. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  8385. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET);
  8386. else
  8387. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET);
  8388. }
  8389. else {
  8390. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET);
  8391. }
  8392. this._shaderValues.setVector(PBRSpecularMaterial.TILINGOFFSET, value);
  8393. }
  8394. set renderMode(value) {
  8395. switch (value) {
  8396. case PBRSpecularMaterial.RENDERMODE_OPAQUE:
  8397. this.alphaTest = false;
  8398. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  8399. this.depthWrite = true;
  8400. this.cull = RenderState.CULL_BACK;
  8401. this.blend = RenderState.BLEND_DISABLE;
  8402. this.depthTest = RenderState.DEPTHTEST_LESS;
  8403. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8404. break;
  8405. case PBRSpecularMaterial.RENDERMODE_CUTOUT:
  8406. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  8407. this.alphaTest = true;
  8408. this.depthWrite = true;
  8409. this.cull = RenderState.CULL_BACK;
  8410. this.blend = RenderState.BLEND_DISABLE;
  8411. this.depthTest = RenderState.DEPTHTEST_LESS;
  8412. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8413. break;
  8414. case PBRSpecularMaterial.RENDERMODE_FADE:
  8415. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  8416. this.alphaTest = false;
  8417. this.depthWrite = false;
  8418. this.cull = RenderState.CULL_BACK;
  8419. this.blend = RenderState.BLEND_ENABLE_ALL;
  8420. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  8421. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  8422. this.depthTest = RenderState.DEPTHTEST_LESS;
  8423. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8424. break;
  8425. case PBRSpecularMaterial.RENDERMODE_TRANSPARENT:
  8426. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  8427. this.alphaTest = false;
  8428. this.depthWrite = false;
  8429. this.cull = RenderState.CULL_BACK;
  8430. this.blend = RenderState.BLEND_ENABLE_ALL;
  8431. this.blendSrc = RenderState.BLENDPARAM_ONE;
  8432. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  8433. this.depthTest = RenderState.DEPTHTEST_LESS;
  8434. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8435. break;
  8436. default:
  8437. throw new Error("PBRSpecularMaterial : renderMode value error.");
  8438. }
  8439. }
  8440. get depthWrite() {
  8441. return this._shaderValues.getBool(PBRSpecularMaterial.DEPTH_WRITE);
  8442. }
  8443. set depthWrite(value) {
  8444. this._shaderValues.setBool(PBRSpecularMaterial.DEPTH_WRITE, value);
  8445. }
  8446. get cull() {
  8447. return this._shaderValues.getInt(PBRSpecularMaterial.CULL);
  8448. }
  8449. set cull(value) {
  8450. this._shaderValues.setInt(PBRSpecularMaterial.CULL, value);
  8451. }
  8452. get blend() {
  8453. return this._shaderValues.getInt(PBRSpecularMaterial.BLEND);
  8454. }
  8455. set blend(value) {
  8456. this._shaderValues.setInt(PBRSpecularMaterial.BLEND, value);
  8457. }
  8458. get blendSrc() {
  8459. return this._shaderValues.getInt(PBRSpecularMaterial.BLEND_SRC);
  8460. }
  8461. set blendSrc(value) {
  8462. this._shaderValues.setInt(PBRSpecularMaterial.BLEND_SRC, value);
  8463. }
  8464. get blendDst() {
  8465. return this._shaderValues.getInt(PBRSpecularMaterial.BLEND_DST);
  8466. }
  8467. set blendDst(value) {
  8468. this._shaderValues.setInt(PBRSpecularMaterial.BLEND_DST, value);
  8469. }
  8470. get depthTest() {
  8471. return this._shaderValues.getInt(PBRSpecularMaterial.DEPTH_TEST);
  8472. }
  8473. set depthTest(value) {
  8474. this._shaderValues.setInt(PBRSpecularMaterial.DEPTH_TEST, value);
  8475. }
  8476. clone() {
  8477. var dest = new PBRSpecularMaterial();
  8478. this.cloneTo(dest);
  8479. return dest;
  8480. }
  8481. cloneTo(destObject) {
  8482. super.cloneTo(destObject);
  8483. var destMaterial = destObject;
  8484. this._albedoColor.cloneTo(destMaterial._albedoColor);
  8485. this._specularColor.cloneTo(destMaterial._specularColor);
  8486. this._emissionColor.cloneTo(destMaterial._emissionColor);
  8487. }
  8488. }
  8489. PBRSpecularMaterial.SmoothnessSource_SpecularTexture_Alpha = 0;
  8490. PBRSpecularMaterial.SmoothnessSource_AlbedoTexture_Alpha = 1;
  8491. PBRSpecularMaterial.RENDERMODE_OPAQUE = 0;
  8492. PBRSpecularMaterial.RENDERMODE_CUTOUT = 1;
  8493. PBRSpecularMaterial.RENDERMODE_FADE = 2;
  8494. PBRSpecularMaterial.RENDERMODE_TRANSPARENT = 3;
  8495. PBRSpecularMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  8496. PBRSpecularMaterial.SPECULARTEXTURE = Shader3D.propertyNameToID("u_SpecularTexture");
  8497. PBRSpecularMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  8498. PBRSpecularMaterial.PARALLAXTEXTURE = Shader3D.propertyNameToID("u_ParallaxTexture");
  8499. PBRSpecularMaterial.OCCLUSIONTEXTURE = Shader3D.propertyNameToID("u_OcclusionTexture");
  8500. PBRSpecularMaterial.EMISSIONTEXTURE = Shader3D.propertyNameToID("u_EmissionTexture");
  8501. PBRSpecularMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  8502. PBRSpecularMaterial.SPECULARCOLOR = Shader3D.propertyNameToID("u_SpecularColor");
  8503. PBRSpecularMaterial.EMISSIONCOLOR = Shader3D.propertyNameToID("u_EmissionColor");
  8504. PBRSpecularMaterial.SMOOTHNESS = Shader3D.propertyNameToID("u_smoothness");
  8505. PBRSpecularMaterial.SMOOTHNESSSCALE = Shader3D.propertyNameToID("u_smoothnessScale");
  8506. PBRSpecularMaterial.SMOOTHNESSSOURCE = -1;
  8507. PBRSpecularMaterial.OCCLUSIONSTRENGTH = Shader3D.propertyNameToID("u_occlusionStrength");
  8508. PBRSpecularMaterial.NORMALSCALE = Shader3D.propertyNameToID("u_normalScale");
  8509. PBRSpecularMaterial.PARALLAXSCALE = Shader3D.propertyNameToID("u_parallaxScale");
  8510. PBRSpecularMaterial.ENABLEEMISSION = -1;
  8511. PBRSpecularMaterial.ENABLEREFLECT = -1;
  8512. PBRSpecularMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  8513. PBRSpecularMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  8514. PBRSpecularMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  8515. PBRSpecularMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  8516. PBRSpecularMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  8517. PBRSpecularMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  8518. PBRSpecularMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  8519. class PBRStandardMaterial extends Material {
  8520. constructor() {
  8521. super();
  8522. this.setShaderName("PBRStandard");
  8523. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  8524. this._shaderValues.setVector(PBRStandardMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  8525. this._emissionColor = new Vector4(0.0, 0.0, 0.0, 0.0);
  8526. this._shaderValues.setVector(PBRStandardMaterial.EMISSIONCOLOR, new Vector4(0.0, 0.0, 0.0, 0.0));
  8527. this._shaderValues.setNumber(PBRStandardMaterial.METALLIC, 0.0);
  8528. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESS, 0.5);
  8529. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESSSCALE, 1.0);
  8530. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESSSOURCE, 0);
  8531. this._shaderValues.setNumber(PBRStandardMaterial.OCCLUSIONSTRENGTH, 1.0);
  8532. this._shaderValues.setNumber(PBRStandardMaterial.NORMALSCALE, 1.0);
  8533. this._shaderValues.setNumber(PBRStandardMaterial.PARALLAXSCALE, 0.001);
  8534. this._shaderValues.setBool(PBRStandardMaterial.ENABLEEMISSION, false);
  8535. this._shaderValues.setBool(PBRStandardMaterial.ENABLEREFLECT, true);
  8536. this._shaderValues.setNumber(Material.ALPHATESTVALUE, 0.5);
  8537. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8538. this.renderMode = PBRStandardMaterial.RENDERMODE_OPAQUE;
  8539. }
  8540. static __initDefine__() {
  8541. PBRStandardMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  8542. PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE = Shader3D.getDefineByName("METALLICGLOSSTEXTURE");
  8543. PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA = Shader3D.getDefineByName("SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA");
  8544. PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  8545. PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE = Shader3D.getDefineByName("PARALLAXTEXTURE");
  8546. PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE = Shader3D.getDefineByName("OCCLUSIONTEXTURE");
  8547. PBRStandardMaterial.SHADERDEFINE_EMISSION = Shader3D.getDefineByName("EMISSION");
  8548. PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE = Shader3D.getDefineByName("EMISSIONTEXTURE");
  8549. PBRStandardMaterial.SHADERDEFINE_REFLECTMAP = Shader3D.getDefineByName("REFLECTMAP");
  8550. PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  8551. PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY = Shader3D.getDefineByName("ALPHAPREMULTIPLY");
  8552. }
  8553. get _ColorR() {
  8554. return this._albedoColor.x;
  8555. }
  8556. set _ColorR(value) {
  8557. this._albedoColor.x = value;
  8558. this.albedoColor = this._albedoColor;
  8559. }
  8560. get _ColorG() {
  8561. return this._albedoColor.y;
  8562. }
  8563. set _ColorG(value) {
  8564. this._albedoColor.y = value;
  8565. this.albedoColor = this._albedoColor;
  8566. }
  8567. get _ColorB() {
  8568. return this._albedoColor.z;
  8569. }
  8570. set _ColorB(value) {
  8571. this._albedoColor.z = value;
  8572. this.albedoColor = this._albedoColor;
  8573. }
  8574. get _ColorA() {
  8575. return this._albedoColor.w;
  8576. }
  8577. set _ColorA(value) {
  8578. this._albedoColor.w = value;
  8579. this.albedoColor = this._albedoColor;
  8580. }
  8581. get _Metallic() {
  8582. return this._shaderValues.getNumber(PBRStandardMaterial.METALLIC);
  8583. }
  8584. set _Metallic(value) {
  8585. this._shaderValues.setNumber(PBRStandardMaterial.METALLIC, value);
  8586. }
  8587. get _Glossiness() {
  8588. return this._shaderValues.getNumber(PBRStandardMaterial.SMOOTHNESS);
  8589. }
  8590. set _Glossiness(value) {
  8591. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESS, value);
  8592. }
  8593. get _GlossMapScale() {
  8594. return this._shaderValues.getNumber(PBRStandardMaterial.SMOOTHNESSSCALE);
  8595. }
  8596. set _GlossMapScale(value) {
  8597. this._shaderValues.setNumber(PBRStandardMaterial.SMOOTHNESSSCALE, value);
  8598. }
  8599. get _BumpScale() {
  8600. return this._shaderValues.getNumber(PBRStandardMaterial.NORMALSCALE);
  8601. }
  8602. set _BumpScale(value) {
  8603. this._shaderValues.setNumber(PBRStandardMaterial.NORMALSCALE, value);
  8604. }
  8605. get _Parallax() {
  8606. return this._shaderValues.getNumber(PBRStandardMaterial.PARALLAXSCALE);
  8607. }
  8608. set _Parallax(value) {
  8609. this._shaderValues.setNumber(PBRStandardMaterial.PARALLAXSCALE, value);
  8610. }
  8611. get _OcclusionStrength() {
  8612. return this._shaderValues.getNumber(PBRStandardMaterial.OCCLUSIONSTRENGTH);
  8613. }
  8614. set _OcclusionStrength(value) {
  8615. this._shaderValues.setNumber(PBRStandardMaterial.OCCLUSIONSTRENGTH, value);
  8616. }
  8617. get _EmissionColorR() {
  8618. return this._emissionColor.x;
  8619. }
  8620. set _EmissionColorR(value) {
  8621. this._emissionColor.x = value;
  8622. this.emissionColor = this._emissionColor;
  8623. }
  8624. get _EmissionColorG() {
  8625. return this._emissionColor.y;
  8626. }
  8627. set _EmissionColorG(value) {
  8628. this._emissionColor.y = value;
  8629. this.emissionColor = this._emissionColor;
  8630. }
  8631. get _EmissionColorB() {
  8632. return this._emissionColor.z;
  8633. }
  8634. set _EmissionColorB(value) {
  8635. this._emissionColor.z = value;
  8636. this.emissionColor = this._emissionColor;
  8637. }
  8638. get _EmissionColorA() {
  8639. return this._emissionColor.w;
  8640. }
  8641. set _EmissionColorA(value) {
  8642. this._emissionColor.w = value;
  8643. this.emissionColor = this._emissionColor;
  8644. }
  8645. get _MainTex_STX() {
  8646. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET).x;
  8647. }
  8648. set _MainTex_STX(x) {
  8649. var tilOff = this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8650. tilOff.x = x;
  8651. this.tilingOffset = tilOff;
  8652. }
  8653. get _MainTex_STY() {
  8654. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET).y;
  8655. }
  8656. set _MainTex_STY(y) {
  8657. var tilOff = this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8658. tilOff.y = y;
  8659. this.tilingOffset = tilOff;
  8660. }
  8661. get _MainTex_STZ() {
  8662. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET).z;
  8663. }
  8664. set _MainTex_STZ(z) {
  8665. var tilOff = this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8666. tilOff.z = z;
  8667. this.tilingOffset = tilOff;
  8668. }
  8669. get _MainTex_STW() {
  8670. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET).w;
  8671. }
  8672. set _MainTex_STW(w) {
  8673. var tilOff = this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8674. tilOff.w = w;
  8675. this.tilingOffset = tilOff;
  8676. }
  8677. get _Cutoff() {
  8678. return this.alphaTestValue;
  8679. }
  8680. set _Cutoff(value) {
  8681. this.alphaTestValue = value;
  8682. }
  8683. get albedoColorR() {
  8684. return this._ColorR;
  8685. }
  8686. set albedoColorR(value) {
  8687. this._ColorR = value;
  8688. }
  8689. get albedoColorG() {
  8690. return this._ColorG;
  8691. }
  8692. set albedoColorG(value) {
  8693. this._ColorG = value;
  8694. }
  8695. get albedoColorB() {
  8696. return this._ColorB;
  8697. }
  8698. set albedoColorB(value) {
  8699. this._ColorB = value;
  8700. }
  8701. get albedoColorA() {
  8702. return this._ColorA;
  8703. }
  8704. set albedoColorA(value) {
  8705. this._ColorA = value;
  8706. }
  8707. get albedoColor() {
  8708. return this._albedoColor;
  8709. }
  8710. set albedoColor(value) {
  8711. this._albedoColor = value;
  8712. this._shaderValues.setVector(PBRStandardMaterial.ALBEDOCOLOR, value);
  8713. }
  8714. get albedoTexture() {
  8715. return this._shaderValues.getTexture(PBRStandardMaterial.ALBEDOTEXTURE);
  8716. }
  8717. set albedoTexture(value) {
  8718. if (value) {
  8719. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  8720. }
  8721. else {
  8722. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  8723. }
  8724. this._shaderValues.setTexture(PBRStandardMaterial.ALBEDOTEXTURE, value);
  8725. }
  8726. get normalTexture() {
  8727. return this._shaderValues.getTexture(PBRStandardMaterial.NORMALTEXTURE);
  8728. }
  8729. set normalTexture(value) {
  8730. if (value) {
  8731. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE);
  8732. }
  8733. else {
  8734. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE);
  8735. }
  8736. this._shaderValues.setTexture(PBRStandardMaterial.NORMALTEXTURE, value);
  8737. }
  8738. get normalTextureScale() {
  8739. return this._BumpScale;
  8740. }
  8741. set normalTextureScale(value) {
  8742. this._BumpScale = value;
  8743. }
  8744. get parallaxTexture() {
  8745. return this._shaderValues.getTexture(PBRStandardMaterial.PARALLAXTEXTURE);
  8746. }
  8747. set parallaxTexture(value) {
  8748. if (value) {
  8749. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  8750. }
  8751. else {
  8752. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  8753. }
  8754. this._shaderValues.setTexture(PBRStandardMaterial.PARALLAXTEXTURE, value);
  8755. }
  8756. get parallaxTextureScale() {
  8757. return this._Parallax;
  8758. }
  8759. set parallaxTextureScale(value) {
  8760. this._Parallax = Math.max(0.005, Math.min(0.08, value));
  8761. }
  8762. get occlusionTexture() {
  8763. return this._shaderValues.getTexture(PBRStandardMaterial.OCCLUSIONTEXTURE);
  8764. }
  8765. set occlusionTexture(value) {
  8766. if (value) {
  8767. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  8768. }
  8769. else {
  8770. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  8771. }
  8772. this._shaderValues.setTexture(PBRStandardMaterial.OCCLUSIONTEXTURE, value);
  8773. }
  8774. get occlusionTextureStrength() {
  8775. return this._OcclusionStrength;
  8776. }
  8777. set occlusionTextureStrength(value) {
  8778. this._OcclusionStrength = Math.max(0.0, Math.min(1.0, value));
  8779. }
  8780. get metallicGlossTexture() {
  8781. return this._shaderValues.getTexture(PBRStandardMaterial.METALLICGLOSSTEXTURE);
  8782. }
  8783. set metallicGlossTexture(value) {
  8784. if (value) {
  8785. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE);
  8786. }
  8787. else {
  8788. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE);
  8789. }
  8790. this._shaderValues.setTexture(PBRStandardMaterial.METALLICGLOSSTEXTURE, value);
  8791. }
  8792. get metallic() {
  8793. return this._Metallic;
  8794. }
  8795. set metallic(value) {
  8796. this._Metallic = Math.max(0.0, Math.min(1.0, value));
  8797. }
  8798. get smoothness() {
  8799. return this._Glossiness;
  8800. }
  8801. set smoothness(value) {
  8802. this._Glossiness = Math.max(0.0, Math.min(1.0, value));
  8803. }
  8804. get smoothnessTextureScale() {
  8805. return this._GlossMapScale;
  8806. }
  8807. set smoothnessTextureScale(value) {
  8808. this._GlossMapScale = Math.max(0.0, Math.min(1.0, value));
  8809. }
  8810. get smoothnessSource() {
  8811. return this._shaderValues.getInt(PBRStandardMaterial.SMOOTHNESSSOURCE);
  8812. }
  8813. set smoothnessSource(value) {
  8814. if (value) {
  8815. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  8816. this._shaderValues.setInt(PBRStandardMaterial.SMOOTHNESSSOURCE, 1);
  8817. }
  8818. else {
  8819. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  8820. this._shaderValues.setInt(PBRStandardMaterial.SMOOTHNESSSOURCE, 0);
  8821. }
  8822. }
  8823. get enableEmission() {
  8824. return this._shaderValues.getBool(PBRStandardMaterial.ENABLEEMISSION);
  8825. }
  8826. set enableEmission(value) {
  8827. if (value) {
  8828. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_EMISSION);
  8829. }
  8830. else {
  8831. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_EMISSION);
  8832. }
  8833. this._shaderValues.setBool(PBRStandardMaterial.ENABLEEMISSION, value);
  8834. }
  8835. get emissionColorR() {
  8836. return this._EmissionColorR;
  8837. }
  8838. set emissionColorR(value) {
  8839. this._EmissionColorR = value;
  8840. }
  8841. get emissionColorG() {
  8842. return this._EmissionColorG;
  8843. }
  8844. set emissionColorG(value) {
  8845. this._EmissionColorG = value;
  8846. }
  8847. get emissionColorB() {
  8848. return this._EmissionColorB;
  8849. }
  8850. set emissionColorB(value) {
  8851. this._EmissionColorB = value;
  8852. }
  8853. get emissionColorA() {
  8854. return this._EmissionColorA;
  8855. }
  8856. set emissionColorA(value) {
  8857. this._EmissionColorA = value;
  8858. }
  8859. get emissionColor() {
  8860. return this._shaderValues.getVector(PBRStandardMaterial.EMISSIONCOLOR);
  8861. }
  8862. set emissionColor(value) {
  8863. this._shaderValues.setVector(PBRStandardMaterial.EMISSIONCOLOR, value);
  8864. }
  8865. get emissionTexture() {
  8866. return this._shaderValues.getTexture(PBRStandardMaterial.EMISSIONTEXTURE);
  8867. }
  8868. set emissionTexture(value) {
  8869. if (value) {
  8870. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  8871. }
  8872. else {
  8873. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  8874. }
  8875. this._shaderValues.setTexture(PBRStandardMaterial.EMISSIONTEXTURE, value);
  8876. }
  8877. get enableReflection() {
  8878. return this._shaderValues.getBool(PBRStandardMaterial.ENABLEREFLECT);
  8879. }
  8880. set enableReflection(value) {
  8881. this._shaderValues.setBool(PBRStandardMaterial.ENABLEREFLECT, true);
  8882. if (value) {
  8883. this._disablePublicDefineDatas.remove(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8884. }
  8885. else {
  8886. this._disablePublicDefineDatas.add(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  8887. }
  8888. }
  8889. get tilingOffsetX() {
  8890. return this._MainTex_STX;
  8891. }
  8892. set tilingOffsetX(x) {
  8893. this._MainTex_STX = x;
  8894. }
  8895. get tilingOffsetY() {
  8896. return this._MainTex_STY;
  8897. }
  8898. set tilingOffsetY(y) {
  8899. this._MainTex_STY = y;
  8900. }
  8901. get tilingOffsetZ() {
  8902. return this._MainTex_STZ;
  8903. }
  8904. set tilingOffsetZ(z) {
  8905. this._MainTex_STZ = z;
  8906. }
  8907. get tilingOffsetW() {
  8908. return this._MainTex_STW;
  8909. }
  8910. set tilingOffsetW(w) {
  8911. this._MainTex_STW = w;
  8912. }
  8913. get tilingOffset() {
  8914. return this._shaderValues.getVector(PBRStandardMaterial.TILINGOFFSET);
  8915. }
  8916. set tilingOffset(value) {
  8917. if (value) {
  8918. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0) {
  8919. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET);
  8920. }
  8921. else {
  8922. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET);
  8923. }
  8924. }
  8925. else {
  8926. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET);
  8927. }
  8928. this._shaderValues.setVector(PBRStandardMaterial.TILINGOFFSET, value);
  8929. }
  8930. set renderMode(value) {
  8931. switch (value) {
  8932. case PBRStandardMaterial.RENDERMODE_OPAQUE:
  8933. this.alphaTest = false;
  8934. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  8935. this.depthWrite = true;
  8936. this.cull = RenderState.CULL_BACK;
  8937. this.blend = RenderState.BLEND_DISABLE;
  8938. this.depthTest = RenderState.DEPTHTEST_LESS;
  8939. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8940. break;
  8941. case PBRStandardMaterial.RENDERMODE_CUTOUT:
  8942. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  8943. this.alphaTest = true;
  8944. this.depthWrite = true;
  8945. this.cull = RenderState.CULL_BACK;
  8946. this.blend = RenderState.BLEND_DISABLE;
  8947. this.depthTest = RenderState.DEPTHTEST_LESS;
  8948. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8949. break;
  8950. case PBRStandardMaterial.RENDERMODE_FADE:
  8951. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  8952. this.alphaTest = false;
  8953. this.depthWrite = false;
  8954. this.cull = RenderState.CULL_BACK;
  8955. this.blend = RenderState.BLEND_ENABLE_ALL;
  8956. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  8957. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  8958. this.depthTest = RenderState.DEPTHTEST_LESS;
  8959. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8960. break;
  8961. break;
  8962. case PBRStandardMaterial.RENDERMODE_TRANSPARENT:
  8963. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  8964. this.alphaTest = false;
  8965. this.depthWrite = false;
  8966. this.cull = RenderState.CULL_BACK;
  8967. this.blend = RenderState.BLEND_ENABLE_ALL;
  8968. this.blendSrc = RenderState.BLENDPARAM_ONE;
  8969. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  8970. this.depthTest = RenderState.DEPTHTEST_LESS;
  8971. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_ALPHAPREMULTIPLY);
  8972. break;
  8973. default:
  8974. throw new Error("PBRSpecularMaterial : renderMode value error.");
  8975. }
  8976. }
  8977. get depthWrite() {
  8978. return this._shaderValues.getBool(PBRStandardMaterial.DEPTH_WRITE);
  8979. }
  8980. set depthWrite(value) {
  8981. this._shaderValues.setBool(PBRStandardMaterial.DEPTH_WRITE, value);
  8982. }
  8983. get cull() {
  8984. return this._shaderValues.getInt(PBRStandardMaterial.CULL);
  8985. }
  8986. set cull(value) {
  8987. this._shaderValues.setInt(PBRStandardMaterial.CULL, value);
  8988. }
  8989. get blend() {
  8990. return this._shaderValues.getInt(PBRStandardMaterial.BLEND);
  8991. }
  8992. set blend(value) {
  8993. this._shaderValues.setInt(PBRStandardMaterial.BLEND, value);
  8994. }
  8995. get blendSrc() {
  8996. return this._shaderValues.getInt(PBRStandardMaterial.BLEND_SRC);
  8997. }
  8998. set blendSrc(value) {
  8999. this._shaderValues.setInt(PBRStandardMaterial.BLEND_SRC, value);
  9000. }
  9001. get blendDst() {
  9002. return this._shaderValues.getInt(PBRStandardMaterial.BLEND_DST);
  9003. }
  9004. set blendDst(value) {
  9005. this._shaderValues.setInt(PBRStandardMaterial.BLEND_DST, value);
  9006. }
  9007. get depthTest() {
  9008. return this._shaderValues.getInt(PBRStandardMaterial.DEPTH_TEST);
  9009. }
  9010. set depthTest(value) {
  9011. this._shaderValues.setInt(PBRStandardMaterial.DEPTH_TEST, value);
  9012. }
  9013. clone() {
  9014. var dest = new PBRStandardMaterial();
  9015. this.cloneTo(dest);
  9016. return dest;
  9017. }
  9018. cloneTo(destObject) {
  9019. super.cloneTo(destObject);
  9020. var destMaterial = destObject;
  9021. this._albedoColor.cloneTo(destMaterial._albedoColor);
  9022. this._emissionColor.cloneTo(destMaterial._emissionColor);
  9023. }
  9024. }
  9025. PBRStandardMaterial.SmoothnessSource_MetallicGlossTexture_Alpha = 0;
  9026. PBRStandardMaterial.SmoothnessSource_AlbedoTexture_Alpha = 1;
  9027. PBRStandardMaterial.RENDERMODE_OPAQUE = 0;
  9028. PBRStandardMaterial.RENDERMODE_CUTOUT = 1;
  9029. PBRStandardMaterial.RENDERMODE_FADE = 2;
  9030. PBRStandardMaterial.RENDERMODE_TRANSPARENT = 3;
  9031. PBRStandardMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  9032. PBRStandardMaterial.METALLICGLOSSTEXTURE = Shader3D.propertyNameToID("u_MetallicGlossTexture");
  9033. PBRStandardMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  9034. PBRStandardMaterial.PARALLAXTEXTURE = Shader3D.propertyNameToID("u_ParallaxTexture");
  9035. PBRStandardMaterial.OCCLUSIONTEXTURE = Shader3D.propertyNameToID("u_OcclusionTexture");
  9036. PBRStandardMaterial.EMISSIONTEXTURE = Shader3D.propertyNameToID("u_EmissionTexture");
  9037. PBRStandardMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  9038. PBRStandardMaterial.EMISSIONCOLOR = Shader3D.propertyNameToID("u_EmissionColor");
  9039. PBRStandardMaterial.METALLIC = Shader3D.propertyNameToID("u_metallic");
  9040. PBRStandardMaterial.SMOOTHNESS = Shader3D.propertyNameToID("u_smoothness");
  9041. PBRStandardMaterial.SMOOTHNESSSCALE = Shader3D.propertyNameToID("u_smoothnessScale");
  9042. PBRStandardMaterial.SMOOTHNESSSOURCE = -1;
  9043. PBRStandardMaterial.OCCLUSIONSTRENGTH = Shader3D.propertyNameToID("u_occlusionStrength");
  9044. PBRStandardMaterial.NORMALSCALE = Shader3D.propertyNameToID("u_normalScale");
  9045. PBRStandardMaterial.PARALLAXSCALE = Shader3D.propertyNameToID("u_parallaxScale");
  9046. PBRStandardMaterial.ENABLEEMISSION = -1;
  9047. PBRStandardMaterial.ENABLEREFLECT = -1;
  9048. PBRStandardMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  9049. PBRStandardMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  9050. PBRStandardMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  9051. PBRStandardMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  9052. PBRStandardMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  9053. PBRStandardMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  9054. PBRStandardMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  9055. class SkyBoxMaterial extends Material {
  9056. constructor() {
  9057. super();
  9058. this.setShaderName("SkyBox");
  9059. this.tintColor = new Vector4(0.5, 0.5, 0.5, 0.5);
  9060. this.exposure = 1.0;
  9061. this.rotation = 0;
  9062. }
  9063. static __initDefine__() {
  9064. }
  9065. get tintColor() {
  9066. return this._shaderValues.getVector(SkyBoxMaterial.TINTCOLOR);
  9067. }
  9068. set tintColor(value) {
  9069. this._shaderValues.setVector(SkyBoxMaterial.TINTCOLOR, value);
  9070. }
  9071. get exposure() {
  9072. return this._shaderValues.getNumber(SkyBoxMaterial.EXPOSURE);
  9073. }
  9074. set exposure(value) {
  9075. this._shaderValues.setNumber(SkyBoxMaterial.EXPOSURE, value);
  9076. }
  9077. get rotation() {
  9078. return this._shaderValues.getNumber(SkyBoxMaterial.ROTATION);
  9079. }
  9080. set rotation(value) {
  9081. this._shaderValues.setNumber(SkyBoxMaterial.ROTATION, value);
  9082. }
  9083. get textureCube() {
  9084. return this._shaderValues.getTexture(SkyBoxMaterial.TEXTURECUBE);
  9085. }
  9086. set textureCube(value) {
  9087. this._shaderValues.setTexture(SkyBoxMaterial.TEXTURECUBE, value);
  9088. }
  9089. clone() {
  9090. var dest = new SkyBoxMaterial();
  9091. this.cloneTo(dest);
  9092. return dest;
  9093. }
  9094. }
  9095. SkyBoxMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_TintColor");
  9096. SkyBoxMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  9097. SkyBoxMaterial.ROTATION = Shader3D.propertyNameToID("u_Rotation");
  9098. SkyBoxMaterial.TEXTURECUBE = Shader3D.propertyNameToID("u_CubeTexture");
  9099. class SkyProceduralMaterial extends Material {
  9100. constructor() {
  9101. super();
  9102. this.setShaderName("SkyBoxProcedural");
  9103. this.sunDisk = SkyProceduralMaterial.SUN_HIGH_QUALITY;
  9104. this.sunSize = 0.04;
  9105. this.sunSizeConvergence = 5;
  9106. this.atmosphereThickness = 1.0;
  9107. this.skyTint = new Vector4(0.5, 0.5, 0.5, 1.0);
  9108. this.groundTint = new Vector4(0.369, 0.349, 0.341, 1.0);
  9109. this.exposure = 1.3;
  9110. }
  9111. static __initDefine__() {
  9112. SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY = Shader3D.getDefineByName("SUN_HIGH_QUALITY");
  9113. SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE = Shader3D.getDefineByName("SUN_SIMPLE");
  9114. }
  9115. get sunDisk() {
  9116. return this._sunDisk;
  9117. }
  9118. set sunDisk(value) {
  9119. switch (value) {
  9120. case SkyProceduralMaterial.SUN_HIGH_QUALITY:
  9121. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  9122. this._shaderValues.addDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  9123. break;
  9124. case SkyProceduralMaterial.SUN_SIMPLE:
  9125. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  9126. this._shaderValues.addDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  9127. break;
  9128. case SkyProceduralMaterial.SUN_NODE:
  9129. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  9130. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  9131. break;
  9132. default:
  9133. throw "SkyBoxProceduralMaterial: unknown sun value.";
  9134. }
  9135. this._sunDisk = value;
  9136. }
  9137. get sunSize() {
  9138. return this._shaderValues.getNumber(SkyProceduralMaterial.SUNSIZE);
  9139. }
  9140. set sunSize(value) {
  9141. value = Math.min(Math.max(0.0, value), 1.0);
  9142. this._shaderValues.setNumber(SkyProceduralMaterial.SUNSIZE, value);
  9143. }
  9144. get sunSizeConvergence() {
  9145. return this._shaderValues.getNumber(SkyProceduralMaterial.SUNSIZECONVERGENCE);
  9146. }
  9147. set sunSizeConvergence(value) {
  9148. value = Math.min(Math.max(0.0, value), 20.0);
  9149. this._shaderValues.setNumber(SkyProceduralMaterial.SUNSIZECONVERGENCE, value);
  9150. }
  9151. get atmosphereThickness() {
  9152. return this._shaderValues.getNumber(SkyProceduralMaterial.ATMOSPHERETHICKNESS);
  9153. }
  9154. set atmosphereThickness(value) {
  9155. value = Math.min(Math.max(0.0, value), 5.0);
  9156. this._shaderValues.setNumber(SkyProceduralMaterial.ATMOSPHERETHICKNESS, value);
  9157. }
  9158. get skyTint() {
  9159. return this._shaderValues.getVector(SkyProceduralMaterial.SKYTINT);
  9160. }
  9161. set skyTint(value) {
  9162. this._shaderValues.setVector(SkyProceduralMaterial.SKYTINT, value);
  9163. }
  9164. get groundTint() {
  9165. return this._shaderValues.getVector(SkyProceduralMaterial.GROUNDTINT);
  9166. }
  9167. set groundTint(value) {
  9168. this._shaderValues.setVector(SkyProceduralMaterial.GROUNDTINT, value);
  9169. }
  9170. get exposure() {
  9171. return this._shaderValues.getNumber(SkyProceduralMaterial.EXPOSURE);
  9172. }
  9173. set exposure(value) {
  9174. value = Math.min(Math.max(0.0, value), 8.0);
  9175. this._shaderValues.setNumber(SkyProceduralMaterial.EXPOSURE, value);
  9176. }
  9177. clone() {
  9178. var dest = new SkyProceduralMaterial();
  9179. this.cloneTo(dest);
  9180. return dest;
  9181. }
  9182. }
  9183. SkyProceduralMaterial.SUN_NODE = 0;
  9184. SkyProceduralMaterial.SUN_SIMPLE = 1;
  9185. SkyProceduralMaterial.SUN_HIGH_QUALITY = 2;
  9186. SkyProceduralMaterial.SUNSIZE = Shader3D.propertyNameToID("u_SunSize");
  9187. SkyProceduralMaterial.SUNSIZECONVERGENCE = Shader3D.propertyNameToID("u_SunSizeConvergence");
  9188. SkyProceduralMaterial.ATMOSPHERETHICKNESS = Shader3D.propertyNameToID("u_AtmosphereThickness");
  9189. SkyProceduralMaterial.SKYTINT = Shader3D.propertyNameToID("u_SkyTint");
  9190. SkyProceduralMaterial.GROUNDTINT = Shader3D.propertyNameToID("u_GroundTint");
  9191. SkyProceduralMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  9192. class UnlitMaterial extends Material {
  9193. constructor() {
  9194. super();
  9195. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  9196. this._albedoIntensity = 1.0;
  9197. this._enableVertexColor = false;
  9198. this.setShaderName("Unlit");
  9199. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  9200. this.renderMode = UnlitMaterial.RENDERMODE_OPAQUE;
  9201. }
  9202. static __initDefine__() {
  9203. UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  9204. UnlitMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  9205. UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR = Shader3D.getDefineByName("ENABLEVERTEXCOLOR");
  9206. }
  9207. get _ColorR() {
  9208. return this._albedoColor.x;
  9209. }
  9210. set _ColorR(value) {
  9211. this._albedoColor.x = value;
  9212. this.albedoColor = this._albedoColor;
  9213. }
  9214. get _ColorG() {
  9215. return this._albedoColor.y;
  9216. }
  9217. set _ColorG(value) {
  9218. this._albedoColor.y = value;
  9219. this.albedoColor = this._albedoColor;
  9220. }
  9221. get _ColorB() {
  9222. return this._albedoColor.z;
  9223. }
  9224. set _ColorB(value) {
  9225. this._albedoColor.z = value;
  9226. this.albedoColor = this._albedoColor;
  9227. }
  9228. get _ColorA() {
  9229. return this._albedoColor.w;
  9230. }
  9231. set _ColorA(value) {
  9232. this._albedoColor.w = value;
  9233. this.albedoColor = this._albedoColor;
  9234. }
  9235. get _AlbedoIntensity() {
  9236. return this._albedoIntensity;
  9237. }
  9238. set _AlbedoIntensity(value) {
  9239. if (this._albedoIntensity !== value) {
  9240. var finalAlbedo = this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  9241. Vector4.scale(this._albedoColor, value, finalAlbedo);
  9242. this._albedoIntensity = value;
  9243. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, finalAlbedo);
  9244. }
  9245. }
  9246. get _MainTex_STX() {
  9247. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).x;
  9248. }
  9249. set _MainTex_STX(x) {
  9250. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9251. tilOff.x = x;
  9252. this.tilingOffset = tilOff;
  9253. }
  9254. get _MainTex_STY() {
  9255. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).y;
  9256. }
  9257. set _MainTex_STY(y) {
  9258. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9259. tilOff.y = y;
  9260. this.tilingOffset = tilOff;
  9261. }
  9262. get _MainTex_STZ() {
  9263. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).z;
  9264. }
  9265. set _MainTex_STZ(z) {
  9266. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9267. tilOff.z = z;
  9268. this.tilingOffset = tilOff;
  9269. }
  9270. get _MainTex_STW() {
  9271. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).w;
  9272. }
  9273. set _MainTex_STW(w) {
  9274. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9275. tilOff.w = w;
  9276. this.tilingOffset = tilOff;
  9277. }
  9278. get _Cutoff() {
  9279. return this.alphaTestValue;
  9280. }
  9281. set _Cutoff(value) {
  9282. this.alphaTestValue = value;
  9283. }
  9284. get albedoColorR() {
  9285. return this._ColorR;
  9286. }
  9287. set albedoColorR(value) {
  9288. this._ColorR = value;
  9289. }
  9290. get albedoColorG() {
  9291. return this._ColorG;
  9292. }
  9293. set albedoColorG(value) {
  9294. this._ColorG = value;
  9295. }
  9296. get albedoColorB() {
  9297. return this._ColorB;
  9298. }
  9299. set albedoColorB(value) {
  9300. this._ColorB = value;
  9301. }
  9302. get albedoColorA() {
  9303. return this._ColorA;
  9304. }
  9305. set albedoColorA(value) {
  9306. this._ColorA = value;
  9307. }
  9308. get albedoColor() {
  9309. return this._albedoColor;
  9310. }
  9311. set albedoColor(value) {
  9312. var finalAlbedo = this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  9313. Vector4.scale(value, this._albedoIntensity, finalAlbedo);
  9314. this._albedoColor = value;
  9315. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, finalAlbedo);
  9316. }
  9317. get albedoIntensity() {
  9318. return this._albedoIntensity;
  9319. }
  9320. set albedoIntensity(value) {
  9321. this._AlbedoIntensity = value;
  9322. }
  9323. get albedoTexture() {
  9324. return this._shaderValues.getTexture(UnlitMaterial.ALBEDOTEXTURE);
  9325. }
  9326. set albedoTexture(value) {
  9327. if (value)
  9328. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  9329. else
  9330. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  9331. this._shaderValues.setTexture(UnlitMaterial.ALBEDOTEXTURE, value);
  9332. }
  9333. get tilingOffsetX() {
  9334. return this._MainTex_STX;
  9335. }
  9336. set tilingOffsetX(x) {
  9337. this._MainTex_STX = x;
  9338. }
  9339. get tilingOffsetY() {
  9340. return this._MainTex_STY;
  9341. }
  9342. set tilingOffsetY(y) {
  9343. this._MainTex_STY = y;
  9344. }
  9345. get tilingOffsetZ() {
  9346. return this._MainTex_STZ;
  9347. }
  9348. set tilingOffsetZ(z) {
  9349. this._MainTex_STZ = z;
  9350. }
  9351. get tilingOffsetW() {
  9352. return this._MainTex_STW;
  9353. }
  9354. set tilingOffsetW(w) {
  9355. this._MainTex_STW = w;
  9356. }
  9357. get tilingOffset() {
  9358. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  9359. }
  9360. set tilingOffset(value) {
  9361. if (value) {
  9362. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  9363. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  9364. else
  9365. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  9366. }
  9367. else {
  9368. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  9369. }
  9370. this._shaderValues.setVector(UnlitMaterial.TILINGOFFSET, value);
  9371. }
  9372. get enableVertexColor() {
  9373. return this._enableVertexColor;
  9374. }
  9375. set enableVertexColor(value) {
  9376. this._enableVertexColor = value;
  9377. if (value)
  9378. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  9379. else
  9380. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  9381. }
  9382. set renderMode(value) {
  9383. switch (value) {
  9384. case UnlitMaterial.RENDERMODE_OPAQUE:
  9385. this.alphaTest = false;
  9386. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  9387. this.depthWrite = true;
  9388. this.cull = RenderState.CULL_BACK;
  9389. this.blend = RenderState.BLEND_DISABLE;
  9390. this.depthTest = RenderState.DEPTHTEST_LESS;
  9391. break;
  9392. case UnlitMaterial.RENDERMODE_CUTOUT:
  9393. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  9394. this.alphaTest = true;
  9395. this.depthWrite = true;
  9396. this.cull = RenderState.CULL_BACK;
  9397. this.blend = RenderState.BLEND_DISABLE;
  9398. this.depthTest = RenderState.DEPTHTEST_LESS;
  9399. break;
  9400. case UnlitMaterial.RENDERMODE_TRANSPARENT:
  9401. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  9402. this.alphaTest = false;
  9403. this.depthWrite = false;
  9404. this.cull = RenderState.CULL_BACK;
  9405. this.blend = RenderState.BLEND_ENABLE_ALL;
  9406. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  9407. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  9408. this.depthTest = RenderState.DEPTHTEST_LESS;
  9409. break;
  9410. default:
  9411. throw new Error("UnlitMaterial : renderMode value error.");
  9412. }
  9413. }
  9414. get depthWrite() {
  9415. return this._shaderValues.getBool(UnlitMaterial.DEPTH_WRITE);
  9416. }
  9417. set depthWrite(value) {
  9418. this._shaderValues.setBool(UnlitMaterial.DEPTH_WRITE, value);
  9419. }
  9420. get cull() {
  9421. return this._shaderValues.getInt(UnlitMaterial.CULL);
  9422. }
  9423. set cull(value) {
  9424. this._shaderValues.setInt(UnlitMaterial.CULL, value);
  9425. }
  9426. get blend() {
  9427. return this._shaderValues.getInt(UnlitMaterial.BLEND);
  9428. }
  9429. set blend(value) {
  9430. this._shaderValues.setInt(UnlitMaterial.BLEND, value);
  9431. }
  9432. get blendSrc() {
  9433. return this._shaderValues.getInt(UnlitMaterial.BLEND_SRC);
  9434. }
  9435. set blendSrc(value) {
  9436. this._shaderValues.setInt(UnlitMaterial.BLEND_SRC, value);
  9437. }
  9438. get blendDst() {
  9439. return this._shaderValues.getInt(UnlitMaterial.BLEND_DST);
  9440. }
  9441. set blendDst(value) {
  9442. this._shaderValues.setInt(UnlitMaterial.BLEND_DST, value);
  9443. }
  9444. get depthTest() {
  9445. return this._shaderValues.getInt(UnlitMaterial.DEPTH_TEST);
  9446. }
  9447. set depthTest(value) {
  9448. this._shaderValues.setInt(UnlitMaterial.DEPTH_TEST, value);
  9449. }
  9450. clone() {
  9451. var dest = new UnlitMaterial();
  9452. this.cloneTo(dest);
  9453. return dest;
  9454. }
  9455. }
  9456. UnlitMaterial.RENDERMODE_OPAQUE = 0;
  9457. UnlitMaterial.RENDERMODE_CUTOUT = 1;
  9458. UnlitMaterial.RENDERMODE_TRANSPARENT = 2;
  9459. UnlitMaterial.RENDERMODE_ADDTIVE = 3;
  9460. UnlitMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  9461. UnlitMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  9462. UnlitMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  9463. UnlitMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  9464. UnlitMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  9465. UnlitMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  9466. UnlitMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  9467. UnlitMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  9468. UnlitMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  9469. class WaterPrimaryMaterial extends Material {
  9470. constructor() {
  9471. super();
  9472. this.setShaderName("WaterPrimary");
  9473. this._shaderValues.setVector(WaterPrimaryMaterial.HORIZONCOLOR, new Vector4(0.172, 0.463, 0.435, 0));
  9474. this._shaderValues.setNumber(WaterPrimaryMaterial.WAVESCALE, 0.15);
  9475. this._shaderValues.setVector(WaterPrimaryMaterial.WAVESPEED, new Vector4(19, 9, -16, -7));
  9476. }
  9477. static __initDefine__() {
  9478. WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  9479. WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  9480. }
  9481. get horizonColor() {
  9482. return this._shaderValues.getVector(WaterPrimaryMaterial.HORIZONCOLOR);
  9483. }
  9484. set horizonColor(value) {
  9485. this._shaderValues.setVector(WaterPrimaryMaterial.HORIZONCOLOR, value);
  9486. }
  9487. get mainTexture() {
  9488. return this._shaderValues.getTexture(WaterPrimaryMaterial.MAINTEXTURE);
  9489. }
  9490. set mainTexture(value) {
  9491. if (value)
  9492. this._shaderValues.addDefine(WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE);
  9493. else
  9494. this._shaderValues.removeDefine(WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE);
  9495. this._shaderValues.setTexture(WaterPrimaryMaterial.MAINTEXTURE, value);
  9496. }
  9497. get normalTexture() {
  9498. return this._shaderValues.getTexture(WaterPrimaryMaterial.NORMALTEXTURE);
  9499. }
  9500. set normalTexture(value) {
  9501. if (value)
  9502. this._shaderValues.addDefine(WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE);
  9503. else
  9504. this._shaderValues.removeDefine(WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE);
  9505. this._shaderValues.setTexture(WaterPrimaryMaterial.NORMALTEXTURE, value);
  9506. }
  9507. get waveScale() {
  9508. return this._shaderValues.getNumber(WaterPrimaryMaterial.WAVESCALE);
  9509. }
  9510. set waveScale(value) {
  9511. this._shaderValues.setNumber(WaterPrimaryMaterial.WAVESCALE, value);
  9512. }
  9513. get waveSpeed() {
  9514. return this._shaderValues.getVector(WaterPrimaryMaterial.WAVESPEED);
  9515. }
  9516. set waveSpeed(value) {
  9517. this._shaderValues.setVector(WaterPrimaryMaterial.WAVESPEED, value);
  9518. }
  9519. clone() {
  9520. var dest = new WaterPrimaryMaterial();
  9521. this.cloneTo(dest);
  9522. return dest;
  9523. }
  9524. }
  9525. WaterPrimaryMaterial.HORIZONCOLOR = Shader3D.propertyNameToID("u_HorizonColor");
  9526. WaterPrimaryMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_MainTexture");
  9527. WaterPrimaryMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  9528. WaterPrimaryMaterial.WAVESCALE = Shader3D.propertyNameToID("u_WaveScale");
  9529. WaterPrimaryMaterial.WAVESPEED = Shader3D.propertyNameToID("u_WaveSpeed");
  9530. class Color {
  9531. constructor(r = 1, g = 1, b = 1, a = 1) {
  9532. this.r = r;
  9533. this.g = g;
  9534. this.b = b;
  9535. this.a = a;
  9536. }
  9537. static gammaToLinearSpace(value) {
  9538. if (value <= 0.04045)
  9539. return value / 12.92;
  9540. else if (value < 1.0)
  9541. return Math.pow((value + 0.055) / 1.055, 2.4);
  9542. else
  9543. return Math.pow(value, 2.4);
  9544. }
  9545. static linearToGammaSpace(value) {
  9546. if (value <= 0.0)
  9547. return 0.0;
  9548. else if (value <= 0.0031308)
  9549. return 12.92 * value;
  9550. else if (value <= 1.0)
  9551. return 1.055 * Math.pow(value, 0.41666) - 0.055;
  9552. else
  9553. return Math.pow(value, 0.41666);
  9554. }
  9555. toLinear(out) {
  9556. out.r = Color.gammaToLinearSpace(this.r);
  9557. out.g = Color.gammaToLinearSpace(this.g);
  9558. out.b = Color.gammaToLinearSpace(this.b);
  9559. }
  9560. toGamma(out) {
  9561. out.r = Color.linearToGammaSpace(this.r);
  9562. out.g = Color.linearToGammaSpace(this.g);
  9563. out.b = Color.linearToGammaSpace(this.b);
  9564. }
  9565. cloneTo(destObject) {
  9566. var destColor = destObject;
  9567. destColor.r = this.r;
  9568. destColor.g = this.g;
  9569. destColor.b = this.b;
  9570. destColor.a = this.a;
  9571. }
  9572. clone() {
  9573. var dest = new Color();
  9574. this.cloneTo(dest);
  9575. return dest;
  9576. }
  9577. forNativeElement() {
  9578. }
  9579. }
  9580. Color.RED = new Color(1, 0, 0, 1);
  9581. Color.GREEN = new Color(0, 1, 0, 1);
  9582. Color.BLUE = new Color(0, 0, 1, 1);
  9583. Color.CYAN = new Color(0, 1, 1, 1);
  9584. Color.YELLOW = new Color(1, 0.92, 0.016, 1);
  9585. Color.MAGENTA = new Color(1, 0, 1, 1);
  9586. Color.GRAY = new Color(0.5, 0.5, 0.5, 1);
  9587. Color.WHITE = new Color(1, 1, 1, 1);
  9588. Color.BLACK = new Color(0, 0, 0, 1);
  9589. class DynamicBatchManager {
  9590. constructor() {
  9591. this._batchRenderElementPool = [];
  9592. }
  9593. static _registerManager(manager) {
  9594. DynamicBatchManager._managers.push(manager);
  9595. }
  9596. _clear() {
  9597. this._batchRenderElementPoolIndex = 0;
  9598. }
  9599. _getBatchRenderElementFromPool() {
  9600. throw "StaticBatch:must override this function.";
  9601. }
  9602. dispose() {
  9603. }
  9604. }
  9605. DynamicBatchManager._managers = [];
  9606. class Transform3D extends Laya.EventDispatcher {
  9607. constructor(owner) {
  9608. super();
  9609. this._localPosition = new Vector3(0, 0, 0);
  9610. this._localRotation = new Quaternion(0, 0, 0, 1);
  9611. this._localScale = new Vector3(1, 1, 1);
  9612. this._localRotationEuler = new Vector3(0, 0, 0);
  9613. this._localMatrix = new Matrix4x4();
  9614. this._position = new Vector3(0, 0, 0);
  9615. this._rotation = new Quaternion(0, 0, 0, 1);
  9616. this._scale = new Vector3(1, 1, 1);
  9617. this._rotationEuler = new Vector3(0, 0, 0);
  9618. this._worldMatrix = new Matrix4x4();
  9619. this._children = null;
  9620. this._parent = null;
  9621. this._dummy = null;
  9622. this._transformFlag = 0;
  9623. this._owner = owner;
  9624. this._children = [];
  9625. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION | Transform3D.TRANSFORM_LOCALEULER | Transform3D.TRANSFORM_LOCALMATRIX, false);
  9626. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER | Transform3D.TRANSFORM_WORLDSCALE | Transform3D.TRANSFORM_WORLDMATRIX, true);
  9627. }
  9628. get _isFrontFaceInvert() {
  9629. var scale = this.getWorldLossyScale();
  9630. var isInvert = scale.x < 0;
  9631. (scale.y < 0) && (isInvert = !isInvert);
  9632. (scale.z < 0) && (isInvert = !isInvert);
  9633. return isInvert;
  9634. }
  9635. get owner() {
  9636. return this._owner;
  9637. }
  9638. get worldNeedUpdate() {
  9639. return this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX);
  9640. }
  9641. get localPositionX() {
  9642. return this._localPosition.x;
  9643. }
  9644. set localPositionX(x) {
  9645. this._localPosition.x = x;
  9646. this.localPosition = this._localPosition;
  9647. }
  9648. get localPositionY() {
  9649. return this._localPosition.y;
  9650. }
  9651. set localPositionY(y) {
  9652. this._localPosition.y = y;
  9653. this.localPosition = this._localPosition;
  9654. }
  9655. get localPositionZ() {
  9656. return this._localPosition.z;
  9657. }
  9658. set localPositionZ(z) {
  9659. this._localPosition.z = z;
  9660. this.localPosition = this._localPosition;
  9661. }
  9662. get localPosition() {
  9663. return this._localPosition;
  9664. }
  9665. set localPosition(value) {
  9666. if (this._localPosition !== value)
  9667. value.cloneTo(this._localPosition);
  9668. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, true);
  9669. this._onWorldPositionTransform();
  9670. }
  9671. get localRotationX() {
  9672. return this.localRotation.x;
  9673. }
  9674. set localRotationX(x) {
  9675. this._localRotation.x = x;
  9676. this.localRotation = this._localRotation;
  9677. }
  9678. get localRotationY() {
  9679. return this.localRotation.y;
  9680. }
  9681. set localRotationY(y) {
  9682. this._localRotation.y = y;
  9683. this.localRotation = this._localRotation;
  9684. }
  9685. get localRotationZ() {
  9686. return this.localRotation.z;
  9687. }
  9688. set localRotationZ(z) {
  9689. this._localRotation.z = z;
  9690. this.localRotation = this._localRotation;
  9691. }
  9692. get localRotationW() {
  9693. return this.localRotation.w;
  9694. }
  9695. set localRotationW(w) {
  9696. this._localRotation.w = w;
  9697. this.localRotation = this._localRotation;
  9698. }
  9699. get localRotation() {
  9700. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION)) {
  9701. var eulerE = this._localRotationEuler;
  9702. Quaternion.createFromYawPitchRoll(eulerE.y / Transform3D._angleToRandin, eulerE.x / Transform3D._angleToRandin, eulerE.z / Transform3D._angleToRandin, this._localRotation);
  9703. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION, false);
  9704. }
  9705. return this._localRotation;
  9706. }
  9707. set localRotation(value) {
  9708. if (this._localRotation !== value)
  9709. value.cloneTo(this._localRotation);
  9710. this._localRotation.normalize(this._localRotation);
  9711. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER | Transform3D.TRANSFORM_LOCALMATRIX, true);
  9712. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION, false);
  9713. this._onWorldRotationTransform();
  9714. }
  9715. get localScaleX() {
  9716. return this._localScale.x;
  9717. }
  9718. set localScaleX(value) {
  9719. this._localScale.x = value;
  9720. this.localScale = this._localScale;
  9721. }
  9722. get localScaleY() {
  9723. return this._localScale.y;
  9724. }
  9725. set localScaleY(value) {
  9726. this._localScale.y = value;
  9727. this.localScale = this._localScale;
  9728. }
  9729. get localScaleZ() {
  9730. return this._localScale.z;
  9731. }
  9732. set localScaleZ(value) {
  9733. this._localScale.z = value;
  9734. this.localScale = this._localScale;
  9735. }
  9736. get localScale() {
  9737. return this._localScale;
  9738. }
  9739. set localScale(value) {
  9740. if (this._localScale !== value)
  9741. value.cloneTo(this._localScale);
  9742. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, true);
  9743. this._onWorldScaleTransform();
  9744. }
  9745. get localRotationEulerX() {
  9746. return this.localRotationEuler.x;
  9747. }
  9748. set localRotationEulerX(value) {
  9749. this._localRotationEuler.x = value;
  9750. this.localRotationEuler = this._localRotationEuler;
  9751. }
  9752. get localRotationEulerY() {
  9753. return this.localRotationEuler.y;
  9754. }
  9755. set localRotationEulerY(value) {
  9756. this._localRotationEuler.y = value;
  9757. this.localRotationEuler = this._localRotationEuler;
  9758. }
  9759. get localRotationEulerZ() {
  9760. return this.localRotationEuler.z;
  9761. }
  9762. set localRotationEulerZ(value) {
  9763. this._localRotationEuler.z = value;
  9764. this.localRotationEuler = this._localRotationEuler;
  9765. }
  9766. get localRotationEuler() {
  9767. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALEULER)) {
  9768. this._localRotation.getYawPitchRoll(Transform3D._tempVector30);
  9769. var euler = Transform3D._tempVector30;
  9770. var localRotationEuler = this._localRotationEuler;
  9771. localRotationEuler.x = euler.y * Transform3D._angleToRandin;
  9772. localRotationEuler.y = euler.x * Transform3D._angleToRandin;
  9773. localRotationEuler.z = euler.z * Transform3D._angleToRandin;
  9774. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, false);
  9775. }
  9776. return this._localRotationEuler;
  9777. }
  9778. set localRotationEuler(value) {
  9779. if (this._localRotationEuler !== value)
  9780. value.cloneTo(this._localRotationEuler);
  9781. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, false);
  9782. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION | Transform3D.TRANSFORM_LOCALMATRIX, true);
  9783. this._onWorldRotationTransform();
  9784. }
  9785. get localMatrix() {
  9786. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX)) {
  9787. Matrix4x4.createAffineTransformation(this._localPosition, this.localRotation, this._localScale, this._localMatrix);
  9788. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, false);
  9789. }
  9790. return this._localMatrix;
  9791. }
  9792. set localMatrix(value) {
  9793. if (this._localMatrix !== value)
  9794. value.cloneTo(this._localMatrix);
  9795. this._localMatrix.decomposeTransRotScale(this._localPosition, this._localRotation, this._localScale);
  9796. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, true);
  9797. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, false);
  9798. this._onWorldTransform();
  9799. }
  9800. get position() {
  9801. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  9802. if (this._parent != null) {
  9803. var worldMatE = this.worldMatrix.elements;
  9804. this._position.x = worldMatE[12];
  9805. this._position.y = worldMatE[13];
  9806. this._position.z = worldMatE[14];
  9807. }
  9808. else {
  9809. this._localPosition.cloneTo(this._position);
  9810. }
  9811. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  9812. }
  9813. return this._position;
  9814. }
  9815. set position(value) {
  9816. if (this._parent != null) {
  9817. var parentInvMat = Transform3D._tempMatrix0;
  9818. this._parent.worldMatrix.invert(parentInvMat);
  9819. Vector3.transformCoordinate(value, parentInvMat, this._localPosition);
  9820. }
  9821. else {
  9822. value.cloneTo(this._localPosition);
  9823. }
  9824. this.localPosition = this._localPosition;
  9825. if (this._position !== value)
  9826. value.cloneTo(this._position);
  9827. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  9828. }
  9829. get rotation() {
  9830. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) {
  9831. if (this._parent != null)
  9832. Quaternion.multiply(this._parent.rotation, this.localRotation, this._rotation);
  9833. else
  9834. this.localRotation.cloneTo(this._rotation);
  9835. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  9836. }
  9837. return this._rotation;
  9838. }
  9839. set rotation(value) {
  9840. if (this._parent != null) {
  9841. this._parent.rotation.invert(Transform3D._tempQuaternion0);
  9842. Quaternion.multiply(Transform3D._tempQuaternion0, value, this._localRotation);
  9843. }
  9844. else {
  9845. value.cloneTo(this._localRotation);
  9846. }
  9847. this.localRotation = this._localRotation;
  9848. if (value !== this._rotation)
  9849. value.cloneTo(this._rotation);
  9850. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  9851. }
  9852. get rotationEuler() {
  9853. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  9854. this.rotation.getYawPitchRoll(Transform3D._tempVector30);
  9855. var eulerE = Transform3D._tempVector30;
  9856. var rotationEulerE = this._rotationEuler;
  9857. rotationEulerE.x = eulerE.y * Transform3D._angleToRandin;
  9858. rotationEulerE.y = eulerE.x * Transform3D._angleToRandin;
  9859. rotationEulerE.z = eulerE.z * Transform3D._angleToRandin;
  9860. this._setTransformFlag(Transform3D.TRANSFORM_WORLDEULER, false);
  9861. }
  9862. return this._rotationEuler;
  9863. }
  9864. set rotationEuler(value) {
  9865. Quaternion.createFromYawPitchRoll(value.y / Transform3D._angleToRandin, value.x / Transform3D._angleToRandin, value.z / Transform3D._angleToRandin, this._rotation);
  9866. this.rotation = this._rotation;
  9867. if (this._rotationEuler !== value)
  9868. value.cloneTo(this._rotationEuler);
  9869. this._setTransformFlag(Transform3D.TRANSFORM_WORLDEULER, false);
  9870. }
  9871. get worldMatrix() {
  9872. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX)) {
  9873. if (this._parent != null)
  9874. Matrix4x4.multiply(this._parent.worldMatrix, this.localMatrix, this._worldMatrix);
  9875. else
  9876. this.localMatrix.cloneTo(this._worldMatrix);
  9877. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX, false);
  9878. }
  9879. return this._worldMatrix;
  9880. }
  9881. set worldMatrix(value) {
  9882. if (this._parent === null) {
  9883. value.cloneTo(this._localMatrix);
  9884. }
  9885. else {
  9886. this._parent.worldMatrix.invert(this._localMatrix);
  9887. Matrix4x4.multiply(this._localMatrix, value, this._localMatrix);
  9888. }
  9889. this.localMatrix = this._localMatrix;
  9890. if (this._worldMatrix !== value)
  9891. value.cloneTo(this._worldMatrix);
  9892. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX, false);
  9893. }
  9894. _getScaleMatrix() {
  9895. var invRotation = Transform3D._tempQuaternion0;
  9896. var invRotationMat = Transform3D._tempMatrix3x30;
  9897. var worldRotScaMat = Transform3D._tempMatrix3x31;
  9898. var scaMat = Transform3D._tempMatrix3x32;
  9899. Matrix3x3.createFromMatrix4x4(this.worldMatrix, worldRotScaMat);
  9900. this.rotation.invert(invRotation);
  9901. Matrix3x3.createRotationQuaternion(invRotation, invRotationMat);
  9902. Matrix3x3.multiply(invRotationMat, worldRotScaMat, scaMat);
  9903. return scaMat;
  9904. }
  9905. _setTransformFlag(type, value) {
  9906. if (value)
  9907. this._transformFlag |= type;
  9908. else
  9909. this._transformFlag &= ~type;
  9910. }
  9911. _getTransformFlag(type) {
  9912. return (this._transformFlag & type) != 0;
  9913. }
  9914. _setParent(value) {
  9915. if (this._parent !== value) {
  9916. if (this._parent) {
  9917. var parentChilds = this._parent._children;
  9918. var index = parentChilds.indexOf(this);
  9919. parentChilds.splice(index, 1);
  9920. }
  9921. if (value) {
  9922. value._children.push(this);
  9923. (value) && (this._onWorldTransform());
  9924. }
  9925. this._parent = value;
  9926. }
  9927. }
  9928. _onWorldPositionRotationTransform() {
  9929. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  9930. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER, true);
  9931. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9932. for (var i = 0, n = this._children.length; i < n; i++)
  9933. this._children[i]._onWorldPositionRotationTransform();
  9934. }
  9935. }
  9936. _onWorldPositionScaleTransform() {
  9937. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  9938. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDSCALE, true);
  9939. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9940. for (var i = 0, n = this._children.length; i < n; i++)
  9941. this._children[i]._onWorldPositionScaleTransform();
  9942. }
  9943. }
  9944. _onWorldPositionTransform() {
  9945. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  9946. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION, true);
  9947. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9948. for (var i = 0, n = this._children.length; i < n; i++)
  9949. this._children[i]._onWorldPositionTransform();
  9950. }
  9951. }
  9952. _onWorldRotationTransform() {
  9953. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  9954. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER, true);
  9955. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9956. for (var i = 0, n = this._children.length; i < n; i++)
  9957. this._children[i]._onWorldPositionRotationTransform();
  9958. }
  9959. }
  9960. _onWorldScaleTransform() {
  9961. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  9962. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDSCALE, true);
  9963. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9964. for (var i = 0, n = this._children.length; i < n; i++)
  9965. this._children[i]._onWorldPositionScaleTransform();
  9966. }
  9967. }
  9968. _onWorldTransform() {
  9969. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  9970. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER | Transform3D.TRANSFORM_WORLDSCALE, true);
  9971. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  9972. for (var i = 0, n = this._children.length; i < n; i++)
  9973. this._children[i]._onWorldTransform();
  9974. }
  9975. }
  9976. translate(translation, isLocal = true) {
  9977. if (isLocal) {
  9978. Matrix4x4.createFromQuaternion(this.localRotation, Transform3D._tempMatrix0);
  9979. Vector3.transformCoordinate(translation, Transform3D._tempMatrix0, Transform3D._tempVector30);
  9980. Vector3.add(this.localPosition, Transform3D._tempVector30, this._localPosition);
  9981. this.localPosition = this._localPosition;
  9982. }
  9983. else {
  9984. Vector3.add(this.position, translation, this._position);
  9985. this.position = this._position;
  9986. }
  9987. }
  9988. rotate(rotation, isLocal = true, isRadian = true) {
  9989. var rot;
  9990. if (isRadian) {
  9991. rot = rotation;
  9992. }
  9993. else {
  9994. Vector3.scale(rotation, Math.PI / 180.0, Transform3D._tempVector30);
  9995. rot = Transform3D._tempVector30;
  9996. }
  9997. Quaternion.createFromYawPitchRoll(rot.y, rot.x, rot.z, Transform3D._tempQuaternion0);
  9998. if (isLocal) {
  9999. Quaternion.multiply(this._localRotation, Transform3D._tempQuaternion0, this._localRotation);
  10000. this.localRotation = this._localRotation;
  10001. }
  10002. else {
  10003. Quaternion.multiply(Transform3D._tempQuaternion0, this.rotation, this._rotation);
  10004. this.rotation = this._rotation;
  10005. }
  10006. }
  10007. getForward(forward) {
  10008. var worldMatElem = this.worldMatrix.elements;
  10009. forward.x = -worldMatElem[8];
  10010. forward.y = -worldMatElem[9];
  10011. forward.z = -worldMatElem[10];
  10012. }
  10013. getUp(up) {
  10014. var worldMatElem = this.worldMatrix.elements;
  10015. up.x = worldMatElem[4];
  10016. up.y = worldMatElem[5];
  10017. up.z = worldMatElem[6];
  10018. }
  10019. getRight(right) {
  10020. var worldMatElem = this.worldMatrix.elements;
  10021. right.x = worldMatElem[0];
  10022. right.y = worldMatElem[1];
  10023. right.z = worldMatElem[2];
  10024. }
  10025. lookAt(target, up, isLocal = false) {
  10026. var eye;
  10027. if (isLocal) {
  10028. eye = this._localPosition;
  10029. if (Math.abs(eye.x - target.x) < MathUtils3D.zeroTolerance && Math.abs(eye.y - target.y) < MathUtils3D.zeroTolerance && Math.abs(eye.z - target.z) < MathUtils3D.zeroTolerance)
  10030. return;
  10031. Quaternion.lookAt(this._localPosition, target, up, this._localRotation);
  10032. this._localRotation.invert(this._localRotation);
  10033. this.localRotation = this._localRotation;
  10034. }
  10035. else {
  10036. var worldPosition = this.position;
  10037. eye = worldPosition;
  10038. if (Math.abs(eye.x - target.x) < MathUtils3D.zeroTolerance && Math.abs(eye.y - target.y) < MathUtils3D.zeroTolerance && Math.abs(eye.z - target.z) < MathUtils3D.zeroTolerance)
  10039. return;
  10040. Quaternion.lookAt(worldPosition, target, up, this._rotation);
  10041. this._rotation.invert(this._rotation);
  10042. this.rotation = this._rotation;
  10043. }
  10044. }
  10045. getWorldLossyScale() {
  10046. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  10047. if (this._parent !== null) {
  10048. var scaMatE = this._getScaleMatrix().elements;
  10049. this._scale.x = scaMatE[0];
  10050. this._scale.y = scaMatE[4];
  10051. this._scale.z = scaMatE[8];
  10052. }
  10053. else {
  10054. this._localScale.cloneTo(this._scale);
  10055. }
  10056. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  10057. }
  10058. return this._scale;
  10059. }
  10060. setWorldLossyScale(value) {
  10061. if (this._parent !== null) {
  10062. var scaleMat = Transform3D._tempMatrix3x33;
  10063. var localScaleMat = Transform3D._tempMatrix3x33;
  10064. var localScaleMatE = localScaleMat.elements;
  10065. var parInvScaleMat = this._parent._getScaleMatrix();
  10066. parInvScaleMat.invert(parInvScaleMat);
  10067. Matrix3x3.createFromScaling(value, scaleMat);
  10068. Matrix3x3.multiply(parInvScaleMat, scaleMat, localScaleMat);
  10069. this._localScale.x = localScaleMatE[0];
  10070. this._localScale.y = localScaleMatE[4];
  10071. this._localScale.z = localScaleMatE[8];
  10072. }
  10073. else {
  10074. value.cloneTo(this._localScale);
  10075. }
  10076. this.localScale = this._localScale;
  10077. if (this._scale !== value)
  10078. value.cloneTo(this._scale);
  10079. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  10080. }
  10081. get scale() {
  10082. console.warn("Transfrm3D: discard function,please use getWorldLossyScale instead.");
  10083. return this.getWorldLossyScale();
  10084. }
  10085. set scale(value) {
  10086. console.warn("Transfrm3D: discard function,please use setWorldLossyScale instead.");
  10087. this.setWorldLossyScale(value);
  10088. }
  10089. }
  10090. Transform3D._tempVector30 = new Vector3();
  10091. Transform3D._tempQuaternion0 = new Quaternion();
  10092. Transform3D._tempMatrix0 = new Matrix4x4();
  10093. Transform3D._tempMatrix3x30 = new Matrix3x3();
  10094. Transform3D._tempMatrix3x31 = new Matrix3x3();
  10095. Transform3D._tempMatrix3x32 = new Matrix3x3();
  10096. Transform3D._tempMatrix3x33 = new Matrix3x3();
  10097. Transform3D.TRANSFORM_LOCALQUATERNION = 0x01;
  10098. Transform3D.TRANSFORM_LOCALEULER = 0x02;
  10099. Transform3D.TRANSFORM_LOCALMATRIX = 0x04;
  10100. Transform3D.TRANSFORM_WORLDPOSITION = 0x08;
  10101. Transform3D.TRANSFORM_WORLDQUATERNION = 0x10;
  10102. Transform3D.TRANSFORM_WORLDSCALE = 0x20;
  10103. Transform3D.TRANSFORM_WORLDMATRIX = 0x40;
  10104. Transform3D.TRANSFORM_WORLDEULER = 0x80;
  10105. Transform3D._angleToRandin = 180 / Math.PI;
  10106. class Sprite3D extends Laya.Node {
  10107. constructor(name = null, isStatic = false) {
  10108. super();
  10109. this._needProcessCollisions = false;
  10110. this._needProcessTriggers = false;
  10111. this._id = ++Sprite3D._uniqueIDCounter;
  10112. this._transform = new Transform3D(this);
  10113. this._isStatic = isStatic;
  10114. this.layer = 0;
  10115. this.name = name ? name : "New Sprite3D";
  10116. }
  10117. static __init__() {
  10118. }
  10119. static instantiate(original, parent = null, worldPositionStays = true, position = null, rotation = null) {
  10120. var destSprite3D = original.clone();
  10121. (parent) && (parent.addChild(destSprite3D));
  10122. var transform = destSprite3D.transform;
  10123. if (worldPositionStays) {
  10124. var worldMatrix = transform.worldMatrix;
  10125. original.transform.worldMatrix.cloneTo(worldMatrix);
  10126. transform.worldMatrix = worldMatrix;
  10127. }
  10128. else {
  10129. (position) && (transform.position = position);
  10130. (rotation) && (transform.rotation = rotation);
  10131. }
  10132. return destSprite3D;
  10133. }
  10134. static load(url, complete) {
  10135. Laya.Laya.loader.create(url, complete, null, Sprite3D.HIERARCHY);
  10136. }
  10137. get id() {
  10138. return this._id;
  10139. }
  10140. get layer() {
  10141. return this._layer;
  10142. }
  10143. set layer(value) {
  10144. if (this._layer !== value) {
  10145. if (value >= 0 && value <= 30) {
  10146. this._layer = value;
  10147. }
  10148. else {
  10149. throw new Error("Layer value must be 0-30.");
  10150. }
  10151. }
  10152. }
  10153. get url() {
  10154. return this._url;
  10155. }
  10156. get isStatic() {
  10157. return this._isStatic;
  10158. }
  10159. get transform() {
  10160. return this._transform;
  10161. }
  10162. _setCreateURL(url) {
  10163. this._url = Laya.URL.formatURL(url);
  10164. }
  10165. _changeAnimatorsToLinkSprite3D(sprite3D, isLink, path) {
  10166. var animator = this.getComponent(Animator);
  10167. if (animator) {
  10168. if (!animator.avatar)
  10169. sprite3D._changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path);
  10170. }
  10171. if (this._parent && this._parent instanceof Sprite3D) {
  10172. path.unshift(this._parent.name);
  10173. var p = this._parent;
  10174. (p._hierarchyAnimator) && (p._changeAnimatorsToLinkSprite3D(sprite3D, isLink, path));
  10175. }
  10176. }
  10177. _setHierarchyAnimator(animator, parentAnimator) {
  10178. this._changeHierarchyAnimator(animator);
  10179. this._changeAnimatorAvatar(animator.avatar);
  10180. for (var i = 0, n = this._children.length; i < n; i++) {
  10181. var child = this._children[i];
  10182. (child._hierarchyAnimator == parentAnimator) && (child._setHierarchyAnimator(animator, parentAnimator));
  10183. }
  10184. }
  10185. _clearHierarchyAnimator(animator, parentAnimator) {
  10186. this._changeHierarchyAnimator(parentAnimator);
  10187. this._changeAnimatorAvatar(parentAnimator ? parentAnimator.avatar : null);
  10188. for (var i = 0, n = this._children.length; i < n; i++) {
  10189. var child = this._children[i];
  10190. (child._hierarchyAnimator == animator) && (child._clearHierarchyAnimator(animator, parentAnimator));
  10191. }
  10192. }
  10193. _changeHierarchyAnimatorAvatar(animator, avatar) {
  10194. this._changeAnimatorAvatar(avatar);
  10195. for (var i = 0, n = this._children.length; i < n; i++) {
  10196. var child = this._children[i];
  10197. (child._hierarchyAnimator == animator) && (child._changeHierarchyAnimatorAvatar(animator, avatar));
  10198. }
  10199. }
  10200. _changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path) {
  10201. animator._handleSpriteOwnersBySprite(isLink, path, this);
  10202. for (var i = 0, n = this._children.length; i < n; i++) {
  10203. var child = this._children[i];
  10204. var index = path.length;
  10205. path.push(child.name);
  10206. child._changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path);
  10207. path.splice(index, 1);
  10208. }
  10209. }
  10210. _changeHierarchyAnimator(animator) {
  10211. this._hierarchyAnimator = animator;
  10212. }
  10213. _changeAnimatorAvatar(avatar) {
  10214. }
  10215. _onAdded() {
  10216. if (this._parent instanceof Sprite3D) {
  10217. var parent3D = this._parent;
  10218. this.transform._setParent(parent3D.transform);
  10219. if (parent3D._hierarchyAnimator) {
  10220. (!this._hierarchyAnimator) && (this._setHierarchyAnimator(parent3D._hierarchyAnimator, null));
  10221. parent3D._changeAnimatorsToLinkSprite3D(this, true, [this.name]);
  10222. }
  10223. }
  10224. super._onAdded();
  10225. }
  10226. _onRemoved() {
  10227. super._onRemoved();
  10228. if (this._parent instanceof Sprite3D) {
  10229. var parent3D = this._parent;
  10230. this.transform._setParent(null);
  10231. if (parent3D._hierarchyAnimator) {
  10232. (this._hierarchyAnimator == parent3D._hierarchyAnimator) && (this._clearHierarchyAnimator(parent3D._hierarchyAnimator, null));
  10233. parent3D._changeAnimatorsToLinkSprite3D(this, false, [this.name]);
  10234. }
  10235. }
  10236. }
  10237. _parse(data, spriteMap) {
  10238. (data.isStatic !== undefined) && (this._isStatic = data.isStatic);
  10239. (data.active !== undefined) && (this.active = data.active);
  10240. (data.name != undefined) && (this.name = data.name);
  10241. if (data.position !== undefined) {
  10242. var loccalPosition = this.transform.localPosition;
  10243. loccalPosition.fromArray(data.position);
  10244. this.transform.localPosition = loccalPosition;
  10245. }
  10246. if (data.rotationEuler !== undefined) {
  10247. var localRotationEuler = this.transform.localRotationEuler;
  10248. localRotationEuler.fromArray(data.rotationEuler);
  10249. this.transform.localRotationEuler = localRotationEuler;
  10250. }
  10251. if (data.rotation !== undefined) {
  10252. var localRotation = this.transform.localRotation;
  10253. localRotation.fromArray(data.rotation);
  10254. this.transform.localRotation = localRotation;
  10255. }
  10256. if (data.scale !== undefined) {
  10257. var localScale = this.transform.localScale;
  10258. localScale.fromArray(data.scale);
  10259. this.transform.localScale = localScale;
  10260. }
  10261. (data.layer != undefined) && (this.layer = data.layer);
  10262. }
  10263. _cloneTo(destObject, srcRoot, dstRoot) {
  10264. if (this.destroyed)
  10265. throw new Error("Sprite3D: Can't be cloned if the Sprite3D has destroyed.");
  10266. var destSprite3D = destObject;
  10267. var trans = this._transform;
  10268. var destTrans = destSprite3D._transform;
  10269. destSprite3D.name = this.name;
  10270. destSprite3D.destroyed = this.destroyed;
  10271. destSprite3D.active = this.active;
  10272. destTrans.localPosition = trans.localPosition;
  10273. destTrans.localRotation = trans.localRotation;
  10274. destTrans.localScale = trans.localScale;
  10275. destSprite3D._isStatic = this._isStatic;
  10276. destSprite3D.layer = this.layer;
  10277. super._cloneTo(destSprite3D, srcRoot, dstRoot);
  10278. }
  10279. static _createSprite3DInstance(scrSprite) {
  10280. var node = scrSprite._create();
  10281. var children = scrSprite._children;
  10282. for (var i = 0, n = children.length; i < n; i++) {
  10283. var child = Sprite3D._createSprite3DInstance(children[i]);
  10284. node.addChild(child);
  10285. }
  10286. return node;
  10287. }
  10288. static _parseSprite3DInstance(srcRoot, dstRoot, scrSprite, dstSprite) {
  10289. var srcChildren = scrSprite._children;
  10290. var dstChildren = dstSprite._children;
  10291. for (var i = 0, n = srcChildren.length; i < n; i++)
  10292. Sprite3D._parseSprite3DInstance(srcRoot, dstRoot, srcChildren[i], dstChildren[i]);
  10293. scrSprite._cloneTo(dstSprite, srcRoot, dstRoot);
  10294. }
  10295. clone() {
  10296. var dstSprite3D = Sprite3D._createSprite3DInstance(this);
  10297. Sprite3D._parseSprite3DInstance(this, dstSprite3D, this, dstSprite3D);
  10298. return dstSprite3D;
  10299. }
  10300. destroy(destroyChild = true) {
  10301. if (this.destroyed)
  10302. return;
  10303. super.destroy(destroyChild);
  10304. this._transform = null;
  10305. this._scripts = null;
  10306. this._url && Laya.Loader.clearRes(this._url);
  10307. }
  10308. _create() {
  10309. return new Sprite3D();
  10310. }
  10311. }
  10312. Sprite3D.HIERARCHY = "HIERARCHY";
  10313. Sprite3D.WORLDMATRIX = Shader3D.propertyNameToID("u_WorldMat");
  10314. Sprite3D.MVPMATRIX = Shader3D.propertyNameToID("u_MvpMatrix");
  10315. Sprite3D._uniqueIDCounter = 0;
  10316. class RenderableSprite3D extends Sprite3D {
  10317. constructor(name) {
  10318. super(name);
  10319. }
  10320. static __init__() {
  10321. RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW = Shader3D.getDefineByName("RECEIVESHADOW");
  10322. RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV = Shader3D.getDefineByName("SCALEOFFSETLIGHTINGMAPUV");
  10323. RenderableSprite3D.SAHDERDEFINE_LIGHTMAP = Shader3D.getDefineByName("LIGHTMAP");
  10324. }
  10325. _onInActive() {
  10326. super._onInActive();
  10327. this._scene._removeRenderObject(this._render);
  10328. }
  10329. _onActive() {
  10330. super._onActive();
  10331. this._scene._addRenderObject(this._render);
  10332. }
  10333. _onActiveInScene() {
  10334. super._onActiveInScene();
  10335. if (ILaya3D.Laya3D._editerEnvironment) {
  10336. var scene = this._scene;
  10337. var pickColor = new Vector4();
  10338. scene._allotPickColorByID(this.id, pickColor);
  10339. scene._pickIdToSprite[this.id] = this;
  10340. this._render._shaderValues.setVector(RenderableSprite3D.PICKCOLOR, pickColor);
  10341. }
  10342. }
  10343. _addToInitStaticBatchManager() {
  10344. }
  10345. _setBelongScene(scene) {
  10346. super._setBelongScene(scene);
  10347. this._render._setBelongScene(scene);
  10348. }
  10349. _setUnBelongScene() {
  10350. this._render._shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  10351. super._setUnBelongScene();
  10352. }
  10353. _changeHierarchyAnimator(animator) {
  10354. if (this._hierarchyAnimator) {
  10355. var renderableSprites = this._hierarchyAnimator._renderableSprites;
  10356. renderableSprites.splice(renderableSprites.indexOf(this), 1);
  10357. }
  10358. if (animator)
  10359. animator._renderableSprites.push(this);
  10360. super._changeHierarchyAnimator(animator);
  10361. }
  10362. destroy(destroyChild = true) {
  10363. super.destroy(destroyChild);
  10364. this._render._destroy();
  10365. this._render = null;
  10366. }
  10367. _create() {
  10368. return new RenderableSprite3D(this.name);
  10369. }
  10370. }
  10371. RenderableSprite3D.LIGHTMAPSCALEOFFSET = Shader3D.propertyNameToID("u_LightmapScaleOffset");
  10372. RenderableSprite3D.LIGHTMAP = Shader3D.propertyNameToID("u_LightMap");
  10373. RenderableSprite3D.PICKCOLOR = Shader3D.propertyNameToID("u_PickColor");
  10374. class StaticBatchManager {
  10375. constructor() {
  10376. this._initBatchSprites = [];
  10377. this._staticBatches = {};
  10378. this._batchRenderElementPoolIndex = 0;
  10379. this._batchRenderElementPool = [];
  10380. }
  10381. static _addToStaticBatchQueue(sprite3D, renderableSprite3D) {
  10382. if (sprite3D instanceof RenderableSprite3D)
  10383. renderableSprite3D.push(sprite3D);
  10384. for (var i = 0, n = sprite3D.numChildren; i < n; i++)
  10385. StaticBatchManager._addToStaticBatchQueue(sprite3D._children[i], renderableSprite3D);
  10386. }
  10387. static _registerManager(manager) {
  10388. StaticBatchManager._managers.push(manager);
  10389. }
  10390. static combine(staticBatchRoot, renderableSprite3Ds = null) {
  10391. if (!renderableSprite3Ds) {
  10392. renderableSprite3Ds = [];
  10393. if (staticBatchRoot)
  10394. StaticBatchManager._addToStaticBatchQueue(staticBatchRoot, renderableSprite3Ds);
  10395. }
  10396. var batchSpritesCount = renderableSprite3Ds.length;
  10397. if (batchSpritesCount > 0) {
  10398. for (var i = 0; i < batchSpritesCount; i++) {
  10399. var sprite = renderableSprite3Ds[i];
  10400. if (!sprite.destroyed) {
  10401. if (sprite._render._isPartOfStaticBatch)
  10402. console.warn("StaticBatchManager: Sprite " + sprite.name + " has a part of Static Batch,it will be ignore.");
  10403. else
  10404. sprite._addToInitStaticBatchManager();
  10405. }
  10406. }
  10407. for (var k = 0, m = StaticBatchManager._managers.length; k < m; k++) {
  10408. var manager = StaticBatchManager._managers[k];
  10409. manager._initStaticBatchs(staticBatchRoot);
  10410. }
  10411. }
  10412. }
  10413. _partition(items, left, right) {
  10414. var pivot = items[Math.floor((right + left) / 2)];
  10415. while (left <= right) {
  10416. while (this._compare(items[left], pivot) < 0)
  10417. left++;
  10418. while (this._compare(items[right], pivot) > 0)
  10419. right--;
  10420. if (left < right) {
  10421. var temp = items[left];
  10422. items[left] = items[right];
  10423. items[right] = temp;
  10424. left++;
  10425. right--;
  10426. }
  10427. else if (left === right) {
  10428. left++;
  10429. break;
  10430. }
  10431. }
  10432. return left;
  10433. }
  10434. _quickSort(items, left, right) {
  10435. if (items.length > 1) {
  10436. var index = this._partition(items, left, right);
  10437. var leftIndex = index - 1;
  10438. if (left < leftIndex)
  10439. this._quickSort(items, left, leftIndex);
  10440. if (index < right)
  10441. this._quickSort(items, index, right);
  10442. }
  10443. }
  10444. _compare(left, right) {
  10445. throw "StaticBatch:must override this function.";
  10446. }
  10447. _initStaticBatchs(rootSprite) {
  10448. throw "StaticBatch:must override this function.";
  10449. }
  10450. _getBatchRenderElementFromPool() {
  10451. throw "StaticBatch:must override this function.";
  10452. }
  10453. _addBatchSprite(renderableSprite3D) {
  10454. this._initBatchSprites.push(renderableSprite3D);
  10455. }
  10456. _clear() {
  10457. this._batchRenderElementPoolIndex = 0;
  10458. }
  10459. _garbageCollection() {
  10460. throw "StaticBatchManager: must override it.";
  10461. }
  10462. dispose() {
  10463. this._staticBatches = null;
  10464. }
  10465. }
  10466. StaticBatchManager._managers = [];
  10467. class FrustumCulling {
  10468. constructor() {
  10469. }
  10470. static __init__() {
  10471. if (Laya.Render.supportWebGLPlusCulling) {
  10472. FrustumCulling._cullingBufferLength = 0;
  10473. FrustumCulling._cullingBuffer = new Float32Array(4096);
  10474. }
  10475. }
  10476. static _drawTraversalCullingBound(renderList, debugTool) {
  10477. var validCount = renderList.length;
  10478. var renders = renderList.elements;
  10479. for (var i = 0, n = renderList.length; i < n; i++) {
  10480. var color = FrustumCulling._tempColor0;
  10481. color.r = 0;
  10482. color.g = 1;
  10483. color.b = 0;
  10484. color.a = 1;
  10485. Utils3D._drawBound(debugTool, renders[i].bounds._getBoundBox(), color);
  10486. }
  10487. }
  10488. static _traversalCulling(camera, scene, context, renderList, customShader, replacementTag, isShadowCasterCull) {
  10489. var renders = renderList.elements;
  10490. var boundFrustum = camera.boundFrustum;
  10491. var camPos = camera._transform.position;
  10492. for (var i = 0, n = renderList.length; i < n; i++) {
  10493. var render = renders[i];
  10494. var canPass;
  10495. if (isShadowCasterCull)
  10496. canPass = render._castShadow && render._enable;
  10497. else
  10498. canPass = camera._isLayerVisible(render._owner._layer) && render._enable;
  10499. if (canPass) {
  10500. Laya.Stat.frustumCulling++;
  10501. if (!camera.useOcclusionCulling || render._needRender(boundFrustum, context)) {
  10502. render._visible = true;
  10503. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  10504. var elements = render._renderElements;
  10505. for (var j = 0, m = elements.length; j < m; j++)
  10506. elements[j]._update(scene, context, customShader, replacementTag);
  10507. }
  10508. else {
  10509. render._visible = false;
  10510. }
  10511. }
  10512. else {
  10513. render._visible = false;
  10514. }
  10515. }
  10516. }
  10517. static renderObjectCulling(camera, scene, context, customShader, replacementTag, isShadowCasterCull) {
  10518. var i, n;
  10519. var opaqueQueue = scene._opaqueQueue;
  10520. var transparentQueue = scene._transparentQueue;
  10521. var renderList = scene._renders;
  10522. opaqueQueue.clear();
  10523. transparentQueue.clear();
  10524. var staticBatchManagers = StaticBatchManager._managers;
  10525. for (i = 0, n = staticBatchManagers.length; i < n; i++)
  10526. staticBatchManagers[i]._clear();
  10527. var dynamicBatchManagers = DynamicBatchManager._managers;
  10528. for (i = 0, n = dynamicBatchManagers.length; i < n; i++)
  10529. dynamicBatchManagers[i]._clear();
  10530. var octree = scene._octree;
  10531. if (octree) {
  10532. octree.updateMotionObjects();
  10533. octree.shrinkRootIfPossible();
  10534. octree.getCollidingWithFrustum(context, customShader, replacementTag, isShadowCasterCull);
  10535. }
  10536. FrustumCulling._traversalCulling(camera, scene, context, renderList, customShader, replacementTag, isShadowCasterCull);
  10537. if (FrustumCulling.debugFrustumCulling) {
  10538. var debugTool = scene._debugTool;
  10539. debugTool.clear();
  10540. if (octree) {
  10541. octree.drawAllBounds(debugTool);
  10542. octree.drawAllObjects(debugTool);
  10543. }
  10544. FrustumCulling._drawTraversalCullingBound(renderList, debugTool);
  10545. }
  10546. var count = opaqueQueue.elements.length;
  10547. (count > 0) && (opaqueQueue._quickSort(0, count - 1));
  10548. count = transparentQueue.elements.length;
  10549. (count > 0) && (transparentQueue._quickSort(0, count - 1));
  10550. }
  10551. static renderObjectCullingNative(camera, scene, context, renderList, customShader, replacementTag) {
  10552. var i, n, j, m;
  10553. var opaqueQueue = scene._opaqueQueue;
  10554. var transparentQueue = scene._transparentQueue;
  10555. opaqueQueue.clear();
  10556. transparentQueue.clear();
  10557. var staticBatchManagers = StaticBatchManager._managers;
  10558. for (i = 0, n = staticBatchManagers.length; i < n; i++)
  10559. staticBatchManagers[i]._clear();
  10560. var dynamicBatchManagers = DynamicBatchManager._managers;
  10561. for (i = 0, n = dynamicBatchManagers.length; i < n; i++)
  10562. dynamicBatchManagers[i]._clear();
  10563. var validCount = renderList.length;
  10564. var renders = renderList.elements;
  10565. for (i = 0; i < validCount; i++) {
  10566. renders[i].bounds;
  10567. renders[i]._updateForNative && renders[i]._updateForNative(context);
  10568. }
  10569. var boundFrustum = camera.boundFrustum;
  10570. FrustumCulling.cullingNative(camera._boundFrustumBuffer, FrustumCulling._cullingBuffer, scene._cullingBufferIndices, validCount, scene._cullingBufferResult);
  10571. var camPos = context.camera._transform.position;
  10572. for (i = 0; i < validCount; i++) {
  10573. var render = renders[i];
  10574. if (!camera.useOcclusionCulling || (camera._isLayerVisible(render._owner._layer) && render._enable && scene._cullingBufferResult[i])) {
  10575. render._visible = true;
  10576. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  10577. var elements = render._renderElements;
  10578. for (j = 0, m = elements.length; j < m; j++) {
  10579. var element = elements[j];
  10580. element._update(scene, context, customShader, replacementTag);
  10581. }
  10582. }
  10583. else {
  10584. render._visible = false;
  10585. }
  10586. }
  10587. var count = opaqueQueue.elements.length;
  10588. (count > 0) && (opaqueQueue._quickSort(0, count - 1));
  10589. count = transparentQueue.elements.length;
  10590. (count > 0) && (transparentQueue._quickSort(0, count - 1));
  10591. }
  10592. static cullingNative(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult) {
  10593. return Laya.LayaGL.instance.culling(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult);
  10594. }
  10595. }
  10596. FrustumCulling._tempVector3 = new Vector3();
  10597. FrustumCulling._tempColor0 = new Color();
  10598. FrustumCulling.debugFrustumCulling = false;
  10599. class BatchMark {
  10600. constructor() {
  10601. this.updateMark = -1;
  10602. this.indexInList = -1;
  10603. this.batched = false;
  10604. }
  10605. }
  10606. class GeometryElement {
  10607. constructor() {
  10608. this._destroyed = false;
  10609. }
  10610. get destroyed() {
  10611. return this._destroyed;
  10612. }
  10613. _getType() {
  10614. throw "GeometryElement:must override it.";
  10615. }
  10616. _prepareRender(state) {
  10617. return true;
  10618. }
  10619. _render(state) {
  10620. throw "GeometryElement:must override it.";
  10621. }
  10622. destroy() {
  10623. if (this._destroyed)
  10624. return;
  10625. this._destroyed = true;
  10626. }
  10627. }
  10628. GeometryElement._typeCounter = 0;
  10629. class VertexBuffer3D extends Laya.Buffer {
  10630. constructor(byteLength, bufferUsage, canRead = false) {
  10631. super();
  10632. this._vertexDeclaration = null;
  10633. this._float32Reader = null;
  10634. var gl = Laya.LayaGL.instance;
  10635. this._bufferUsage = bufferUsage;
  10636. this._bufferType = gl.ARRAY_BUFFER;
  10637. this._canRead = canRead;
  10638. this._byteLength = byteLength;
  10639. this.bind();
  10640. gl.bufferData(this._bufferType, this._byteLength, this._bufferUsage);
  10641. if (canRead) {
  10642. this._buffer = new Uint8Array(byteLength);
  10643. this._float32Reader = new Float32Array(this._buffer.buffer);
  10644. }
  10645. }
  10646. get vertexDeclaration() {
  10647. return this._vertexDeclaration;
  10648. }
  10649. set vertexDeclaration(value) {
  10650. this._vertexDeclaration = value;
  10651. }
  10652. get canRead() {
  10653. return this._canRead;
  10654. }
  10655. bind() {
  10656. if (Laya.Buffer._bindedVertexBuffer !== this._glBuffer) {
  10657. var gl = Laya.LayaGL.instance;
  10658. gl.bindBuffer(gl.ARRAY_BUFFER, this._glBuffer);
  10659. Laya.Buffer._bindedVertexBuffer = this._glBuffer;
  10660. return true;
  10661. }
  10662. else {
  10663. return false;
  10664. }
  10665. }
  10666. setData(buffer, bufferOffset = 0, dataStartIndex = 0, dataCount = Number.MAX_SAFE_INTEGER) {
  10667. this.bind();
  10668. var needSubData = dataStartIndex !== 0 || dataCount !== Number.MAX_SAFE_INTEGER;
  10669. if (needSubData) {
  10670. var subData = new Uint8Array(buffer, dataStartIndex, dataCount);
  10671. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset, subData);
  10672. if (this._canRead)
  10673. this._buffer.set(subData, bufferOffset);
  10674. }
  10675. else {
  10676. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset, buffer);
  10677. if (this._canRead)
  10678. this._buffer.set(new Uint8Array(buffer), bufferOffset);
  10679. }
  10680. }
  10681. getUint8Data() {
  10682. if (this._canRead)
  10683. return this._buffer;
  10684. else
  10685. throw new Error("Can't read data from VertexBuffer with only write flag!");
  10686. }
  10687. getFloat32Data() {
  10688. if (this._canRead)
  10689. return this._float32Reader;
  10690. else
  10691. throw new Error("Can't read data from VertexBuffer with only write flag!");
  10692. }
  10693. markAsUnreadbale() {
  10694. this._canRead = false;
  10695. this._buffer = null;
  10696. this._float32Reader = null;
  10697. }
  10698. destroy() {
  10699. super.destroy();
  10700. this._buffer = null;
  10701. this._float32Reader = null;
  10702. this._vertexDeclaration = null;
  10703. }
  10704. }
  10705. VertexBuffer3D.DATATYPE_FLOAT32ARRAY = 0;
  10706. VertexBuffer3D.DATATYPE_UINT8ARRAY = 1;
  10707. class VertexElementFormat {
  10708. static __init__() {
  10709. var gl = Laya.LayaGL.instance;
  10710. VertexElementFormat._elementInfos = {
  10711. "single": [1, gl.FLOAT, 0],
  10712. "vector2": [2, gl.FLOAT, 0],
  10713. "vector3": [3, gl.FLOAT, 0],
  10714. "vector4": [4, gl.FLOAT, 0],
  10715. "color": [4, gl.FLOAT, 0],
  10716. "byte4": [4, gl.UNSIGNED_BYTE, 0],
  10717. "short2": [2, gl.FLOAT, 0],
  10718. "short4": [4, gl.FLOAT, 0],
  10719. "normalizedshort2": [2, gl.FLOAT, 0],
  10720. "normalizedshort4": [4, gl.FLOAT, 0],
  10721. "halfvector2": [2, gl.FLOAT, 0],
  10722. "halfvector4": [4, gl.FLOAT, 0]
  10723. };
  10724. }
  10725. static getElementInfos(element) {
  10726. var info = VertexElementFormat._elementInfos[element];
  10727. if (info)
  10728. return info;
  10729. else
  10730. throw "VertexElementFormat: this vertexElementFormat is not implement.";
  10731. }
  10732. }
  10733. VertexElementFormat.Single = "single";
  10734. VertexElementFormat.Vector2 = "vector2";
  10735. VertexElementFormat.Vector3 = "vector3";
  10736. VertexElementFormat.Vector4 = "vector4";
  10737. VertexElementFormat.Color = "color";
  10738. VertexElementFormat.Byte4 = "byte4";
  10739. VertexElementFormat.Short2 = "short2";
  10740. VertexElementFormat.Short4 = "short4";
  10741. VertexElementFormat.NormalizedShort2 = "normalizedshort2";
  10742. VertexElementFormat.NormalizedShort4 = "normalizedshort4";
  10743. VertexElementFormat.HalfVector2 = "halfvector2";
  10744. VertexElementFormat.HalfVector4 = "halfvector4";
  10745. class VertexDeclaration {
  10746. constructor(vertexStride, vertexElements) {
  10747. this._id = ++VertexDeclaration._uniqueIDCounter;
  10748. this._vertexElementsDic = {};
  10749. this._vertexStride = vertexStride;
  10750. this._vertexElements = vertexElements;
  10751. var count = vertexElements.length;
  10752. this._shaderValues = new ShaderData(null);
  10753. for (var j = 0; j < count; j++) {
  10754. var vertexElement = vertexElements[j];
  10755. var name = vertexElement._elementUsage;
  10756. this._vertexElementsDic[name] = vertexElement;
  10757. var value = new Int32Array(5);
  10758. var elmentInfo = VertexElementFormat.getElementInfos(vertexElement._elementFormat);
  10759. value[0] = elmentInfo[0];
  10760. value[1] = elmentInfo[1];
  10761. value[2] = elmentInfo[2];
  10762. value[3] = this._vertexStride;
  10763. value[4] = vertexElement._offset;
  10764. this._shaderValues.setAttribute(name, value);
  10765. }
  10766. }
  10767. get id() {
  10768. return this._id;
  10769. }
  10770. get vertexStride() {
  10771. return this._vertexStride;
  10772. }
  10773. get vertexElementCount() {
  10774. return this._vertexElements.length;
  10775. }
  10776. getVertexElementByIndex(index) {
  10777. return this._vertexElements[index];
  10778. }
  10779. getVertexElementByUsage(usage) {
  10780. return this._vertexElementsDic[usage];
  10781. }
  10782. }
  10783. VertexDeclaration._uniqueIDCounter = 1;
  10784. class VertexElement {
  10785. get offset() {
  10786. return this._offset;
  10787. }
  10788. get elementFormat() {
  10789. return this._elementFormat;
  10790. }
  10791. get elementUsage() {
  10792. return this._elementUsage;
  10793. }
  10794. constructor(offset, elementFormat, elementUsage) {
  10795. this._offset = offset;
  10796. this._elementFormat = elementFormat;
  10797. this._elementUsage = elementUsage;
  10798. }
  10799. }
  10800. class VertexMesh {
  10801. static __init__() {
  10802. VertexMesh.instanceWorldMatrixDeclaration = new VertexDeclaration(64, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW0),
  10803. new VertexElement(16, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW1),
  10804. new VertexElement(32, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW2),
  10805. new VertexElement(48, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW3)]);
  10806. VertexMesh.instanceMVPMatrixDeclaration = new VertexDeclaration(64, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW0),
  10807. new VertexElement(16, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW1),
  10808. new VertexElement(32, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW2),
  10809. new VertexElement(48, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW3)]);
  10810. }
  10811. static getVertexDeclaration(vertexFlag, compatible = true) {
  10812. var verDec = VertexMesh._vertexDeclarationMap[vertexFlag + (compatible ? "_0" : "_1")];
  10813. if (!verDec) {
  10814. var subFlags = vertexFlag.split(",");
  10815. var offset = 0;
  10816. var elements = [];
  10817. for (var i = 0, n = subFlags.length; i < n; i++) {
  10818. var element;
  10819. switch (subFlags[i]) {
  10820. case "POSITION":
  10821. element = new VertexElement(offset, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0);
  10822. offset += 12;
  10823. break;
  10824. case "NORMAL":
  10825. element = new VertexElement(offset, VertexElementFormat.Vector3, VertexMesh.MESH_NORMAL0);
  10826. offset += 12;
  10827. break;
  10828. case "COLOR":
  10829. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_COLOR0);
  10830. offset += 16;
  10831. break;
  10832. case "UV":
  10833. element = new VertexElement(offset, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE0);
  10834. offset += 8;
  10835. break;
  10836. case "UV1":
  10837. element = new VertexElement(offset, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE1);
  10838. offset += 8;
  10839. break;
  10840. case "BLENDWEIGHT":
  10841. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_BLENDWEIGHT0);
  10842. offset += 16;
  10843. break;
  10844. case "BLENDINDICES":
  10845. if (compatible) {
  10846. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_BLENDINDICES0);
  10847. offset += 16;
  10848. }
  10849. else {
  10850. element = new VertexElement(offset, VertexElementFormat.Byte4, VertexMesh.MESH_BLENDINDICES0);
  10851. offset += 4;
  10852. }
  10853. break;
  10854. case "TANGENT":
  10855. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_TANGENT0);
  10856. offset += 16;
  10857. break;
  10858. default:
  10859. throw "VertexMesh: unknown vertex flag.";
  10860. }
  10861. elements.push(element);
  10862. }
  10863. verDec = new VertexDeclaration(offset, elements);
  10864. VertexMesh._vertexDeclarationMap[vertexFlag + (compatible ? "_0" : "_1")] = verDec;
  10865. }
  10866. return verDec;
  10867. }
  10868. }
  10869. VertexMesh.MESH_POSITION0 = 0;
  10870. VertexMesh.MESH_COLOR0 = 1;
  10871. VertexMesh.MESH_TEXTURECOORDINATE0 = 2;
  10872. VertexMesh.MESH_NORMAL0 = 3;
  10873. VertexMesh.MESH_TANGENT0 = 4;
  10874. VertexMesh.MESH_BLENDINDICES0 = 5;
  10875. VertexMesh.MESH_BLENDWEIGHT0 = 6;
  10876. VertexMesh.MESH_TEXTURECOORDINATE1 = 7;
  10877. VertexMesh.MESH_WORLDMATRIX_ROW0 = 8;
  10878. VertexMesh.MESH_WORLDMATRIX_ROW1 = 9;
  10879. VertexMesh.MESH_WORLDMATRIX_ROW2 = 10;
  10880. VertexMesh.MESH_WORLDMATRIX_ROW3 = 11;
  10881. VertexMesh.MESH_MVPMATRIX_ROW0 = 12;
  10882. VertexMesh.MESH_MVPMATRIX_ROW1 = 13;
  10883. VertexMesh.MESH_MVPMATRIX_ROW2 = 14;
  10884. VertexMesh.MESH_MVPMATRIX_ROW3 = 15;
  10885. VertexMesh._vertexDeclarationMap = {};
  10886. class SubMeshInstanceBatch extends GeometryElement {
  10887. constructor() {
  10888. super();
  10889. this.maxInstanceCount = 1024;
  10890. this.instanceWorldMatrixData = new Float32Array(this.maxInstanceCount * 16);
  10891. this.instanceMVPMatrixData = new Float32Array(this.maxInstanceCount * 16);
  10892. var gl = Laya.LayaGL.instance;
  10893. this.instanceWorldMatrixBuffer = new VertexBuffer3D(this.instanceWorldMatrixData.length * 4, gl.DYNAMIC_DRAW);
  10894. this.instanceMVPMatrixBuffer = new VertexBuffer3D(this.instanceMVPMatrixData.length * 4, gl.DYNAMIC_DRAW);
  10895. this.instanceWorldMatrixBuffer.vertexDeclaration = VertexMesh.instanceWorldMatrixDeclaration;
  10896. this.instanceMVPMatrixBuffer.vertexDeclaration = VertexMesh.instanceMVPMatrixDeclaration;
  10897. }
  10898. static __init__() {
  10899. SubMeshInstanceBatch.instance = new SubMeshInstanceBatch();
  10900. }
  10901. _render(state) {
  10902. var gl = Laya.LayaGL.instance;
  10903. var element = state.renderElement;
  10904. var subMesh = element.instanceSubMesh;
  10905. var count = element.instanceBatchElementList.length;
  10906. var indexCount = subMesh._indexCount;
  10907. subMesh._mesh._instanceBufferState.bind();
  10908. Laya.LayaGL.layaGPUInstance.drawElementsInstanced(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, subMesh._indexStart * 2, count);
  10909. Laya.Stat.renderBatches++;
  10910. Laya.Stat.savedRenderBatches += count - 1;
  10911. Laya.Stat.trianglesFaces += indexCount * count / 3;
  10912. }
  10913. }
  10914. class LightBound {
  10915. }
  10916. class ClusterData {
  10917. constructor() {
  10918. this.updateMark = -1;
  10919. this.pointLightCount = 0;
  10920. this.spotLightCount = 0;
  10921. this.indices = [];
  10922. }
  10923. }
  10924. class Cluster {
  10925. constructor(xSlices, ySlices, zSlices, maxLightsPerClusterAverage) {
  10926. this._updateMark = 0;
  10927. this._depthSliceParam = new Vector2();
  10928. this._xSlices = xSlices;
  10929. this._ySlices = ySlices;
  10930. this._zSlices = zSlices;
  10931. var clusterTexWidth = xSlices * ySlices;
  10932. var clisterTexHeight = zSlices * (1 + Math.ceil(maxLightsPerClusterAverage / 4));
  10933. this._clusterTexture = Utils3D._createFloatTextureBuffer(clusterTexWidth, clisterTexHeight);
  10934. this._clusterTexture.lock = true;
  10935. this._clusterPixels = new Float32Array(clusterTexWidth * clisterTexHeight * 4);
  10936. var clusterDatas = new Array(this._zSlices);
  10937. for (var z = 0; z < this._zSlices; z++) {
  10938. clusterDatas[z] = new Array(this._ySlices);
  10939. for (var y = 0; y < this._ySlices; y++) {
  10940. clusterDatas[z][y] = new Array(this._xSlices);
  10941. for (var x = 0; x < this._xSlices; x++)
  10942. clusterDatas[z][y][x] = new ClusterData();
  10943. }
  10944. }
  10945. this._clusterDatas = clusterDatas;
  10946. }
  10947. _insertSpotLightSphere(origin, forward, size, angle, testSphere) {
  10948. var V = Cluster._tempVector35;
  10949. V.x = testSphere.x - origin.x;
  10950. V.y = testSphere.y - origin.y;
  10951. V.z = testSphere.z - origin.z;
  10952. var VlenSq = Vector3.dot(V, V);
  10953. var sphereRadius = testSphere.w;
  10954. var rangeCull = VlenSq > sphereRadius * sphereRadius;
  10955. if (!rangeCull)
  10956. return false;
  10957. var V1len = Vector3.dot(V, forward);
  10958. var distanceClosestPoint = Math.cos(angle) * Math.sqrt(VlenSq - V1len * V1len) - V1len * Math.sin(angle);
  10959. var angleCull = distanceClosestPoint > sphereRadius;
  10960. var frontCull = V1len > sphereRadius + size;
  10961. var backCull = V1len < -sphereRadius;
  10962. return !(angleCull || frontCull || backCull);
  10963. }
  10964. _placePointLightToClusters(lightIndex, lightBound) {
  10965. var clusterDatas = this._clusterDatas;
  10966. var updateMark = this._updateMark;
  10967. for (var z = lightBound.zMin, zEnd = lightBound.zMax; z < zEnd; z++) {
  10968. for (var y = lightBound.yMin, yEnd = lightBound.yMax; y < yEnd; y++) {
  10969. for (var x = lightBound.xMin, xEnd = lightBound.xMax; x < xEnd; x++) {
  10970. var data = clusterDatas[z][y][x];
  10971. if (data.updateMark != updateMark) {
  10972. data.pointLightCount = 0;
  10973. data.spotLightCount = 0;
  10974. data.updateMark = updateMark;
  10975. }
  10976. var indices = data.indices;
  10977. var lightCount = data.pointLightCount++;
  10978. if (lightCount < indices.length)
  10979. indices[lightCount] = lightIndex;
  10980. else
  10981. indices.push(lightIndex);
  10982. }
  10983. }
  10984. }
  10985. }
  10986. _placeSpotLightToClusters(lightIndex, lightBound) {
  10987. var clusterDatas = this._clusterDatas;
  10988. var updateMark = this._updateMark;
  10989. for (var z = lightBound.zMin, zEnd = lightBound.zMax; z < zEnd; z++) {
  10990. for (var y = lightBound.yMin, yEnd = lightBound.yMax; y < yEnd; y++) {
  10991. for (var x = lightBound.xMin, xEnd = lightBound.xMax; x < xEnd; x++) {
  10992. var data = clusterDatas[z][y][x];
  10993. if (data.updateMark != updateMark) {
  10994. data.pointLightCount = 0;
  10995. data.spotLightCount = 0;
  10996. data.updateMark = updateMark;
  10997. }
  10998. var indices = data.indices;
  10999. var lightCount = data.pointLightCount + data.spotLightCount++;
  11000. if (lightCount < indices.length)
  11001. indices[lightCount] = lightIndex;
  11002. else
  11003. indices.push(lightIndex);
  11004. }
  11005. }
  11006. }
  11007. }
  11008. _insertConePlane(origin, forward, radius, halfAngle, pNor) {
  11009. var V1 = Cluster._tempVector36;
  11010. var V2 = Cluster._tempVector37;
  11011. Vector3.cross(pNor, forward, V1);
  11012. Vector3.cross(V1, forward, V2);
  11013. Vector3.normalize(V2, V2);
  11014. var tanR = radius * Math.tan(halfAngle);
  11015. var capRimX = origin.x + radius * forward.x + tanR * V2.x;
  11016. var capRimY = origin.y + radius * forward.y + tanR * V2.y;
  11017. var capRimZ = origin.z + radius * forward.z + tanR * V2.z;
  11018. return capRimX * pNor.x + capRimY * pNor.y + capRimZ * pNor.z <= 0 || origin.x * pNor.x + origin.y * pNor.y + origin.z * pNor.z <= 0;
  11019. }
  11020. _shrinkSphereLightZPerspective(near, far, lightviewPos, radius, lightBound) {
  11021. var lvZ = lightviewPos.z;
  11022. var minZ = lvZ - radius;
  11023. var maxZ = lvZ + radius;
  11024. if ((minZ > far) || (maxZ <= near))
  11025. return false;
  11026. var depthSliceParam = this._depthSliceParam;
  11027. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  11028. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  11029. return true;
  11030. }
  11031. _shrinkSpotLightZPerspective(near, far, viewLightPos, viewConeCap, radius, halfAngle, lightBound) {
  11032. var pbX = viewConeCap.x, pbY = viewConeCap.y, pbZ = viewConeCap.z;
  11033. var rb = Math.tan(halfAngle) * radius;
  11034. var paX = viewLightPos.x, paY = viewLightPos.y, paZ = viewLightPos.z;
  11035. var aX = pbX - paX, aY = pbY - paY, aZ = pbZ - paZ;
  11036. var dotA = aX * aX + aY * aY + aZ * aZ;
  11037. var eZ = Math.sqrt(1.0 - aZ * aZ / dotA);
  11038. var minZ = Math.max(Math.min(paZ, pbZ - eZ * rb), viewLightPos.z - radius);
  11039. var maxZ = Math.min(Math.max(paZ, pbZ + eZ * rb), viewLightPos.z + radius);
  11040. if ((minZ > far) || (maxZ <= near))
  11041. return false;
  11042. var depthSliceParam = this._depthSliceParam;
  11043. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  11044. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  11045. return true;
  11046. }
  11047. _shrinkSphereLightByBoundOrth(halfX, halfY, near, far, lightviewPos, radius, lightBound) {
  11048. var lvZ = lightviewPos.z;
  11049. var minZ = lvZ - radius, maxZ = lvZ + radius;
  11050. if ((minZ > far) || (maxZ <= near))
  11051. return false;
  11052. var lvX = lightviewPos.x;
  11053. var minX = lvX - radius, maxX = lvX + radius;
  11054. if ((minX > halfX) || (maxX <= -halfX))
  11055. return false;
  11056. var lvY = lightviewPos.y;
  11057. var minY = lvY - radius, maxY = lvY + radius;
  11058. if ((minY > halfY) || (maxY <= -halfY))
  11059. return false;
  11060. var xSlices = this._xSlices, ySlices = this._ySlices;
  11061. var depthSliceParam = this._depthSliceParam;
  11062. var xStride = halfX * 2 / xSlices, yStride = halfY * 2 / ySlices;
  11063. lightBound.xMin = Math.max(Math.floor((minX + halfX) / xStride), 0);
  11064. lightBound.xMax = Math.min(Math.ceil((maxX + halfX) / xStride), xSlices);
  11065. lightBound.yMin = Math.max(Math.floor((halfY - maxY) / yStride), 0);
  11066. lightBound.yMax = Math.min(Math.ceil((halfY - minY) / yStride), ySlices);
  11067. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  11068. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  11069. return true;
  11070. }
  11071. _shrinkSpotLightByBoundOrth(halfX, halfY, near, far, viewLightPos, viewConeCap, radius, halfAngle, lightBound) {
  11072. var pbX = viewConeCap.x, pbY = viewConeCap.y, pbZ = viewConeCap.z;
  11073. var rb = Math.tan(halfAngle) * radius;
  11074. var paX = viewLightPos.x, paY = viewLightPos.y, paZ = viewLightPos.z;
  11075. var aX = pbX - paX, aY = pbY - paY, aZ = pbZ - paZ;
  11076. var dotA = aX * aX + aY * aY + aZ * aZ;
  11077. var eZ = Math.sqrt(1.0 - aZ * aZ / dotA);
  11078. var minZ = Math.max(Math.min(paZ, pbZ - eZ * rb), viewLightPos.z - radius);
  11079. var maxZ = Math.min(Math.max(paZ, pbZ + eZ * rb), viewLightPos.z + radius);
  11080. if ((minZ > far) || (maxZ <= near))
  11081. return false;
  11082. var eX = Math.sqrt(1.0 - aX * aX / dotA);
  11083. var minX = Math.max(Math.min(paX, pbX - eX * rb), viewLightPos.x - radius);
  11084. var maxX = Math.min(Math.max(paX, pbX + eX * rb), viewLightPos.x + radius);
  11085. if ((minX > halfX) || (maxX <= -halfX))
  11086. return false;
  11087. var eY = Math.sqrt(1.0 - aY * aY / dotA);
  11088. var minY = Math.max(Math.min(paY, pbY - eY * rb), viewLightPos.y - radius);
  11089. var maxY = Math.min(Math.max(paY, pbY + eY * rb), viewLightPos.y + radius);
  11090. if ((minY > halfY) || (maxY <= -halfY))
  11091. return false;
  11092. var xSlices = this._xSlices, ySlices = this._ySlices;
  11093. var depthSliceParam = this._depthSliceParam;
  11094. var xStride = halfX * 2 / xSlices, yStride = halfY * 2 / ySlices;
  11095. lightBound.xMin = Math.max(Math.floor((minX + halfX) / xStride), 0);
  11096. lightBound.xMax = Math.min(Math.ceil((maxX + halfX) / xStride), xSlices);
  11097. lightBound.yMin = Math.max(Math.floor((halfY - maxY) / yStride), 0);
  11098. lightBound.yMax = Math.min(Math.ceil((halfY - minY) / yStride), ySlices);
  11099. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  11100. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  11101. return true;
  11102. }
  11103. _shrinkXYByRadiusPerspective(lightviewPos, radius, lightBound, xPlanes, yPlanes) {
  11104. var xMin, yMin;
  11105. var xMax, yMax;
  11106. var lvX = lightviewPos.x, lvY = lightviewPos.y, lvZ = lightviewPos.z;
  11107. var i;
  11108. var n = this._ySlices + 1;
  11109. for (i = 0; i < n; i++) {
  11110. var plane = yPlanes[i];
  11111. if (lvY * plane.y + lvZ * plane.z < radius) {
  11112. yMin = Math.max(0, i - 1);
  11113. break;
  11114. }
  11115. }
  11116. if (i == n)
  11117. return false;
  11118. yMax = this._ySlices;
  11119. for (i = yMin + 1; i < n; i++) {
  11120. var plane = yPlanes[i];
  11121. if (lvY * plane.y + lvZ * plane.z <= -radius) {
  11122. yMax = Math.max(0, i);
  11123. break;
  11124. }
  11125. }
  11126. n = this._xSlices + 1;
  11127. for (i = 0; i < n; i++) {
  11128. var plane = xPlanes[i];
  11129. if (lvX * plane.x + lvZ * plane.z < radius) {
  11130. xMin = Math.max(0, i - 1);
  11131. break;
  11132. }
  11133. }
  11134. xMax = this._xSlices;
  11135. for (i = xMin + 1; i < n; i++) {
  11136. var plane = xPlanes[i];
  11137. if (lvX * plane.x + lvZ * plane.z <= -radius) {
  11138. xMax = Math.max(0, i);
  11139. break;
  11140. }
  11141. }
  11142. lightBound.xMin = xMin;
  11143. lightBound.xMax = xMax;
  11144. lightBound.yMin = yMin;
  11145. lightBound.yMax = yMax;
  11146. return true;
  11147. }
  11148. _shrinkSpotXYByConePerspective(lightviewPos, viewForward, radius, halfAngle, lightBound, xPlanes, yPlanes) {
  11149. var xMin, yMin;
  11150. var xMax, yMax;
  11151. var normal = Cluster._tempVector32;
  11152. var n = lightBound.yMax + 1;
  11153. for (var i = lightBound.yMin + 1; i < n; i++) {
  11154. if (this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, yPlanes[i])) {
  11155. yMin = Math.max(0, i - 1);
  11156. break;
  11157. }
  11158. }
  11159. yMax = lightBound.yMax;
  11160. for (var i = yMin + 1; i < n; i++) {
  11161. var plane = yPlanes[i];
  11162. normal.setValue(0, -plane.y, -plane.z);
  11163. if (!this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, normal)) {
  11164. yMax = Math.max(0, i);
  11165. break;
  11166. }
  11167. }
  11168. n = lightBound.xMax + 1;
  11169. for (var i = lightBound.xMin + 1; i < n; i++) {
  11170. if (this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, xPlanes[i])) {
  11171. xMin = Math.max(0, i - 1);
  11172. break;
  11173. }
  11174. }
  11175. xMax = lightBound.xMax;
  11176. for (var i = xMin + 1; i < n; i++) {
  11177. var plane = xPlanes[i];
  11178. normal.setValue(-plane.x, 0, -plane.z);
  11179. if (!this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, normal)) {
  11180. xMax = Math.max(0, i);
  11181. break;
  11182. }
  11183. }
  11184. lightBound.xMin = xMin;
  11185. lightBound.xMax = xMax;
  11186. lightBound.yMin = yMin;
  11187. lightBound.yMax = yMax;
  11188. }
  11189. _updatePointLightPerspective(near, far, viewMat, pointLight, lightIndex, xPlanes, yPlanes) {
  11190. var lightBound = Cluster._tempLightBound;
  11191. var lightviewPos = Cluster._tempVector30;
  11192. Vector3.transformV3ToV3(pointLight._transform.position, viewMat, lightviewPos);
  11193. lightviewPos.z *= -1;
  11194. if (!this._shrinkSphereLightZPerspective(near, far, lightviewPos, pointLight.range, lightBound))
  11195. return;
  11196. if (!this._shrinkXYByRadiusPerspective(lightviewPos, pointLight.range, lightBound, xPlanes, yPlanes))
  11197. return;
  11198. this._placePointLightToClusters(lightIndex, lightBound);
  11199. }
  11200. _updateSpotLightPerspective(near, far, viewMat, spotLight, lightIndex, xPlanes, yPlanes) {
  11201. var lightBound = Cluster._tempLightBound;
  11202. var viewPos = Cluster._tempVector30;
  11203. var forward = Cluster._tempVector31;
  11204. var viewConeCap = Cluster._tempVector34;
  11205. var position = spotLight._transform.position;
  11206. var range = spotLight.range;
  11207. spotLight._transform.worldMatrix.getForward(forward);
  11208. Vector3.normalize(forward, forward);
  11209. Vector3.scale(forward, range, viewConeCap);
  11210. Vector3.add(position, viewConeCap, viewConeCap);
  11211. Vector3.transformV3ToV3(position, viewMat, viewPos);
  11212. Vector3.transformV3ToV3(viewConeCap, viewMat, viewConeCap);
  11213. viewPos.z *= -1;
  11214. viewConeCap.z *= -1;
  11215. var halfAngle = (spotLight.spotAngle / 2) * Math.PI / 180;
  11216. if (!this._shrinkSpotLightZPerspective(near, far, viewPos, viewConeCap, range, halfAngle, lightBound))
  11217. return;
  11218. if (!this._shrinkXYByRadiusPerspective(viewPos, range, lightBound, xPlanes, yPlanes))
  11219. return;
  11220. var viewFor = Cluster._tempVector33;
  11221. viewFor.x = viewConeCap.x - viewPos.x, viewFor.y = viewConeCap.y - viewPos.y, viewFor.z = viewConeCap.z - viewPos.z;
  11222. Vector3.normalize(viewFor, viewFor);
  11223. this._shrinkSpotXYByConePerspective(viewPos, viewFor, range, halfAngle, lightBound, xPlanes, yPlanes);
  11224. this._placeSpotLightToClusters(lightIndex, lightBound);
  11225. }
  11226. _updatePointLightOrth(halfX, halfY, near, far, viewMat, pointLight, lightIndex) {
  11227. var lightBound = Cluster._tempLightBound;
  11228. var lightviewPos = Cluster._tempVector30;
  11229. Vector3.transformV3ToV3(pointLight._transform.position, viewMat, lightviewPos);
  11230. lightviewPos.z *= -1;
  11231. if (!this._shrinkSphereLightByBoundOrth(halfX, halfY, near, far, lightviewPos, pointLight.range, lightBound))
  11232. return;
  11233. this._placePointLightToClusters(lightIndex, lightBound);
  11234. }
  11235. _updateSpotLightOrth(halfX, halfY, near, far, viewMat, spotLight, lightIndex) {
  11236. var lightBound = Cluster._tempLightBound;
  11237. var viewPos = Cluster._tempVector30;
  11238. var forward = Cluster._tempVector31;
  11239. var viewConeCap = Cluster._tempVector34;
  11240. var position = spotLight._transform.position;
  11241. var range = spotLight.range;
  11242. spotLight._transform.worldMatrix.getForward(forward);
  11243. Vector3.normalize(forward, forward);
  11244. Vector3.scale(forward, range, viewConeCap);
  11245. Vector3.add(position, viewConeCap, viewConeCap);
  11246. Vector3.transformV3ToV3(position, viewMat, viewPos);
  11247. Vector3.transformV3ToV3(viewConeCap, viewMat, viewConeCap);
  11248. viewPos.z *= -1;
  11249. viewConeCap.z *= -1;
  11250. var halfAngle = (spotLight.spotAngle / 2) * Math.PI / 180;
  11251. if (!this._shrinkSpotLightByBoundOrth(halfX, halfY, near, far, viewPos, viewConeCap, range, halfAngle, lightBound))
  11252. return;
  11253. this._placeSpotLightToClusters(lightIndex, lightBound);
  11254. }
  11255. update(camera, scene) {
  11256. this._updateMark++;
  11257. var camNear = camera.nearPlane;
  11258. this._depthSliceParam.x = Config3D._config.lightClusterCount.z / Math.log2(camera.farPlane / camNear);
  11259. this._depthSliceParam.y = Math.log2(camNear) * this._depthSliceParam.x;
  11260. var near = camera.nearPlane;
  11261. var far = camera.farPlane;
  11262. var viewMat = camera.viewMatrix;
  11263. var curCount = scene._directionLights._length;
  11264. var pointLights = scene._pointLights;
  11265. var poiCount = pointLights._length;
  11266. var poiElements = pointLights._elements;
  11267. var spotLights = scene._spotLights;
  11268. var spoCount = spotLights._length;
  11269. var spoElements = spotLights._elements;
  11270. if (camera.orthographic) {
  11271. var halfY = camera.orthographicVerticalSize / 2.0;
  11272. var halfX = halfY * camera.aspectRatio;
  11273. for (var i = 0; i < poiCount; i++, curCount++)
  11274. this._updatePointLightOrth(halfX, halfY, near, far, viewMat, poiElements[i], curCount);
  11275. for (var i = 0; i < spoCount; i++, curCount++)
  11276. this._updateSpotLightOrth(halfX, halfY, near, far, viewMat, spoElements[i], curCount);
  11277. }
  11278. else {
  11279. camera._updateClusterPlaneXY();
  11280. var xPlanes = camera._clusterXPlanes;
  11281. var yPlanes = camera._clusterYPlanes;
  11282. for (var i = 0; i < poiCount; i++, curCount++)
  11283. this._updatePointLightPerspective(near, far, viewMat, poiElements[i], curCount, xPlanes, yPlanes);
  11284. for (var i = 0; i < spoCount; i++, curCount++)
  11285. this._updateSpotLightPerspective(near, far, viewMat, spoElements[i], curCount, xPlanes, yPlanes);
  11286. }
  11287. if (poiCount + spoCount > 0) {
  11288. var xSlices = this._xSlices, ySlices = this._ySlices, zSlices = this._zSlices;
  11289. var widthFloat = xSlices * ySlices * 4;
  11290. var lightOff = widthFloat * zSlices;
  11291. var clusterPixels = this._clusterPixels;
  11292. var clusterPixelsCount = clusterPixels.length;
  11293. var clusterDatas = this._clusterDatas;
  11294. var updateMark = this._updateMark;
  11295. var freeSpace = true;
  11296. for (var z = 0; z < zSlices; z++) {
  11297. for (var y = 0; y < ySlices; y++) {
  11298. for (var x = 0; x < xSlices; x++) {
  11299. var data = clusterDatas[z][y][x];
  11300. var clusterOff = (x + y * xSlices + z * xSlices * ySlices) * 4;
  11301. if (data.updateMark !== updateMark) {
  11302. clusterPixels[clusterOff] = 0;
  11303. clusterPixels[clusterOff + 1] = 0;
  11304. }
  11305. else {
  11306. if (freeSpace) {
  11307. var indices = data.indices;
  11308. var pCount = data.pointLightCount;
  11309. var sCount = data.spotLightCount;
  11310. var count = pCount + sCount;
  11311. if (lightOff + count < clusterPixelsCount) {
  11312. clusterPixels[clusterOff] = pCount;
  11313. clusterPixels[clusterOff + 1] = sCount;
  11314. clusterPixels[clusterOff + 2] = Math.floor(lightOff / widthFloat);
  11315. clusterPixels[clusterOff + 3] = lightOff % widthFloat;
  11316. for (var i = 0; i < count; i++)
  11317. clusterPixels[lightOff++] = indices[i];
  11318. }
  11319. else {
  11320. count = clusterPixelsCount - (lightOff + count);
  11321. pCount = Math.min(pCount, count);
  11322. clusterPixels[clusterOff] = pCount;
  11323. clusterPixels[clusterOff + 1] = Math.min(sCount, count - pCount);
  11324. clusterPixels[clusterOff + 2] = Math.floor(lightOff / widthFloat);
  11325. clusterPixels[clusterOff + 3] = lightOff % widthFloat;
  11326. for (var i = 0; i < count; i++)
  11327. clusterPixels[lightOff++] = indices[i];
  11328. freeSpace = false;
  11329. }
  11330. }
  11331. }
  11332. }
  11333. }
  11334. }
  11335. var width = this._clusterTexture.width;
  11336. this._clusterTexture.setSubPixels(0, 0, width, Math.ceil(lightOff / (4 * width)), clusterPixels);
  11337. }
  11338. }
  11339. }
  11340. Cluster._tempVector30 = new Vector3();
  11341. Cluster._tempVector31 = new Vector3();
  11342. Cluster._tempVector32 = new Vector3();
  11343. Cluster._tempVector33 = new Vector3();
  11344. Cluster._tempVector34 = new Vector3();
  11345. Cluster._tempVector35 = new Vector3();
  11346. Cluster._tempVector36 = new Vector3();
  11347. Cluster._tempVector37 = new Vector3();
  11348. Cluster._tempLightBound = new LightBound();
  11349. class Plane {
  11350. constructor(normal, d = 0) {
  11351. this.normal = normal;
  11352. this.distance = d;
  11353. }
  11354. static createPlaneBy3P(point1, point2, point3) {
  11355. var x1 = point2.x - point1.x;
  11356. var y1 = point2.y - point1.y;
  11357. var z1 = point2.z - point1.z;
  11358. var x2 = point3.x - point1.x;
  11359. var y2 = point3.y - point1.y;
  11360. var z2 = point3.z - point1.z;
  11361. var yz = (y1 * z2) - (z1 * y2);
  11362. var xz = (z1 * x2) - (x1 * z2);
  11363. var xy = (x1 * y2) - (y1 * x2);
  11364. var invPyth = 1 / (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  11365. var x = yz * invPyth;
  11366. var y = xz * invPyth;
  11367. var z = xy * invPyth;
  11368. Plane._TEMPVec3.x = x;
  11369. Plane._TEMPVec3.y = y;
  11370. Plane._TEMPVec3.z = z;
  11371. var d = -((x * point1.x) + (y * point1.y) + (z * point1.z));
  11372. var plane = new Plane(Plane._TEMPVec3, d);
  11373. return plane;
  11374. }
  11375. normalize() {
  11376. var normalEX = this.normal.x;
  11377. var normalEY = this.normal.y;
  11378. var normalEZ = this.normal.z;
  11379. var magnitude = 1 / Math.sqrt(normalEX * normalEX + normalEY * normalEY + normalEZ * normalEZ);
  11380. this.normal.x = normalEX * magnitude;
  11381. this.normal.y = normalEY * magnitude;
  11382. this.normal.z = normalEZ * magnitude;
  11383. this.distance *= magnitude;
  11384. }
  11385. }
  11386. Plane._TEMPVec3 = new Vector3();
  11387. Plane.PlaneIntersectionType_Back = 0;
  11388. Plane.PlaneIntersectionType_Front = 1;
  11389. Plane.PlaneIntersectionType_Intersecting = 2;
  11390. class Ray {
  11391. constructor(origin, direction) {
  11392. this.origin = origin;
  11393. this.direction = direction;
  11394. }
  11395. }
  11396. class ContainmentType {
  11397. }
  11398. ContainmentType.Disjoint = 0;
  11399. ContainmentType.Contains = 1;
  11400. ContainmentType.Intersects = 2;
  11401. class CollisionUtils {
  11402. constructor() {
  11403. }
  11404. static distancePlaneToPoint(plane, point) {
  11405. var dot = Vector3.dot(plane.normal, point);
  11406. return dot - plane.distance;
  11407. }
  11408. static distanceBoxToPoint(box, point) {
  11409. var boxMin = box.min;
  11410. var boxMineX = boxMin.x;
  11411. var boxMineY = boxMin.y;
  11412. var boxMineZ = boxMin.z;
  11413. var boxMax = box.max;
  11414. var boxMaxeX = boxMax.x;
  11415. var boxMaxeY = boxMax.y;
  11416. var boxMaxeZ = boxMax.z;
  11417. var pointeX = point.x;
  11418. var pointeY = point.y;
  11419. var pointeZ = point.z;
  11420. var distance = 0;
  11421. if (pointeX < boxMineX)
  11422. distance += (boxMineX - pointeX) * (boxMineX - pointeX);
  11423. if (pointeX > boxMaxeX)
  11424. distance += (boxMaxeX - pointeX) * (boxMaxeX - pointeX);
  11425. if (pointeY < boxMineY)
  11426. distance += (boxMineY - pointeY) * (boxMineY - pointeY);
  11427. if (pointeY > boxMaxeY)
  11428. distance += (boxMaxeY - pointeY) * (boxMaxeY - pointeY);
  11429. if (pointeZ < boxMineZ)
  11430. distance += (boxMineZ - pointeZ) * (boxMineZ - pointeZ);
  11431. if (pointeZ > boxMaxeZ)
  11432. distance += (boxMaxeZ - pointeZ) * (boxMaxeZ - pointeZ);
  11433. return Math.sqrt(distance);
  11434. }
  11435. static distanceBoxToBox(box1, box2) {
  11436. var box1Mine = box1.min;
  11437. var box1MineX = box1Mine.x;
  11438. var box1MineY = box1Mine.y;
  11439. var box1MineZ = box1Mine.z;
  11440. var box1Maxe = box1.max;
  11441. var box1MaxeX = box1Maxe.x;
  11442. var box1MaxeY = box1Maxe.y;
  11443. var box1MaxeZ = box1Maxe.z;
  11444. var box2Mine = box2.min;
  11445. var box2MineX = box2Mine.x;
  11446. var box2MineY = box2Mine.y;
  11447. var box2MineZ = box2Mine.z;
  11448. var box2Maxe = box2.max;
  11449. var box2MaxeX = box2Maxe.x;
  11450. var box2MaxeY = box2Maxe.y;
  11451. var box2MaxeZ = box2Maxe.z;
  11452. var distance = 0;
  11453. var delta;
  11454. if (box1MineX > box2MaxeX) {
  11455. delta = box1MineX - box2MaxeX;
  11456. distance += delta * delta;
  11457. }
  11458. else if (box2MineX > box1MaxeX) {
  11459. delta = box2MineX - box1MaxeX;
  11460. distance += delta * delta;
  11461. }
  11462. if (box1MineY > box2MaxeY) {
  11463. delta = box1MineY - box2MaxeY;
  11464. distance += delta * delta;
  11465. }
  11466. else if (box2MineY > box1MaxeY) {
  11467. delta = box2MineY - box1MaxeY;
  11468. distance += delta * delta;
  11469. }
  11470. if (box1MineZ > box2MaxeZ) {
  11471. delta = box1MineZ - box2MaxeZ;
  11472. distance += delta * delta;
  11473. }
  11474. else if (box2MineZ > box1MaxeZ) {
  11475. delta = box2MineZ - box1MaxeZ;
  11476. distance += delta * delta;
  11477. }
  11478. return Math.sqrt(distance);
  11479. }
  11480. static distanceSphereToPoint(sphere, point) {
  11481. var distance = Math.sqrt(Vector3.distanceSquared(sphere.center, point));
  11482. distance -= sphere.radius;
  11483. return Math.max(distance, 0);
  11484. }
  11485. static distanceSphereToSphere(sphere1, sphere2) {
  11486. var distance = Math.sqrt(Vector3.distanceSquared(sphere1.center, sphere2.center));
  11487. distance -= sphere1.radius + sphere2.radius;
  11488. return Math.max(distance, 0);
  11489. }
  11490. static intersectsRayAndTriangleRD(ray, vertex1, vertex2, vertex3, out) {
  11491. var rayO = ray.origin;
  11492. var rayOeX = rayO.x;
  11493. var rayOeY = rayO.y;
  11494. var rayOeZ = rayO.z;
  11495. var rayD = ray.direction;
  11496. var rayDeX = rayD.x;
  11497. var rayDeY = rayD.y;
  11498. var rayDeZ = rayD.z;
  11499. var v1eX = vertex1.x;
  11500. var v1eY = vertex1.y;
  11501. var v1eZ = vertex1.z;
  11502. var v2eX = vertex2.x;
  11503. var v2eY = vertex2.y;
  11504. var v2eZ = vertex2.z;
  11505. var v3eX = vertex3.x;
  11506. var v3eY = vertex3.y;
  11507. var v3eZ = vertex3.z;
  11508. var _tempV30eX = CollisionUtils._tempV30.x;
  11509. var _tempV30eY = CollisionUtils._tempV30.y;
  11510. var _tempV30eZ = CollisionUtils._tempV30.z;
  11511. _tempV30eX = v2eX - v1eX;
  11512. _tempV30eY = v2eY - v1eY;
  11513. _tempV30eZ = v2eZ - v1eZ;
  11514. var _tempV31eX = CollisionUtils._tempV31.x;
  11515. var _tempV31eY = CollisionUtils._tempV31.y;
  11516. var _tempV31eZ = CollisionUtils._tempV31.z;
  11517. _tempV31eX = v3eX - v1eX;
  11518. _tempV31eY = v3eY - v1eY;
  11519. _tempV31eZ = v3eZ - v1eZ;
  11520. var _tempV32eX = CollisionUtils._tempV32.x;
  11521. var _tempV32eY = CollisionUtils._tempV32.y;
  11522. var _tempV32eZ = CollisionUtils._tempV32.z;
  11523. _tempV32eX = (rayDeY * _tempV31eZ) - (rayDeZ * _tempV31eY);
  11524. _tempV32eY = (rayDeZ * _tempV31eX) - (rayDeX * _tempV31eZ);
  11525. _tempV32eZ = (rayDeX * _tempV31eY) - (rayDeY * _tempV31eX);
  11526. var determinant = (_tempV30eX * _tempV32eX) + (_tempV30eY * _tempV32eY) + (_tempV30eZ * _tempV32eZ);
  11527. if (MathUtils3D.isZero(determinant)) {
  11528. return false;
  11529. }
  11530. var inversedeterminant = 1 / determinant;
  11531. var _tempV33eX = CollisionUtils._tempV33.x;
  11532. var _tempV33eY = CollisionUtils._tempV33.y;
  11533. var _tempV33eZ = CollisionUtils._tempV33.z;
  11534. _tempV33eX = rayOeX - v1eX;
  11535. _tempV33eY = rayOeY - v1eY;
  11536. _tempV33eZ = rayOeZ - v1eZ;
  11537. var triangleU = (_tempV33eX * _tempV32eX) + (_tempV33eY * _tempV32eY) + (_tempV33eZ * _tempV32eZ);
  11538. triangleU *= inversedeterminant;
  11539. if (triangleU < 0 || triangleU > 1) {
  11540. return false;
  11541. }
  11542. var _tempV34eX = CollisionUtils._tempV34.x;
  11543. var _tempV34eY = CollisionUtils._tempV34.y;
  11544. var _tempV34eZ = CollisionUtils._tempV34.z;
  11545. _tempV34eX = (_tempV33eY * _tempV30eZ) - (_tempV33eZ * _tempV30eY);
  11546. _tempV34eY = (_tempV33eZ * _tempV30eX) - (_tempV33eX * _tempV30eZ);
  11547. _tempV34eZ = (_tempV33eX * _tempV30eY) - (_tempV33eY * _tempV30eX);
  11548. var triangleV = ((rayDeX * _tempV34eX) + (rayDeY * _tempV34eY)) + (rayDeZ * _tempV34eZ);
  11549. triangleV *= inversedeterminant;
  11550. if (triangleV < 0 || triangleU + triangleV > 1) {
  11551. return false;
  11552. }
  11553. var raydistance = (_tempV31eX * _tempV34eX) + (_tempV31eY * _tempV34eY) + (_tempV31eZ * _tempV34eZ);
  11554. raydistance *= inversedeterminant;
  11555. if (raydistance < 0) {
  11556. return false;
  11557. }
  11558. return true;
  11559. }
  11560. static intersectsRayAndTriangleRP(ray, vertex1, vertex2, vertex3, out) {
  11561. var distance;
  11562. if (!CollisionUtils.intersectsRayAndTriangleRD(ray, vertex1, vertex2, vertex3, distance)) {
  11563. out = Vector3._ZERO;
  11564. return false;
  11565. }
  11566. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  11567. Vector3.add(ray.origin, CollisionUtils._tempV30, out);
  11568. return true;
  11569. }
  11570. static intersectsRayAndPoint(ray, point) {
  11571. Vector3.subtract(ray.origin, point, CollisionUtils._tempV30);
  11572. var b = Vector3.dot(CollisionUtils._tempV30, ray.direction);
  11573. var c = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30) - MathUtils3D.zeroTolerance;
  11574. if (c > 0 && b > 0)
  11575. return false;
  11576. var discriminant = b * b - c;
  11577. if (discriminant < 0)
  11578. return false;
  11579. return true;
  11580. }
  11581. static intersectsRayAndRay(ray1, ray2, out) {
  11582. var ray1o = ray1.origin;
  11583. var ray1oeX = ray1o.x;
  11584. var ray1oeY = ray1o.y;
  11585. var ray1oeZ = ray1o.z;
  11586. var ray1d = ray1.direction;
  11587. var ray1deX = ray1d.x;
  11588. var ray1deY = ray1d.y;
  11589. var ray1deZ = ray1d.z;
  11590. var ray2o = ray2.origin;
  11591. var ray2oeX = ray2o.x;
  11592. var ray2oeY = ray2o.y;
  11593. var ray2oeZ = ray2o.z;
  11594. var ray2d = ray2.direction;
  11595. var ray2deX = ray2d.x;
  11596. var ray2deY = ray2d.y;
  11597. var ray2deZ = ray2d.z;
  11598. Vector3.cross(ray1d, ray2d, CollisionUtils._tempV30);
  11599. var tempV3 = CollisionUtils._tempV30;
  11600. var denominator = Vector3.scalarLength(CollisionUtils._tempV30);
  11601. if (MathUtils3D.isZero(denominator)) {
  11602. if (MathUtils3D.nearEqual(ray2oeX, ray1oeX) && MathUtils3D.nearEqual(ray2oeY, ray1oeY) && MathUtils3D.nearEqual(ray2oeZ, ray1oeZ)) {
  11603. return true;
  11604. }
  11605. }
  11606. denominator = denominator * denominator;
  11607. var m11 = ray2oeX - ray1oeX;
  11608. var m12 = ray2oeY - ray1oeY;
  11609. var m13 = ray2oeZ - ray1oeZ;
  11610. var m21 = ray2deX;
  11611. var m22 = ray2deY;
  11612. var m23 = ray2deZ;
  11613. var m31 = tempV3.x;
  11614. var m32 = tempV3.y;
  11615. var m33 = tempV3.z;
  11616. var dets = m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m11 * m23 * m32 - m12 * m21 * m33 - m13 * m22 * m31;
  11617. m21 = ray1deX;
  11618. m22 = ray1deY;
  11619. m23 = ray1deZ;
  11620. var s = dets / denominator;
  11621. Vector3.scale(ray1d, s, CollisionUtils._tempV30);
  11622. Vector3.scale(ray2d, s, CollisionUtils._tempV31);
  11623. Vector3.add(ray1o, CollisionUtils._tempV30, CollisionUtils._tempV32);
  11624. Vector3.add(ray2o, CollisionUtils._tempV31, CollisionUtils._tempV33);
  11625. var point1e = CollisionUtils._tempV32;
  11626. var point2e = CollisionUtils._tempV33;
  11627. if (!MathUtils3D.nearEqual(point2e.x, point1e.x) || !MathUtils3D.nearEqual(point2e.y, point1e.y) || !MathUtils3D.nearEqual(point2e.z, point1e.z)) {
  11628. return false;
  11629. }
  11630. return true;
  11631. }
  11632. static intersectsPlaneAndTriangle(plane, vertex1, vertex2, vertex3) {
  11633. var test1 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex1);
  11634. var test2 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex2);
  11635. var test3 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex3);
  11636. if (test1 == Plane.PlaneIntersectionType_Front && test2 == Plane.PlaneIntersectionType_Front && test3 == Plane.PlaneIntersectionType_Front)
  11637. return Plane.PlaneIntersectionType_Front;
  11638. if (test1 == Plane.PlaneIntersectionType_Back && test2 == Plane.PlaneIntersectionType_Back && test3 == Plane.PlaneIntersectionType_Back)
  11639. return Plane.PlaneIntersectionType_Back;
  11640. return Plane.PlaneIntersectionType_Intersecting;
  11641. }
  11642. static intersectsRayAndPlaneRD(ray, plane) {
  11643. var planeNor = plane.normal;
  11644. var direction = Vector3.dot(planeNor, ray.direction);
  11645. if (Math.abs(direction) < MathUtils3D.zeroTolerance)
  11646. return -1;
  11647. var position = Vector3.dot(planeNor, ray.origin);
  11648. var distance = (-plane.distance - position) / direction;
  11649. if (distance < 0) {
  11650. if (distance < -MathUtils3D.zeroTolerance)
  11651. return -1;
  11652. distance = 0;
  11653. }
  11654. return distance;
  11655. }
  11656. static intersectsRayAndPlaneRP(ray, plane, out) {
  11657. var distance = CollisionUtils.intersectsRayAndPlaneRD(ray, plane);
  11658. if (distance == -1) {
  11659. out.setValue(0, 0, 0);
  11660. return false;
  11661. }
  11662. var scaDis = CollisionUtils._tempV30;
  11663. Vector3.scale(ray.direction, distance, scaDis);
  11664. Vector3.add(ray.origin, scaDis, out);
  11665. return true;
  11666. }
  11667. static intersectsRayAndBoxRD(ray, box) {
  11668. var rayoe = ray.origin;
  11669. var rayoeX = rayoe.x;
  11670. var rayoeY = rayoe.y;
  11671. var rayoeZ = rayoe.z;
  11672. var rayde = ray.direction;
  11673. var raydeX = rayde.x;
  11674. var raydeY = rayde.y;
  11675. var raydeZ = rayde.z;
  11676. var boxMine = box.min;
  11677. var boxMineX = boxMine.x;
  11678. var boxMineY = boxMine.y;
  11679. var boxMineZ = boxMine.z;
  11680. var boxMaxe = box.max;
  11681. var boxMaxeX = boxMaxe.x;
  11682. var boxMaxeY = boxMaxe.y;
  11683. var boxMaxeZ = boxMaxe.z;
  11684. var out = 0;
  11685. var tmax = MathUtils3D.MaxValue;
  11686. if (MathUtils3D.isZero(raydeX)) {
  11687. if (rayoeX < boxMineX || rayoeX > boxMaxeX) {
  11688. return -1;
  11689. }
  11690. }
  11691. else {
  11692. var inverse = 1 / raydeX;
  11693. var t1 = (boxMineX - rayoeX) * inverse;
  11694. var t2 = (boxMaxeX - rayoeX) * inverse;
  11695. if (t1 > t2) {
  11696. var temp = t1;
  11697. t1 = t2;
  11698. t2 = temp;
  11699. }
  11700. out = Math.max(t1, out);
  11701. tmax = Math.min(t2, tmax);
  11702. if (out > tmax) {
  11703. return -1;
  11704. }
  11705. }
  11706. if (MathUtils3D.isZero(raydeY)) {
  11707. if (rayoeY < boxMineY || rayoeY > boxMaxeY) {
  11708. return -1;
  11709. }
  11710. }
  11711. else {
  11712. var inverse1 = 1 / raydeY;
  11713. var t3 = (boxMineY - rayoeY) * inverse1;
  11714. var t4 = (boxMaxeY - rayoeY) * inverse1;
  11715. if (t3 > t4) {
  11716. var temp1 = t3;
  11717. t3 = t4;
  11718. t4 = temp1;
  11719. }
  11720. out = Math.max(t3, out);
  11721. tmax = Math.min(t4, tmax);
  11722. if (out > tmax) {
  11723. return -1;
  11724. }
  11725. }
  11726. if (MathUtils3D.isZero(raydeZ)) {
  11727. if (rayoeZ < boxMineZ || rayoeZ > boxMaxeZ) {
  11728. return -1;
  11729. }
  11730. }
  11731. else {
  11732. var inverse2 = 1 / raydeZ;
  11733. var t5 = (boxMineZ - rayoeZ) * inverse2;
  11734. var t6 = (boxMaxeZ - rayoeZ) * inverse2;
  11735. if (t5 > t6) {
  11736. var temp2 = t5;
  11737. t5 = t6;
  11738. t6 = temp2;
  11739. }
  11740. out = Math.max(t5, out);
  11741. tmax = Math.min(t6, tmax);
  11742. if (out > tmax) {
  11743. return -1;
  11744. }
  11745. }
  11746. return out;
  11747. }
  11748. static intersectsRayAndBoxRP(ray, box, out) {
  11749. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, box);
  11750. if (distance === -1) {
  11751. Vector3._ZERO.cloneTo(out);
  11752. return distance;
  11753. }
  11754. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  11755. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  11756. CollisionUtils._tempV31.cloneTo(out);
  11757. return distance;
  11758. }
  11759. static intersectsRayAndSphereRD(ray, sphere) {
  11760. var sphereR = sphere.radius;
  11761. Vector3.subtract(ray.origin, sphere.center, CollisionUtils._tempV30);
  11762. var b = Vector3.dot(CollisionUtils._tempV30, ray.direction);
  11763. var c = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30) - (sphereR * sphereR);
  11764. if (c > 0 && b > 0) {
  11765. return -1;
  11766. }
  11767. var discriminant = b * b - c;
  11768. if (discriminant < 0) {
  11769. return -1;
  11770. }
  11771. var distance = -b - Math.sqrt(discriminant);
  11772. if (distance < 0)
  11773. distance = 0;
  11774. return distance;
  11775. }
  11776. static intersectsRayAndSphereRP(ray, sphere, out) {
  11777. var distance = CollisionUtils.intersectsRayAndSphereRD(ray, sphere);
  11778. if (distance === -1) {
  11779. Vector3._ZERO.cloneTo(out);
  11780. return distance;
  11781. }
  11782. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  11783. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  11784. CollisionUtils._tempV31.cloneTo(out);
  11785. return distance;
  11786. }
  11787. static intersectsSphereAndTriangle(sphere, vertex1, vertex2, vertex3) {
  11788. var sphereC = sphere.center;
  11789. var sphereR = sphere.radius;
  11790. CollisionUtils.closestPointPointTriangle(sphereC, vertex1, vertex2, vertex3, CollisionUtils._tempV30);
  11791. Vector3.subtract(CollisionUtils._tempV30, sphereC, CollisionUtils._tempV31);
  11792. var dot = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV31);
  11793. return dot <= sphereR * sphereR;
  11794. }
  11795. static intersectsPlaneAndPoint(plane, point) {
  11796. var distance = Vector3.dot(plane.normal, point) + plane.distance;
  11797. if (distance > 0)
  11798. return Plane.PlaneIntersectionType_Front;
  11799. if (distance < 0)
  11800. return Plane.PlaneIntersectionType_Back;
  11801. return Plane.PlaneIntersectionType_Intersecting;
  11802. }
  11803. static intersectsPlaneAndPlane(plane1, plane2) {
  11804. Vector3.cross(plane1.normal, plane2.normal, CollisionUtils._tempV30);
  11805. var denominator = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30);
  11806. if (MathUtils3D.isZero(denominator))
  11807. return false;
  11808. return true;
  11809. }
  11810. static intersectsPlaneAndPlaneRL(plane1, plane2, line) {
  11811. var plane1nor = plane1.normal;
  11812. var plane2nor = plane2.normal;
  11813. Vector3.cross(plane1nor, plane2nor, CollisionUtils._tempV34);
  11814. var denominator = Vector3.dot(CollisionUtils._tempV34, CollisionUtils._tempV34);
  11815. if (MathUtils3D.isZero(denominator))
  11816. return false;
  11817. Vector3.scale(plane2nor, plane1.distance, CollisionUtils._tempV30);
  11818. Vector3.scale(plane1nor, plane2.distance, CollisionUtils._tempV31);
  11819. Vector3.subtract(CollisionUtils._tempV30, CollisionUtils._tempV31, CollisionUtils._tempV32);
  11820. Vector3.cross(CollisionUtils._tempV32, CollisionUtils._tempV34, CollisionUtils._tempV33);
  11821. Vector3.normalize(CollisionUtils._tempV34, CollisionUtils._tempV34);
  11822. return true;
  11823. }
  11824. static intersectsPlaneAndBox(plane, box) {
  11825. var planeD = plane.distance;
  11826. var planeNor = plane.normal;
  11827. var planeNoreX = planeNor.x;
  11828. var planeNoreY = planeNor.y;
  11829. var planeNoreZ = planeNor.z;
  11830. var boxMine = box.min;
  11831. var boxMineX = boxMine.x;
  11832. var boxMineY = boxMine.y;
  11833. var boxMineZ = boxMine.z;
  11834. var boxMaxe = box.max;
  11835. var boxMaxeX = boxMaxe.x;
  11836. var boxMaxeY = boxMaxe.y;
  11837. var boxMaxeZ = boxMaxe.z;
  11838. CollisionUtils._tempV30.x = (planeNoreX > 0) ? boxMineX : boxMaxeX;
  11839. CollisionUtils._tempV30.y = (planeNoreY > 0) ? boxMineY : boxMaxeY;
  11840. CollisionUtils._tempV30.z = (planeNoreZ > 0) ? boxMineZ : boxMaxeZ;
  11841. CollisionUtils._tempV31.x = (planeNoreX > 0) ? boxMaxeX : boxMineX;
  11842. CollisionUtils._tempV31.y = (planeNoreY > 0) ? boxMaxeY : boxMineY;
  11843. CollisionUtils._tempV31.z = (planeNoreZ > 0) ? boxMaxeZ : boxMineZ;
  11844. var distance = Vector3.dot(planeNor, CollisionUtils._tempV30);
  11845. if (distance + planeD > 0)
  11846. return Plane.PlaneIntersectionType_Front;
  11847. distance = Vector3.dot(planeNor, CollisionUtils._tempV31);
  11848. if (distance + planeD < 0)
  11849. return Plane.PlaneIntersectionType_Back;
  11850. return Plane.PlaneIntersectionType_Intersecting;
  11851. }
  11852. static intersectsPlaneAndSphere(plane, sphere) {
  11853. var sphereR = sphere.radius;
  11854. var distance = Vector3.dot(plane.normal, sphere.center) + plane.distance;
  11855. if (distance > sphereR)
  11856. return Plane.PlaneIntersectionType_Front;
  11857. if (distance < -sphereR)
  11858. return Plane.PlaneIntersectionType_Back;
  11859. return Plane.PlaneIntersectionType_Intersecting;
  11860. }
  11861. static intersectsBoxAndBox(box1, box2) {
  11862. var box1Mine = box1.min;
  11863. var box1Maxe = box1.max;
  11864. var box2Mine = box2.min;
  11865. var box2Maxe = box2.max;
  11866. if (box1Mine.x > box2Maxe.x || box2Mine.x > box1Maxe.x)
  11867. return false;
  11868. if (box1Mine.y > box2Maxe.y || box2Mine.y > box1Maxe.y)
  11869. return false;
  11870. if (box1Mine.z > box2Maxe.z || box2Mine.z > box1Maxe.z)
  11871. return false;
  11872. return true;
  11873. }
  11874. static intersectsBoxAndSphere(box, sphere) {
  11875. var sphereC = sphere.center;
  11876. var sphereR = sphere.radius;
  11877. Vector3.Clamp(sphereC, box.min, box.max, CollisionUtils._tempV30);
  11878. var distance = Vector3.distanceSquared(sphereC, CollisionUtils._tempV30);
  11879. return distance <= sphereR * sphereR;
  11880. }
  11881. static intersectsSphereAndSphere(sphere1, sphere2) {
  11882. var radiisum = sphere1.radius + sphere2.radius;
  11883. return Vector3.distanceSquared(sphere1.center, sphere2.center) <= radiisum * radiisum;
  11884. }
  11885. static boxContainsPoint(box, point) {
  11886. var boxMine = box.min;
  11887. var boxMaxe = box.max;
  11888. if (boxMine.x <= point.x && boxMaxe.x >= point.x && boxMine.y <= point.y && boxMaxe.y >= point.y && boxMine.z <= point.z && boxMaxe.z >= point.z)
  11889. return ContainmentType.Contains;
  11890. return ContainmentType.Disjoint;
  11891. }
  11892. static boxContainsBox(box1, box2) {
  11893. var box1Mine = box1.min;
  11894. var box1MineX = box1Mine.x;
  11895. var box1MineY = box1Mine.y;
  11896. var box1MineZ = box1Mine.z;
  11897. var box1Maxe = box1.max;
  11898. var box1MaxeX = box1Maxe.x;
  11899. var box1MaxeY = box1Maxe.y;
  11900. var box1MaxeZ = box1Maxe.z;
  11901. var box2Mine = box2.min;
  11902. var box2MineX = box2Mine.x;
  11903. var box2MineY = box2Mine.y;
  11904. var box2MineZ = box2Mine.z;
  11905. var box2Maxe = box2.max;
  11906. var box2MaxeX = box2Maxe.x;
  11907. var box2MaxeY = box2Maxe.y;
  11908. var box2MaxeZ = box2Maxe.z;
  11909. if (box1MaxeX < box2MineX || box1MineX > box2MaxeX)
  11910. return ContainmentType.Disjoint;
  11911. if (box1MaxeY < box2MineY || box1MineY > box2MaxeY)
  11912. return ContainmentType.Disjoint;
  11913. if (box1MaxeZ < box2MineZ || box1MineZ > box2MaxeZ)
  11914. return ContainmentType.Disjoint;
  11915. if (box1MineX <= box2MineX && box2MaxeX <= box1MaxeX && box1MineY <= box2MineY && box2MaxeY <= box1MaxeY && box1MineZ <= box2MineZ && box2MaxeZ <= box1MaxeZ) {
  11916. return ContainmentType.Contains;
  11917. }
  11918. return ContainmentType.Intersects;
  11919. }
  11920. static boxContainsSphere(box, sphere) {
  11921. var boxMin = box.min;
  11922. var boxMineX = boxMin.x;
  11923. var boxMineY = boxMin.y;
  11924. var boxMineZ = boxMin.z;
  11925. var boxMax = box.max;
  11926. var boxMaxeX = boxMax.x;
  11927. var boxMaxeY = boxMax.y;
  11928. var boxMaxeZ = boxMax.z;
  11929. var sphereC = sphere.center;
  11930. var sphereCeX = sphereC.x;
  11931. var sphereCeY = sphereC.y;
  11932. var sphereCeZ = sphereC.z;
  11933. var sphereR = sphere.radius;
  11934. Vector3.Clamp(sphereC, boxMin, boxMax, CollisionUtils._tempV30);
  11935. var distance = Vector3.distanceSquared(sphereC, CollisionUtils._tempV30);
  11936. if (distance > sphereR * sphereR)
  11937. return ContainmentType.Disjoint;
  11938. if ((((boxMineX + sphereR <= sphereCeX) && (sphereCeX <= boxMaxeX - sphereR)) && ((boxMaxeX - boxMineX > sphereR) &&
  11939. (boxMineY + sphereR <= sphereCeY))) && (((sphereCeY <= boxMaxeY - sphereR) && (boxMaxeY - boxMineY > sphereR)) &&
  11940. (((boxMineZ + sphereR <= sphereCeZ) && (sphereCeZ <= boxMaxeZ - sphereR)) && (boxMaxeZ - boxMineZ > sphereR))))
  11941. return ContainmentType.Contains;
  11942. return ContainmentType.Intersects;
  11943. }
  11944. static sphereContainsPoint(sphere, point) {
  11945. if (Vector3.distanceSquared(point, sphere.center) <= sphere.radius * sphere.radius)
  11946. return ContainmentType.Contains;
  11947. return ContainmentType.Disjoint;
  11948. }
  11949. static sphereContainsTriangle(sphere, vertex1, vertex2, vertex3) {
  11950. var test1 = CollisionUtils.sphereContainsPoint(sphere, vertex1);
  11951. var test2 = CollisionUtils.sphereContainsPoint(sphere, vertex2);
  11952. var test3 = CollisionUtils.sphereContainsPoint(sphere, vertex3);
  11953. if (test1 == ContainmentType.Contains && test2 == ContainmentType.Contains && test3 == ContainmentType.Contains)
  11954. return ContainmentType.Contains;
  11955. if (CollisionUtils.intersectsSphereAndTriangle(sphere, vertex1, vertex2, vertex3))
  11956. return ContainmentType.Intersects;
  11957. return ContainmentType.Disjoint;
  11958. }
  11959. static sphereContainsBox(sphere, box) {
  11960. var sphereC = sphere.center;
  11961. var sphereCeX = sphereC.x;
  11962. var sphereCeY = sphereC.y;
  11963. var sphereCeZ = sphereC.z;
  11964. var sphereR = sphere.radius;
  11965. var boxMin = box.min;
  11966. var boxMineX = boxMin.x;
  11967. var boxMineY = boxMin.y;
  11968. var boxMineZ = boxMin.z;
  11969. var boxMax = box.max;
  11970. var boxMaxeX = boxMax.x;
  11971. var boxMaxeY = boxMax.y;
  11972. var boxMaxeZ = boxMax.z;
  11973. var _tempV30e = CollisionUtils._tempV30;
  11974. var _tempV30eX = _tempV30e.x;
  11975. var _tempV30eY = _tempV30e.y;
  11976. var _tempV30eZ = _tempV30e.z;
  11977. if (!CollisionUtils.intersectsBoxAndSphere(box, sphere))
  11978. return ContainmentType.Disjoint;
  11979. var radiusSquared = sphereR * sphereR;
  11980. _tempV30eX = sphereCeX - boxMineX;
  11981. _tempV30eY = sphereCeY - boxMaxeY;
  11982. _tempV30eZ = sphereCeZ - boxMaxeZ;
  11983. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11984. return ContainmentType.Intersects;
  11985. _tempV30eX = sphereCeX - boxMaxeX;
  11986. _tempV30eY = sphereCeY - boxMaxeY;
  11987. _tempV30eZ = sphereCeZ - boxMaxeZ;
  11988. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11989. return ContainmentType.Intersects;
  11990. _tempV30eX = sphereCeX - boxMaxeX;
  11991. _tempV30eY = sphereCeY - boxMineY;
  11992. _tempV30eZ = sphereCeZ - boxMaxeZ;
  11993. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11994. return ContainmentType.Intersects;
  11995. _tempV30eX = sphereCeX - boxMineX;
  11996. _tempV30eY = sphereCeY - boxMineY;
  11997. _tempV30eZ = sphereCeZ - boxMaxeZ;
  11998. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  11999. return ContainmentType.Intersects;
  12000. _tempV30eX = sphereCeX - boxMineX;
  12001. _tempV30eY = sphereCeY - boxMaxeY;
  12002. _tempV30eZ = sphereCeZ - boxMineZ;
  12003. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12004. return ContainmentType.Intersects;
  12005. _tempV30eX = sphereCeX - boxMaxeX;
  12006. _tempV30eY = sphereCeY - boxMaxeY;
  12007. _tempV30eZ = sphereCeZ - boxMineZ;
  12008. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12009. return ContainmentType.Intersects;
  12010. _tempV30eX = sphereCeX - boxMaxeX;
  12011. _tempV30eY = sphereCeY - boxMineY;
  12012. _tempV30eZ = sphereCeZ - boxMineZ;
  12013. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12014. return ContainmentType.Intersects;
  12015. _tempV30eX = sphereCeX - boxMineX;
  12016. _tempV30eY = sphereCeY - boxMineY;
  12017. _tempV30eZ = sphereCeZ - boxMineZ;
  12018. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12019. return ContainmentType.Intersects;
  12020. return ContainmentType.Contains;
  12021. }
  12022. static sphereContainsSphere(sphere1, sphere2) {
  12023. var sphere1R = sphere1.radius;
  12024. var sphere2R = sphere2.radius;
  12025. var distance = Vector3.distance(sphere1.center, sphere2.center);
  12026. if (sphere1R + sphere2R < distance)
  12027. return ContainmentType.Disjoint;
  12028. if (sphere1R - sphere2R < distance)
  12029. return ContainmentType.Intersects;
  12030. return ContainmentType.Contains;
  12031. }
  12032. static closestPointPointTriangle(point, vertex1, vertex2, vertex3, out) {
  12033. Vector3.subtract(vertex2, vertex1, CollisionUtils._tempV30);
  12034. Vector3.subtract(vertex3, vertex1, CollisionUtils._tempV31);
  12035. Vector3.subtract(point, vertex1, CollisionUtils._tempV32);
  12036. Vector3.subtract(point, vertex2, CollisionUtils._tempV33);
  12037. Vector3.subtract(point, vertex3, CollisionUtils._tempV34);
  12038. var d1 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV32);
  12039. var d2 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV32);
  12040. var d3 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV33);
  12041. var d4 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV33);
  12042. var d5 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV34);
  12043. var d6 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV34);
  12044. if (d1 <= 0 && d2 <= 0) {
  12045. vertex1.cloneTo(out);
  12046. return;
  12047. }
  12048. if (d3 >= 0 && d4 <= d3) {
  12049. vertex2.cloneTo(out);
  12050. return;
  12051. }
  12052. var vc = d1 * d4 - d3 * d2;
  12053. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  12054. var v = d1 / (d1 - d3);
  12055. Vector3.scale(CollisionUtils._tempV30, v, out);
  12056. Vector3.add(vertex1, out, out);
  12057. return;
  12058. }
  12059. if (d6 >= 0 && d5 <= d6) {
  12060. vertex3.cloneTo(out);
  12061. return;
  12062. }
  12063. var vb = d5 * d2 - d1 * d6;
  12064. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  12065. var w = d2 / (d2 - d6);
  12066. Vector3.scale(CollisionUtils._tempV31, w, out);
  12067. Vector3.add(vertex1, out, out);
  12068. return;
  12069. }
  12070. var va = d3 * d6 - d5 * d4;
  12071. if (va <= 0 && (d4 - d3) >= 0 && (d5 - d6) >= 0) {
  12072. var w3 = (d4 - d3) / ((d4 - d3) + (d5 - d6));
  12073. Vector3.subtract(vertex3, vertex2, out);
  12074. Vector3.scale(out, w3, out);
  12075. Vector3.add(vertex2, out, out);
  12076. return;
  12077. }
  12078. var denom = 1 / (va + vb + vc);
  12079. var v2 = vb * denom;
  12080. var w2 = vc * denom;
  12081. Vector3.scale(CollisionUtils._tempV30, v2, CollisionUtils._tempV35);
  12082. Vector3.scale(CollisionUtils._tempV31, w2, CollisionUtils._tempV36);
  12083. Vector3.add(CollisionUtils._tempV35, CollisionUtils._tempV36, out);
  12084. Vector3.add(vertex1, out, out);
  12085. }
  12086. static closestPointPlanePoint(plane, point, out) {
  12087. var planeN = plane.normal;
  12088. var t = Vector3.dot(planeN, point) - plane.distance;
  12089. Vector3.scale(planeN, t, CollisionUtils._tempV30);
  12090. Vector3.subtract(point, CollisionUtils._tempV30, out);
  12091. }
  12092. static closestPointBoxPoint(box, point, out) {
  12093. Vector3.max(point, box.min, CollisionUtils._tempV30);
  12094. Vector3.min(CollisionUtils._tempV30, box.max, out);
  12095. }
  12096. static closestPointSpherePoint(sphere, point, out) {
  12097. var sphereC = sphere.center;
  12098. Vector3.subtract(point, sphereC, out);
  12099. Vector3.normalize(out, out);
  12100. Vector3.scale(out, sphere.radius, out);
  12101. Vector3.add(out, sphereC, out);
  12102. }
  12103. static closestPointSphereSphere(sphere1, sphere2, out) {
  12104. var sphere1C = sphere1.center;
  12105. Vector3.subtract(sphere2.center, sphere1C, out);
  12106. Vector3.normalize(out, out);
  12107. Vector3.scale(out, sphere1.radius, out);
  12108. Vector3.add(out, sphere1C, out);
  12109. }
  12110. }
  12111. CollisionUtils._tempV30 = new Vector3();
  12112. CollisionUtils._tempV31 = new Vector3();
  12113. CollisionUtils._tempV32 = new Vector3();
  12114. CollisionUtils._tempV33 = new Vector3();
  12115. CollisionUtils._tempV34 = new Vector3();
  12116. CollisionUtils._tempV35 = new Vector3();
  12117. CollisionUtils._tempV36 = new Vector3();
  12118. class BoundFrustum {
  12119. constructor(matrix) {
  12120. this._matrix = matrix;
  12121. this._near = new Plane(new Vector3());
  12122. this._far = new Plane(new Vector3());
  12123. this._left = new Plane(new Vector3());
  12124. this._right = new Plane(new Vector3());
  12125. this._top = new Plane(new Vector3());
  12126. this._bottom = new Plane(new Vector3());
  12127. BoundFrustum._getPlanesFromMatrix(this._matrix, this._near, this._far, this._left, this._right, this._top, this._bottom);
  12128. }
  12129. get matrix() {
  12130. return this._matrix;
  12131. }
  12132. set matrix(matrix) {
  12133. this._matrix = matrix;
  12134. BoundFrustum._getPlanesFromMatrix(this._matrix, this._near, this._far, this._left, this._right, this._top, this._bottom);
  12135. }
  12136. get near() {
  12137. return this._near;
  12138. }
  12139. get far() {
  12140. return this._far;
  12141. }
  12142. get left() {
  12143. return this._left;
  12144. }
  12145. get right() {
  12146. return this._right;
  12147. }
  12148. get top() {
  12149. return this._top;
  12150. }
  12151. get bottom() {
  12152. return this._bottom;
  12153. }
  12154. equalsBoundFrustum(other) {
  12155. return this._matrix.equalsOtherMatrix(other.matrix);
  12156. }
  12157. equalsObj(obj) {
  12158. if (obj instanceof BoundFrustum) {
  12159. var bf = obj;
  12160. return this.equalsBoundFrustum(bf);
  12161. }
  12162. return false;
  12163. }
  12164. getPlane(index) {
  12165. switch (index) {
  12166. case 0:
  12167. return this._near;
  12168. case 1:
  12169. return this._far;
  12170. case 2:
  12171. return this._left;
  12172. case 3:
  12173. return this._right;
  12174. case 4:
  12175. return this._top;
  12176. case 5:
  12177. return this._bottom;
  12178. default:
  12179. return null;
  12180. }
  12181. }
  12182. static _getPlanesFromMatrix(m, np, fp, lp, rp, tp, bp) {
  12183. var matrixE = m.elements;
  12184. var m11 = matrixE[0];
  12185. var m12 = matrixE[1];
  12186. var m13 = matrixE[2];
  12187. var m14 = matrixE[3];
  12188. var m21 = matrixE[4];
  12189. var m22 = matrixE[5];
  12190. var m23 = matrixE[6];
  12191. var m24 = matrixE[7];
  12192. var m31 = matrixE[8];
  12193. var m32 = matrixE[9];
  12194. var m33 = matrixE[10];
  12195. var m34 = matrixE[11];
  12196. var m41 = matrixE[12];
  12197. var m42 = matrixE[13];
  12198. var m43 = matrixE[14];
  12199. var m44 = matrixE[15];
  12200. var nearNorE = np.normal;
  12201. nearNorE.x = m14 + m13;
  12202. nearNorE.y = m24 + m23;
  12203. nearNorE.z = m34 + m33;
  12204. np.distance = m44 + m43;
  12205. np.normalize();
  12206. var farNorE = fp.normal;
  12207. farNorE.x = m14 - m13;
  12208. farNorE.y = m24 - m23;
  12209. farNorE.z = m34 - m33;
  12210. fp.distance = m44 - m43;
  12211. fp.normalize();
  12212. var leftNorE = lp.normal;
  12213. leftNorE.x = m14 + m11;
  12214. leftNorE.y = m24 + m21;
  12215. leftNorE.z = m34 + m31;
  12216. lp.distance = m44 + m41;
  12217. lp.normalize();
  12218. var rightNorE = rp.normal;
  12219. rightNorE.x = m14 - m11;
  12220. rightNorE.y = m24 - m21;
  12221. rightNorE.z = m34 - m31;
  12222. rp.distance = m44 - m41;
  12223. rp.normalize();
  12224. var topNorE = tp.normal;
  12225. topNorE.x = m14 - m12;
  12226. topNorE.y = m24 - m22;
  12227. topNorE.z = m34 - m32;
  12228. tp.distance = m44 - m42;
  12229. tp.normalize();
  12230. var bottomNorE = bp.normal;
  12231. bottomNorE.x = m14 + m12;
  12232. bottomNorE.y = m24 + m22;
  12233. bottomNorE.z = m34 + m32;
  12234. bp.distance = m44 + m42;
  12235. bp.normalize();
  12236. }
  12237. static _get3PlaneInterPoint(p1, p2, p3) {
  12238. var p1Nor = p1.normal;
  12239. var p2Nor = p2.normal;
  12240. var p3Nor = p3.normal;
  12241. Vector3.cross(p2Nor, p3Nor, BoundFrustum._tempV30);
  12242. Vector3.cross(p3Nor, p1Nor, BoundFrustum._tempV31);
  12243. Vector3.cross(p1Nor, p2Nor, BoundFrustum._tempV32);
  12244. var a = Vector3.dot(p1Nor, BoundFrustum._tempV30);
  12245. var b = Vector3.dot(p2Nor, BoundFrustum._tempV31);
  12246. var c = Vector3.dot(p3Nor, BoundFrustum._tempV32);
  12247. Vector3.scale(BoundFrustum._tempV30, -p1.distance / a, BoundFrustum._tempV33);
  12248. Vector3.scale(BoundFrustum._tempV31, -p2.distance / b, BoundFrustum._tempV34);
  12249. Vector3.scale(BoundFrustum._tempV32, -p3.distance / c, BoundFrustum._tempV35);
  12250. Vector3.add(BoundFrustum._tempV33, BoundFrustum._tempV34, BoundFrustum._tempV36);
  12251. Vector3.add(BoundFrustum._tempV35, BoundFrustum._tempV36, BoundFrustum._tempV37);
  12252. var v = BoundFrustum._tempV37;
  12253. return v;
  12254. }
  12255. getCorners(corners) {
  12256. BoundFrustum._get3PlaneInterPoint(this._near, this._bottom, this._right).cloneTo(corners[0]);
  12257. BoundFrustum._get3PlaneInterPoint(this._near, this._top, this._right).cloneTo(corners[1]);
  12258. BoundFrustum._get3PlaneInterPoint(this._near, this._top, this._left).cloneTo(corners[2]);
  12259. BoundFrustum._get3PlaneInterPoint(this._near, this._bottom, this._left).cloneTo(corners[3]);
  12260. BoundFrustum._get3PlaneInterPoint(this._far, this._bottom, this._right).cloneTo(corners[4]);
  12261. BoundFrustum._get3PlaneInterPoint(this._far, this._top, this._right).cloneTo(corners[5]);
  12262. BoundFrustum._get3PlaneInterPoint(this._far, this._top, this._left).cloneTo(corners[6]);
  12263. BoundFrustum._get3PlaneInterPoint(this._far, this._bottom, this._left).cloneTo(corners[7]);
  12264. }
  12265. containsPoint(point) {
  12266. var result = Plane.PlaneIntersectionType_Front;
  12267. var planeResult = Plane.PlaneIntersectionType_Front;
  12268. for (var i = 0; i < 6; i++) {
  12269. switch (i) {
  12270. case 0:
  12271. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._near, point);
  12272. break;
  12273. case 1:
  12274. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._far, point);
  12275. break;
  12276. case 2:
  12277. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._left, point);
  12278. break;
  12279. case 3:
  12280. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._right, point);
  12281. break;
  12282. case 4:
  12283. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._top, point);
  12284. break;
  12285. case 5:
  12286. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._bottom, point);
  12287. break;
  12288. }
  12289. switch (planeResult) {
  12290. case Plane.PlaneIntersectionType_Back:
  12291. return ContainmentType.Disjoint;
  12292. case Plane.PlaneIntersectionType_Intersecting:
  12293. result = Plane.PlaneIntersectionType_Intersecting;
  12294. break;
  12295. }
  12296. }
  12297. switch (result) {
  12298. case Plane.PlaneIntersectionType_Intersecting:
  12299. return ContainmentType.Intersects;
  12300. default:
  12301. return ContainmentType.Contains;
  12302. }
  12303. }
  12304. intersects(box) {
  12305. var min = box.min;
  12306. var max = box.max;
  12307. var minX = min.x;
  12308. var minY = min.y;
  12309. var minZ = min.z;
  12310. var maxX = max.x;
  12311. var maxY = max.y;
  12312. var maxZ = max.z;
  12313. var nearNormal = this._near.normal;
  12314. if (this._near.distance + (nearNormal.x * (nearNormal.x < 0 ? minX : maxX)) + (nearNormal.y * (nearNormal.y < 0 ? minY : maxY)) + (nearNormal.z * (nearNormal.z < 0 ? minZ : maxZ)) < 0)
  12315. return false;
  12316. var leftNormal = this._left.normal;
  12317. if (this._left.distance + (leftNormal.x * (leftNormal.x < 0 ? minX : maxX)) + (leftNormal.y * (leftNormal.y < 0 ? minY : maxY)) + (leftNormal.z * (leftNormal.z < 0 ? minZ : maxZ)) < 0)
  12318. return false;
  12319. var rightNormal = this._right.normal;
  12320. if (this._right.distance + (rightNormal.x * (rightNormal.x < 0 ? minX : maxX)) + (rightNormal.y * (rightNormal.y < 0 ? minY : maxY)) + (rightNormal.z * (rightNormal.z < 0 ? minZ : maxZ)) < 0)
  12321. return false;
  12322. var bottomNormal = this._bottom.normal;
  12323. if (this._bottom.distance + (bottomNormal.x * (bottomNormal.x < 0 ? minX : maxX)) + (bottomNormal.y * (bottomNormal.y < 0 ? minY : maxY)) + (bottomNormal.z * (bottomNormal.z < 0 ? minZ : maxZ)) < 0)
  12324. return false;
  12325. var topNormal = this._top.normal;
  12326. if (this._top.distance + (topNormal.x * (topNormal.x < 0 ? minX : maxX)) + (topNormal.y * (topNormal.y < 0 ? minY : maxY)) + (topNormal.z * (topNormal.z < 0 ? minZ : maxZ)) < 0)
  12327. return false;
  12328. var farNormal = this._far.normal;
  12329. if (this._far.distance + (farNormal.x * (farNormal.x < 0 ? minX : maxX)) + (farNormal.y * (farNormal.y < 0 ? minY : maxY)) + (farNormal.z * (farNormal.z < 0 ? minZ : maxZ)) < 0)
  12330. return false;
  12331. return true;
  12332. }
  12333. containsBoundBox(box) {
  12334. var p = BoundFrustum._tempV30, n = BoundFrustum._tempV31;
  12335. var boxMin = box.min;
  12336. var boxMax = box.max;
  12337. var result = ContainmentType.Contains;
  12338. for (var i = 0; i < 6; i++) {
  12339. var plane = this.getPlane(i);
  12340. var planeNor = plane.normal;
  12341. if (planeNor.x >= 0) {
  12342. p.x = boxMax.x;
  12343. n.x = boxMin.x;
  12344. }
  12345. else {
  12346. p.x = boxMin.x;
  12347. n.x = boxMax.x;
  12348. }
  12349. if (planeNor.y >= 0) {
  12350. p.y = boxMax.y;
  12351. n.y = boxMin.y;
  12352. }
  12353. else {
  12354. p.y = boxMin.y;
  12355. n.y = boxMax.y;
  12356. }
  12357. if (planeNor.z >= 0) {
  12358. p.z = boxMax.z;
  12359. n.z = boxMin.z;
  12360. }
  12361. else {
  12362. p.z = boxMin.z;
  12363. n.z = boxMax.z;
  12364. }
  12365. if (CollisionUtils.intersectsPlaneAndPoint(plane, p) === Plane.PlaneIntersectionType_Back)
  12366. return ContainmentType.Disjoint;
  12367. if (CollisionUtils.intersectsPlaneAndPoint(plane, n) === Plane.PlaneIntersectionType_Back)
  12368. result = ContainmentType.Intersects;
  12369. }
  12370. return result;
  12371. }
  12372. containsBoundSphere(sphere) {
  12373. var result = Plane.PlaneIntersectionType_Front;
  12374. var planeResult = Plane.PlaneIntersectionType_Front;
  12375. for (var i = 0; i < 6; i++) {
  12376. switch (i) {
  12377. case 0:
  12378. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._near, sphere);
  12379. break;
  12380. case 1:
  12381. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._far, sphere);
  12382. break;
  12383. case 2:
  12384. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._left, sphere);
  12385. break;
  12386. case 3:
  12387. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._right, sphere);
  12388. break;
  12389. case 4:
  12390. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._top, sphere);
  12391. break;
  12392. case 5:
  12393. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._bottom, sphere);
  12394. break;
  12395. }
  12396. switch (planeResult) {
  12397. case Plane.PlaneIntersectionType_Back:
  12398. return ContainmentType.Disjoint;
  12399. case Plane.PlaneIntersectionType_Intersecting:
  12400. result = Plane.PlaneIntersectionType_Intersecting;
  12401. break;
  12402. }
  12403. }
  12404. switch (result) {
  12405. case Plane.PlaneIntersectionType_Intersecting:
  12406. return ContainmentType.Intersects;
  12407. default:
  12408. return ContainmentType.Contains;
  12409. }
  12410. }
  12411. }
  12412. BoundFrustum._tempV30 = new Vector3();
  12413. BoundFrustum._tempV31 = new Vector3();
  12414. BoundFrustum._tempV32 = new Vector3();
  12415. BoundFrustum._tempV33 = new Vector3();
  12416. BoundFrustum._tempV34 = new Vector3();
  12417. BoundFrustum._tempV35 = new Vector3();
  12418. BoundFrustum._tempV36 = new Vector3();
  12419. BoundFrustum._tempV37 = new Vector3();
  12420. class Viewport {
  12421. constructor(x, y, width, height) {
  12422. this.minDepth = 0.0;
  12423. this.maxDepth = 1.0;
  12424. this.x = x;
  12425. this.y = y;
  12426. this.width = width;
  12427. this.height = height;
  12428. }
  12429. project(source, matrix, out) {
  12430. var sX = source.x;
  12431. var sY = source.y;
  12432. var sZ = source.z;
  12433. Vector3.transformV3ToV3(source, matrix, out);
  12434. var matE = matrix.elements;
  12435. var a = (((sX * matE[3]) + (sY * matE[7])) + (sZ * matE[11])) + matE[15];
  12436. if (a !== 1.0) {
  12437. out.x = out.x / a;
  12438. out.y = out.y / a;
  12439. out.z = out.z / a;
  12440. }
  12441. out.x = (((out.x + 1.0) * 0.5) * this.width) + this.x;
  12442. out.y = (((-out.y + 1.0) * 0.5) * this.height) + this.y;
  12443. out.z = (out.z * (this.maxDepth - this.minDepth)) + this.minDepth;
  12444. }
  12445. unprojectFromMat(source, matrix, out) {
  12446. var matrixEleme = matrix.elements;
  12447. out.x = (((source.x - this.x) / (this.width)) * 2.0) - 1.0;
  12448. out.y = -((((source.y - this.y) / (this.height)) * 2.0) - 1.0);
  12449. var halfDepth = (this.maxDepth - this.minDepth) / 2;
  12450. out.z = (source.z - this.minDepth - halfDepth) / halfDepth;
  12451. var a = (((out.x * matrixEleme[3]) + (out.y * matrixEleme[7])) + (out.z * matrixEleme[11])) + matrixEleme[15];
  12452. Vector3.transformV3ToV3(out, matrix, out);
  12453. if (a !== 1.0) {
  12454. out.x = out.x / a;
  12455. out.y = out.y / a;
  12456. out.z = out.z / a;
  12457. }
  12458. }
  12459. unprojectFromWVP(source, projection, view, world, out) {
  12460. Matrix4x4.multiply(projection, view, Viewport._tempMatrix4x4);
  12461. (world) && (Matrix4x4.multiply(Viewport._tempMatrix4x4, world, Viewport._tempMatrix4x4));
  12462. Viewport._tempMatrix4x4.invert(Viewport._tempMatrix4x4);
  12463. this.unprojectFromMat(source, Viewport._tempMatrix4x4, out);
  12464. }
  12465. cloneTo(out) {
  12466. out.x = this.x;
  12467. out.y = this.y;
  12468. out.width = this.width;
  12469. out.height = this.height;
  12470. out.minDepth = this.minDepth;
  12471. out.maxDepth = this.maxDepth;
  12472. }
  12473. }
  12474. Viewport._tempMatrix4x4 = new Matrix4x4();
  12475. class Picker {
  12476. constructor() {
  12477. }
  12478. static calculateCursorRay(point, viewPort, projectionMatrix, viewMatrix, world, out) {
  12479. var x = point.x;
  12480. var y = point.y;
  12481. var nearSource = Picker._tempVector30;
  12482. var nerSourceE = nearSource;
  12483. nerSourceE.x = x;
  12484. nerSourceE.y = y;
  12485. nerSourceE.z = viewPort.minDepth;
  12486. var farSource = Picker._tempVector31;
  12487. var farSourceE = farSource;
  12488. farSourceE.x = x;
  12489. farSourceE.y = y;
  12490. farSourceE.z = viewPort.maxDepth;
  12491. var nearPoint = out.origin;
  12492. var farPoint = Picker._tempVector32;
  12493. viewPort.unprojectFromWVP(nearSource, projectionMatrix, viewMatrix, world, nearPoint);
  12494. viewPort.unprojectFromWVP(farSource, projectionMatrix, viewMatrix, world, farPoint);
  12495. var outDire = out.direction;
  12496. outDire.x = farPoint.x - nearPoint.x;
  12497. outDire.y = farPoint.y - nearPoint.y;
  12498. outDire.z = farPoint.z - nearPoint.z;
  12499. Vector3.normalize(out.direction, out.direction);
  12500. }
  12501. static rayIntersectsTriangle(ray, vertex1, vertex2, vertex3) {
  12502. var result;
  12503. var edge1 = Picker._tempVector30, edge2 = Picker._tempVector31;
  12504. Vector3.subtract(vertex2, vertex1, edge1);
  12505. Vector3.subtract(vertex3, vertex1, edge2);
  12506. var directionCrossEdge2 = Picker._tempVector32;
  12507. Vector3.cross(ray.direction, edge2, directionCrossEdge2);
  12508. var determinant;
  12509. determinant = Vector3.dot(edge1, directionCrossEdge2);
  12510. if (determinant > -Number.MIN_VALUE && determinant < Number.MIN_VALUE) {
  12511. result = Number.NaN;
  12512. return result;
  12513. }
  12514. var inverseDeterminant = 1.0 / determinant;
  12515. var distanceVector = Picker._tempVector33;
  12516. Vector3.subtract(ray.origin, vertex1, distanceVector);
  12517. var triangleU;
  12518. triangleU = Vector3.dot(distanceVector, directionCrossEdge2);
  12519. triangleU *= inverseDeterminant;
  12520. if (triangleU < 0 || triangleU > 1) {
  12521. result = Number.NaN;
  12522. return result;
  12523. }
  12524. var distanceCrossEdge1 = Picker._tempVector34;
  12525. Vector3.cross(distanceVector, edge1, distanceCrossEdge1);
  12526. var triangleV;
  12527. triangleV = Vector3.dot(ray.direction, distanceCrossEdge1);
  12528. triangleV *= inverseDeterminant;
  12529. if (triangleV < 0 || triangleU + triangleV > 1) {
  12530. result = Number.NaN;
  12531. return result;
  12532. }
  12533. var rayDistance;
  12534. rayDistance = Vector3.dot(edge2, distanceCrossEdge1);
  12535. rayDistance *= inverseDeterminant;
  12536. if (rayDistance < 0) {
  12537. result = Number.NaN;
  12538. return result;
  12539. }
  12540. result = rayDistance;
  12541. return result;
  12542. }
  12543. }
  12544. Picker._tempVector30 = new Vector3();
  12545. Picker._tempVector31 = new Vector3();
  12546. Picker._tempVector32 = new Vector3();
  12547. Picker._tempVector33 = new Vector3();
  12548. Picker._tempVector34 = new Vector3();
  12549. class SystemUtils {
  12550. static supportTextureFormat(format) {
  12551. switch (format) {
  12552. case Laya.TextureFormat.R32G32B32A32:
  12553. if (!Laya.LayaGL.layaGPUInstance._isWebGL2 && !Laya.LayaGL.layaGPUInstance._oesTextureFloat)
  12554. return false;
  12555. else
  12556. return true;
  12557. default:
  12558. return true;
  12559. }
  12560. }
  12561. static supportRenderTextureFormat(format) {
  12562. switch (format) {
  12563. case Laya.RenderTextureFormat.R16G16B16A16:
  12564. if (Laya.LayaGL.layaGPUInstance._isWebGL2 || Laya.LayaGL.layaGPUInstance._oesTextureHalfFloat && Laya.LayaGL.layaGPUInstance._oesTextureHalfFloatLinear)
  12565. return true;
  12566. else
  12567. return false;
  12568. default:
  12569. return true;
  12570. }
  12571. }
  12572. }
  12573. class BufferState extends Laya.BufferStateBase {
  12574. constructor() {
  12575. super();
  12576. }
  12577. applyVertexBuffer(vertexBuffer) {
  12578. if (Laya.BufferStateBase._curBindedBufferState === this) {
  12579. var gl = Laya.LayaGL.instance;
  12580. var verDec = vertexBuffer.vertexDeclaration;
  12581. var valueData = verDec._shaderValues.getData();
  12582. this.vertexDeclaration = verDec;
  12583. vertexBuffer.bind();
  12584. for (var k in valueData) {
  12585. var loc = parseInt(k);
  12586. var attribute = valueData[k];
  12587. gl.enableVertexAttribArray(loc);
  12588. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  12589. }
  12590. }
  12591. else {
  12592. throw "BufferState: must call bind() function first.";
  12593. }
  12594. }
  12595. applyVertexBuffers(vertexBuffers) {
  12596. if (Laya.BufferStateBase._curBindedBufferState === this) {
  12597. var gl = Laya.LayaGL.instance;
  12598. for (var i = 0, n = vertexBuffers.length; i < n; i++) {
  12599. var verBuf = vertexBuffers[i];
  12600. var verDec = verBuf.vertexDeclaration;
  12601. var valueData = verDec._shaderValues.getData();
  12602. verBuf.bind();
  12603. for (var k in valueData) {
  12604. var loc = parseInt(k);
  12605. var attribute = valueData[k];
  12606. gl.enableVertexAttribArray(loc);
  12607. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  12608. }
  12609. }
  12610. }
  12611. else {
  12612. throw "BufferState: must call bind() function first.";
  12613. }
  12614. }
  12615. applyInstanceVertexBuffer(vertexBuffer) {
  12616. if (Laya.LayaGL.layaGPUInstance.supportInstance()) {
  12617. if (Laya.BufferStateBase._curBindedBufferState === this) {
  12618. var gl = Laya.LayaGL.instance;
  12619. var verDec = vertexBuffer.vertexDeclaration;
  12620. var valueData = verDec._shaderValues.getData();
  12621. vertexBuffer.bind();
  12622. for (var k in valueData) {
  12623. var loc = parseInt(k);
  12624. var attribute = valueData[k];
  12625. gl.enableVertexAttribArray(loc);
  12626. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  12627. Laya.LayaGL.layaGPUInstance.vertexAttribDivisor(loc, 1);
  12628. }
  12629. }
  12630. else {
  12631. throw "BufferState: must call bind() function first.";
  12632. }
  12633. }
  12634. }
  12635. applyIndexBuffer(indexBuffer) {
  12636. if (Laya.BufferStateBase._curBindedBufferState === this) {
  12637. if (this._bindedIndexBuffer !== indexBuffer) {
  12638. indexBuffer._bindForVAO();
  12639. this._bindedIndexBuffer = indexBuffer;
  12640. }
  12641. }
  12642. else {
  12643. throw "BufferState: must call bind() function first.";
  12644. }
  12645. }
  12646. }
  12647. (function (IndexFormat) {
  12648. IndexFormat[IndexFormat["UInt8"] = 0] = "UInt8";
  12649. IndexFormat[IndexFormat["UInt16"] = 1] = "UInt16";
  12650. IndexFormat[IndexFormat["UInt32"] = 2] = "UInt32";
  12651. })(exports.IndexFormat || (exports.IndexFormat = {}));
  12652. class IndexBuffer3D extends Laya.Buffer {
  12653. get indexType() {
  12654. return this._indexType;
  12655. }
  12656. get indexTypeByteCount() {
  12657. return this._indexTypeByteCount;
  12658. }
  12659. get indexCount() {
  12660. return this._indexCount;
  12661. }
  12662. get canRead() {
  12663. return this._canRead;
  12664. }
  12665. constructor(indexType, indexCount, bufferUsage = 0x88E4, canRead = false) {
  12666. super();
  12667. this._indexType = indexType;
  12668. this._indexCount = indexCount;
  12669. this._bufferUsage = bufferUsage;
  12670. this._bufferType = Laya.LayaGL.instance.ELEMENT_ARRAY_BUFFER;
  12671. this._canRead = canRead;
  12672. switch (indexType) {
  12673. case exports.IndexFormat.UInt32:
  12674. this._indexTypeByteCount = 4;
  12675. break;
  12676. case exports.IndexFormat.UInt16:
  12677. this._indexTypeByteCount = 2;
  12678. break;
  12679. case exports.IndexFormat.UInt8:
  12680. this._indexTypeByteCount = 1;
  12681. break;
  12682. default:
  12683. throw new Error("unidentification index type.");
  12684. }
  12685. var byteLength = this._indexTypeByteCount * indexCount;
  12686. var curBufSta = Laya.BufferStateBase._curBindedBufferState;
  12687. this._byteLength = byteLength;
  12688. if (curBufSta) {
  12689. if (curBufSta._bindedIndexBuffer === this) {
  12690. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  12691. }
  12692. else {
  12693. curBufSta.unBind();
  12694. this.bind();
  12695. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  12696. curBufSta.bind();
  12697. }
  12698. }
  12699. else {
  12700. this.bind();
  12701. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  12702. }
  12703. if (canRead) {
  12704. switch (indexType) {
  12705. case exports.IndexFormat.UInt32:
  12706. this._buffer = new Uint32Array(indexCount);
  12707. break;
  12708. case exports.IndexFormat.UInt16:
  12709. this._buffer = new Uint16Array(indexCount);
  12710. break;
  12711. case exports.IndexFormat.UInt8:
  12712. this._buffer = new Uint8Array(indexCount);
  12713. break;
  12714. }
  12715. }
  12716. }
  12717. _bindForVAO() {
  12718. if (Laya.BufferStateBase._curBindedBufferState) {
  12719. var gl = Laya.LayaGL.instance;
  12720. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
  12721. }
  12722. else {
  12723. throw "IndexBuffer3D: must bind current BufferState.";
  12724. }
  12725. }
  12726. bind() {
  12727. if (Laya.BufferStateBase._curBindedBufferState) {
  12728. throw "IndexBuffer3D: must unbind current BufferState.";
  12729. }
  12730. else {
  12731. if (Laya.Buffer._bindedIndexBuffer !== this._glBuffer) {
  12732. var gl = Laya.LayaGL.instance;
  12733. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
  12734. Laya.Buffer._bindedIndexBuffer = this._glBuffer;
  12735. return true;
  12736. }
  12737. else {
  12738. return false;
  12739. }
  12740. }
  12741. }
  12742. setData(data, bufferOffset = 0, dataStartIndex = 0, dataCount = 4294967295) {
  12743. var byteCount = this._indexTypeByteCount;
  12744. if (dataStartIndex !== 0 || dataCount !== 4294967295) {
  12745. switch (this._indexType) {
  12746. case exports.IndexFormat.UInt32:
  12747. data = new Uint32Array(data.buffer, dataStartIndex * byteCount, dataCount);
  12748. break;
  12749. case exports.IndexFormat.UInt16:
  12750. data = new Uint16Array(data.buffer, dataStartIndex * byteCount, dataCount);
  12751. break;
  12752. case exports.IndexFormat.UInt8:
  12753. data = new Uint8Array(data.buffer, dataStartIndex * byteCount, dataCount);
  12754. break;
  12755. }
  12756. }
  12757. var curBufSta = Laya.BufferStateBase._curBindedBufferState;
  12758. if (curBufSta) {
  12759. if (curBufSta._bindedIndexBuffer === this) {
  12760. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  12761. }
  12762. else {
  12763. curBufSta.unBind();
  12764. this.bind();
  12765. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  12766. curBufSta.bind();
  12767. }
  12768. }
  12769. else {
  12770. this.bind();
  12771. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  12772. }
  12773. if (this._canRead) {
  12774. if (bufferOffset !== 0 || dataStartIndex !== 0 || dataCount !== 4294967295) {
  12775. var maxLength = this._buffer.length - bufferOffset;
  12776. if (dataCount > maxLength)
  12777. dataCount = maxLength;
  12778. for (var i = 0; i < dataCount; i++)
  12779. this._buffer[bufferOffset + i] = data[i];
  12780. }
  12781. else {
  12782. this._buffer = data;
  12783. }
  12784. }
  12785. }
  12786. getData() {
  12787. if (this._canRead)
  12788. return this._buffer;
  12789. else
  12790. throw new Error("Can't read data from VertexBuffer with only write flag!");
  12791. }
  12792. destroy() {
  12793. super.destroy();
  12794. this._buffer = null;
  12795. }
  12796. }
  12797. class SkyMesh {
  12798. constructor() {
  12799. }
  12800. _render(state) {
  12801. }
  12802. }
  12803. class SkyBox extends SkyMesh {
  12804. static __init__() {
  12805. SkyBox.instance = new SkyBox();
  12806. }
  12807. constructor() {
  12808. super();
  12809. var gl = Laya.LayaGL.instance;
  12810. var halfHeight = 1.0;
  12811. var halfWidth = 1.0;
  12812. var halfDepth = 1.0;
  12813. var vertices = new Float32Array([-halfDepth, halfHeight, -halfWidth, halfDepth, halfHeight, -halfWidth, halfDepth, halfHeight, halfWidth, -halfDepth, halfHeight, halfWidth,
  12814. -halfDepth, -halfHeight, -halfWidth, halfDepth, -halfHeight, -halfWidth, halfDepth, -halfHeight, halfWidth, -halfDepth, -halfHeight, halfWidth]);
  12815. var indices = new Uint8Array([
  12816. 0, 1, 2, 2, 3, 0,
  12817. 4, 7, 6, 6, 5, 4,
  12818. 0, 3, 7, 7, 4, 0,
  12819. 1, 5, 6, 6, 2, 1,
  12820. 3, 2, 6, 6, 7, 3,
  12821. 0, 4, 5, 5, 1, 0
  12822. ]);
  12823. var verDec = VertexMesh.getVertexDeclaration("POSITION");
  12824. this._vertexBuffer = new VertexBuffer3D(verDec.vertexStride * 8, gl.STATIC_DRAW, false);
  12825. this._vertexBuffer.vertexDeclaration = verDec;
  12826. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt8, 36, gl.STATIC_DRAW, false);
  12827. this._vertexBuffer.setData(vertices.buffer);
  12828. this._indexBuffer.setData(indices);
  12829. var bufferState = new BufferState();
  12830. bufferState.bind();
  12831. bufferState.applyVertexBuffer(this._vertexBuffer);
  12832. bufferState.applyIndexBuffer(this._indexBuffer);
  12833. bufferState.unBind();
  12834. this._bufferState = bufferState;
  12835. }
  12836. _render(state) {
  12837. var gl = Laya.LayaGL.instance;
  12838. gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_BYTE, 0);
  12839. Laya.Stat.trianglesFaces += 12;
  12840. Laya.Stat.renderBatches++;
  12841. }
  12842. }
  12843. class SkyRenderer {
  12844. constructor() {
  12845. this._mesh = SkyBox.instance;
  12846. }
  12847. get material() {
  12848. return this._material;
  12849. }
  12850. set material(value) {
  12851. if (this._material !== value) {
  12852. (this._material) && (this._material._removeReference());
  12853. (value) && (value._addReference());
  12854. this._material = value;
  12855. }
  12856. }
  12857. get mesh() {
  12858. return this._mesh;
  12859. }
  12860. set mesh(value) {
  12861. if (this._mesh !== value) {
  12862. this._mesh = value;
  12863. }
  12864. }
  12865. _isAvailable() {
  12866. return this._material && this._mesh ? true : false;
  12867. }
  12868. _render(context) {
  12869. if (this._material && this._mesh) {
  12870. var gl = Laya.LayaGL.instance;
  12871. var scene = context.scene;
  12872. var camera = context.camera;
  12873. var noteValue = ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_;
  12874. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(false);
  12875. Laya.WebGLContext.setCullFace(gl, false);
  12876. Laya.WebGLContext.setDepthFunc(gl, gl.LEQUAL);
  12877. Laya.WebGLContext.setDepthMask(gl, false);
  12878. var comDef = SkyRenderer._compileDefine;
  12879. this._material._shaderValues._defineDatas.cloneTo(comDef);
  12880. var shader = context.shader = this._material._shader.getSubShaderAt(0)._passes[0].withCompile(comDef);
  12881. var switchShader = shader.bind();
  12882. var switchShaderLoop = (Laya.Stat.loopCount !== shader._uploadMark);
  12883. var uploadScene = (shader._uploadScene !== scene) || switchShaderLoop;
  12884. if (uploadScene || switchShader) {
  12885. shader.uploadUniforms(shader._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  12886. shader._uploadScene = scene;
  12887. }
  12888. var renderTex = camera._getRenderTexture();
  12889. var uploadCamera = (shader._uploadCamera !== camera) || switchShaderLoop;
  12890. if (uploadCamera || switchShader) {
  12891. var viewMatrix = SkyRenderer._tempMatrix0;
  12892. var projectionMatrix = SkyRenderer._tempMatrix1;
  12893. camera.viewMatrix.cloneTo(viewMatrix);
  12894. camera.projectionMatrix.cloneTo(projectionMatrix);
  12895. viewMatrix.setTranslationVector(Vector3._ZERO);
  12896. if (camera.orthographic)
  12897. Matrix4x4.createPerspective(camera.fieldOfView, camera.aspectRatio, camera.nearPlane, camera.farPlane, projectionMatrix);
  12898. var epsilon = 1e-6;
  12899. var yScale = 1.0 / Math.tan(3.1416 * camera.fieldOfView / 180 * 0.5);
  12900. projectionMatrix.elements[0] = yScale / camera.aspectRatio;
  12901. projectionMatrix.elements[5] = yScale;
  12902. projectionMatrix.elements[10] = epsilon - 1.0;
  12903. projectionMatrix.elements[11] = -1.0;
  12904. projectionMatrix.elements[14] = -0;
  12905. camera._applyViewProject(context, viewMatrix, projectionMatrix);
  12906. shader.uploadUniforms(shader._cameraUniformParamsMap, camera._shaderValues, uploadCamera);
  12907. shader._uploadCamera = camera;
  12908. }
  12909. var uploadMaterial = (shader._uploadMaterial !== this._material) || switchShaderLoop;
  12910. if (uploadMaterial || switchShader) {
  12911. shader.uploadUniforms(shader._materialUniformParamsMap, this._material._shaderValues, uploadMaterial);
  12912. shader._uploadMaterial = this._material;
  12913. }
  12914. this._mesh._bufferState.bind();
  12915. this._mesh._render(context);
  12916. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(noteValue);
  12917. Laya.WebGLContext.setDepthFunc(gl, gl.LESS);
  12918. Laya.WebGLContext.setDepthMask(gl, true);
  12919. camera._applyViewProject(context, camera.viewMatrix, camera.projectionMatrix);
  12920. }
  12921. }
  12922. destroy() {
  12923. if (this._material) {
  12924. this._material._removeReference();
  12925. this._material = null;
  12926. }
  12927. }
  12928. }
  12929. SkyRenderer._tempMatrix0 = new Matrix4x4();
  12930. SkyRenderer._tempMatrix1 = new Matrix4x4();
  12931. SkyRenderer._compileDefine = new DefineDatas();
  12932. class BaseCamera extends Sprite3D {
  12933. constructor(nearPlane = 0.3, farPlane = 1000) {
  12934. super();
  12935. this._skyRenderer = new SkyRenderer();
  12936. this._forward = new Vector3();
  12937. this._up = new Vector3();
  12938. this.clearColor = new Vector4(100 / 255, 149 / 255, 237 / 255, 255 / 255);
  12939. this._shaderValues = new ShaderData(null);
  12940. this._fieldOfView = 60;
  12941. this._useUserProjectionMatrix = false;
  12942. this._orthographic = false;
  12943. this._orthographicVerticalSize = 10;
  12944. this.renderingOrder = 0;
  12945. this._nearPlane = nearPlane;
  12946. this._farPlane = farPlane;
  12947. this.cullingMask = 2147483647;
  12948. this.useOcclusionCulling = true;
  12949. }
  12950. get skyRenderer() {
  12951. return this._skyRenderer;
  12952. }
  12953. get fieldOfView() {
  12954. return this._fieldOfView;
  12955. }
  12956. set fieldOfView(value) {
  12957. this._fieldOfView = value;
  12958. this._calculateProjectionMatrix();
  12959. }
  12960. get nearPlane() {
  12961. return this._nearPlane;
  12962. }
  12963. set nearPlane(value) {
  12964. this._nearPlane = value;
  12965. this._calculateProjectionMatrix();
  12966. }
  12967. get farPlane() {
  12968. return this._farPlane;
  12969. }
  12970. set farPlane(vaule) {
  12971. this._farPlane = vaule;
  12972. this._calculateProjectionMatrix();
  12973. }
  12974. get orthographic() {
  12975. return this._orthographic;
  12976. }
  12977. set orthographic(vaule) {
  12978. this._orthographic = vaule;
  12979. this._calculateProjectionMatrix();
  12980. }
  12981. get orthographicVerticalSize() {
  12982. return this._orthographicVerticalSize;
  12983. }
  12984. set orthographicVerticalSize(vaule) {
  12985. this._orthographicVerticalSize = vaule;
  12986. this._calculateProjectionMatrix();
  12987. }
  12988. get renderingOrder() {
  12989. return this._renderingOrder;
  12990. }
  12991. set renderingOrder(value) {
  12992. this._renderingOrder = value;
  12993. this._sortCamerasByRenderingOrder();
  12994. }
  12995. _sortCamerasByRenderingOrder() {
  12996. if (this.displayedInStage) {
  12997. var cameraPool = this.scene._cameraPool;
  12998. var n = cameraPool.length - 1;
  12999. for (var i = 0; i < n; i++) {
  13000. if (cameraPool[i].renderingOrder > cameraPool[n].renderingOrder) {
  13001. var tempCamera = cameraPool[i];
  13002. cameraPool[i] = cameraPool[n];
  13003. cameraPool[n] = tempCamera;
  13004. }
  13005. }
  13006. }
  13007. }
  13008. _calculateProjectionMatrix() {
  13009. }
  13010. _onScreenSizeChanged() {
  13011. this._calculateProjectionMatrix();
  13012. }
  13013. _prepareCameraToRender() {
  13014. var cameraSV = this._shaderValues;
  13015. this.transform.getForward(this._forward);
  13016. this.transform.getUp(this._up);
  13017. cameraSV.setVector3(BaseCamera.CAMERAPOS, this.transform.position);
  13018. cameraSV.setVector3(BaseCamera.CAMERADIRECTION, this._forward);
  13019. cameraSV.setVector3(BaseCamera.CAMERAUP, this._up);
  13020. }
  13021. render(shader = null, replacementTag = null) {
  13022. }
  13023. addLayer(layer) {
  13024. this.cullingMask |= Math.pow(2, layer);
  13025. }
  13026. removeLayer(layer) {
  13027. this.cullingMask &= ~Math.pow(2, layer);
  13028. }
  13029. addAllLayers() {
  13030. this.cullingMask = 2147483647;
  13031. }
  13032. removeAllLayers() {
  13033. this.cullingMask = 0;
  13034. }
  13035. resetProjectionMatrix() {
  13036. this._useUserProjectionMatrix = false;
  13037. this._calculateProjectionMatrix();
  13038. }
  13039. _onActive() {
  13040. this._scene._addCamera(this);
  13041. super._onActive();
  13042. }
  13043. _onInActive() {
  13044. this._scene._removeCamera(this);
  13045. super._onInActive();
  13046. }
  13047. _parse(data, spriteMap) {
  13048. super._parse(data, spriteMap);
  13049. this.orthographic = data.orthographic;
  13050. (data.orthographicVerticalSize !== undefined) && (this.orthographicVerticalSize = data.orthographicVerticalSize);
  13051. (data.fieldOfView !== undefined) && (this.fieldOfView = data.fieldOfView);
  13052. this.nearPlane = data.nearPlane;
  13053. this.farPlane = data.farPlane;
  13054. var color = data.clearColor;
  13055. this.clearColor = new Vector4(color[0], color[1], color[2], color[3]);
  13056. var skyboxMaterial = data.skyboxMaterial;
  13057. if (skyboxMaterial) {
  13058. this._skyRenderer.material = Laya.Loader.getRes(skyboxMaterial.path);
  13059. }
  13060. }
  13061. destroy(destroyChild = true) {
  13062. this._skyRenderer.destroy();
  13063. this._skyRenderer = null;
  13064. Laya.Laya.stage.off(Laya.Event.RESIZE, this, this._onScreenSizeChanged);
  13065. super.destroy(destroyChild);
  13066. }
  13067. _create() {
  13068. return new BaseCamera();
  13069. }
  13070. }
  13071. BaseCamera._tempMatrix4x40 = new Matrix4x4();
  13072. BaseCamera.CAMERAPOS = Shader3D.propertyNameToID("u_CameraPos");
  13073. BaseCamera.VIEWMATRIX = Shader3D.propertyNameToID("u_View");
  13074. BaseCamera.PROJECTMATRIX = Shader3D.propertyNameToID("u_Projection");
  13075. BaseCamera.VIEWPROJECTMATRIX = Shader3D.propertyNameToID("u_ViewProjection");
  13076. BaseCamera.CAMERADIRECTION = Shader3D.propertyNameToID("u_CameraDirection");
  13077. BaseCamera.CAMERAUP = Shader3D.propertyNameToID("u_CameraUp");
  13078. BaseCamera.VIEWPORT = Shader3D.propertyNameToID("u_Viewport");
  13079. BaseCamera.PROJECTION_PARAMS = Shader3D.propertyNameToID("u_ProjectionParams");
  13080. BaseCamera.RENDERINGTYPE_DEFERREDLIGHTING = "DEFERREDLIGHTING";
  13081. BaseCamera.RENDERINGTYPE_FORWARDRENDERING = "FORWARDRENDERING";
  13082. BaseCamera._invertYScaleMatrix = new Matrix4x4(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  13083. BaseCamera._invertYProjectionMatrix = new Matrix4x4();
  13084. BaseCamera._invertYProjectionViewMatrix = new Matrix4x4();
  13085. BaseCamera.CLEARFLAG_SOLIDCOLOR = 0;
  13086. BaseCamera.CLEARFLAG_SKY = 1;
  13087. BaseCamera.CLEARFLAG_DEPTHONLY = 2;
  13088. BaseCamera.CLEARFLAG_NONE = 3;
  13089. class ScreenQuad extends Laya.Resource {
  13090. constructor() {
  13091. super();
  13092. this._bufferState = new BufferState();
  13093. this._bufferStateInvertUV = new BufferState();
  13094. var gl = Laya.LayaGL.instance;
  13095. this._vertexBuffer = new VertexBuffer3D(16 * 4, gl.STATIC_DRAW, false);
  13096. this._vertexBuffer.vertexDeclaration = ScreenQuad._vertexDeclaration;
  13097. this._vertexBuffer.setData(ScreenQuad._vertices.buffer);
  13098. this._bufferState.bind();
  13099. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  13100. this._bufferState.unBind();
  13101. this._vertexBufferInvertUV = new VertexBuffer3D(16 * 4, gl.STATIC_DRAW, false);
  13102. this._vertexBufferInvertUV.vertexDeclaration = ScreenQuad._vertexDeclaration;
  13103. this._vertexBufferInvertUV.setData(ScreenQuad._verticesInvertUV.buffer);
  13104. this._bufferStateInvertUV.bind();
  13105. this._bufferStateInvertUV.applyVertexBuffer(this._vertexBufferInvertUV);
  13106. this._bufferStateInvertUV.unBind();
  13107. this._setGPUMemory(this._vertexBuffer._byteLength + this._vertexBufferInvertUV._byteLength);
  13108. }
  13109. static __init__() {
  13110. ScreenQuad._vertexDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, ScreenQuad.SCREENQUAD_POSITION_UV)]);
  13111. ScreenQuad.instance = new ScreenQuad();
  13112. ScreenQuad.instance.lock = true;
  13113. }
  13114. render() {
  13115. var gl = Laya.LayaGL.instance;
  13116. this._bufferState.bind();
  13117. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  13118. Laya.Stat.renderBatches++;
  13119. }
  13120. renderInvertUV() {
  13121. var gl = Laya.LayaGL.instance;
  13122. this._bufferStateInvertUV.bind();
  13123. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  13124. Laya.Stat.renderBatches++;
  13125. }
  13126. destroy() {
  13127. super.destroy();
  13128. this._bufferState.destroy();
  13129. this._vertexBuffer.destroy();
  13130. this._bufferStateInvertUV.destroy();
  13131. this._vertexBufferInvertUV.destroy();
  13132. this._setGPUMemory(0);
  13133. }
  13134. }
  13135. ScreenQuad.SCREENQUAD_POSITION_UV = 0;
  13136. ScreenQuad._vertices = new Float32Array([1, 1, 1, 1, 1, -1, 1, 0, -1, 1, 0, 1, -1, -1, 0, 0]);
  13137. ScreenQuad._verticesInvertUV = new Float32Array([1, 1, 1, 0, 1, -1, 1, 1, -1, 1, 0, 0, -1, -1, 0, 1]);
  13138. class ScreenTriangle extends Laya.Resource {
  13139. constructor() {
  13140. super();
  13141. this._bufferState = new BufferState();
  13142. this._bufferStateInvertUV = new BufferState();
  13143. var gl = Laya.LayaGL.instance;
  13144. this._vertexBuffer = new VertexBuffer3D(12 * 4, gl.STATIC_DRAW, false);
  13145. this._vertexBuffer.vertexDeclaration = ScreenTriangle._vertexDeclaration;
  13146. this._vertexBuffer.setData(ScreenTriangle._vertices.buffer);
  13147. this._bufferState.bind();
  13148. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  13149. this._bufferState.unBind();
  13150. this._vertexBufferInvertUV = new VertexBuffer3D(12 * 4, gl.STATIC_DRAW, false);
  13151. this._vertexBufferInvertUV.vertexDeclaration = ScreenTriangle._vertexDeclaration;
  13152. this._vertexBufferInvertUV.setData(ScreenTriangle._verticesInvertUV.buffer);
  13153. this._bufferStateInvertUV.bind();
  13154. this._bufferStateInvertUV.applyVertexBuffer(this._vertexBufferInvertUV);
  13155. this._bufferStateInvertUV.unBind();
  13156. this._setGPUMemory(this._vertexBuffer._byteLength + this._vertexBufferInvertUV._byteLength);
  13157. }
  13158. static __init__() {
  13159. ScreenTriangle._vertexDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, ScreenTriangle.SCREENTRIANGLE_POSITION_UV)]);
  13160. ScreenTriangle.instance = new ScreenTriangle();
  13161. ScreenTriangle.instance.lock = true;
  13162. }
  13163. render() {
  13164. var gl = Laya.LayaGL.instance;
  13165. this._bufferState.bind();
  13166. gl.drawArrays(gl.TRIANGLES, 0, 3);
  13167. Laya.Stat.renderBatches++;
  13168. }
  13169. renderInvertUV() {
  13170. var gl = Laya.LayaGL.instance;
  13171. this._bufferStateInvertUV.bind();
  13172. gl.drawArrays(gl.TRIANGLES, 0, 3);
  13173. Laya.Stat.renderBatches++;
  13174. }
  13175. destroy() {
  13176. super.destroy();
  13177. this._bufferState.destroy();
  13178. this._vertexBuffer.destroy();
  13179. this._bufferStateInvertUV.destroy();
  13180. this._vertexBufferInvertUV.destroy();
  13181. this._setGPUMemory(0);
  13182. }
  13183. }
  13184. ScreenTriangle.SCREENTRIANGLE_POSITION_UV = 0;
  13185. ScreenTriangle._vertices = new Float32Array([-1, -1, 0, 0, -1, 3, 0, 2, 3, -1, 2, 0]);
  13186. ScreenTriangle._verticesInvertUV = new Float32Array([-1, -1, 0, 1, -1, 3, 0, -1, 3, -1, 2, 1]);
  13187. class Command {
  13188. constructor() {
  13189. this._commandBuffer = null;
  13190. }
  13191. static __init__() {
  13192. Command._screenShaderData = new ShaderData();
  13193. Command._screenShader = Shader3D.find("BlitScreen");
  13194. }
  13195. run() {
  13196. }
  13197. recover() {
  13198. this._commandBuffer = null;
  13199. }
  13200. }
  13201. Command.SCREENTEXTURE_NAME = "u_MainTex";
  13202. Command.SCREENTEXTUREOFFSETSCALE_NAME = "u_OffsetScale";
  13203. Command.MAINTEXTURE_TEXELSIZE_NAME = "u_MainTex_TexelSize";
  13204. Command.SCREENTEXTURE_ID = Shader3D.propertyNameToID(Command.SCREENTEXTURE_NAME);
  13205. Command.SCREENTEXTUREOFFSETSCALE_ID = Shader3D.propertyNameToID(Command.SCREENTEXTUREOFFSETSCALE_NAME);
  13206. Command.MAINTEXTURE_TEXELSIZE_ID = Shader3D.propertyNameToID(Command.MAINTEXTURE_TEXELSIZE_NAME);
  13207. class BlitScreenQuadCMD extends Command {
  13208. constructor() {
  13209. super(...arguments);
  13210. this._source = null;
  13211. this._dest = null;
  13212. this._offsetScale = null;
  13213. this._shader = null;
  13214. this._shaderData = null;
  13215. this._subShader = 0;
  13216. this._sourceTexelSize = new Vector4();
  13217. this._screenType = 0;
  13218. }
  13219. static create(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0, screenType = BlitScreenQuadCMD._SCREENTYPE_QUAD) {
  13220. var cmd;
  13221. cmd = BlitScreenQuadCMD._pool.length > 0 ? BlitScreenQuadCMD._pool.pop() : new BlitScreenQuadCMD();
  13222. cmd._source = source;
  13223. cmd._dest = dest;
  13224. cmd._offsetScale = offsetScale;
  13225. cmd._shader = shader;
  13226. cmd._shaderData = shaderData;
  13227. cmd._subShader = subShader;
  13228. cmd._screenType = screenType;
  13229. return cmd;
  13230. }
  13231. run() {
  13232. var shader = this._shader || Command._screenShader;
  13233. var shaderData = this._shaderData || Command._screenShaderData;
  13234. var dest = this._dest;
  13235. Laya.LayaGL.instance.viewport(0, 0, dest ? dest.width : RenderContext3D.clientWidth, dest ? dest.height : RenderContext3D.clientHeight);
  13236. shaderData.setTexture(Command.SCREENTEXTURE_ID, this._source);
  13237. shaderData.setVector(Command.SCREENTEXTUREOFFSETSCALE_ID, this._offsetScale || BlitScreenQuadCMD._defaultOffsetScale);
  13238. this._sourceTexelSize.setValue(1.0 / this._source.width, 1.0 / this._source.height, this._source.width, this._source.height);
  13239. shaderData.setVector(Command.MAINTEXTURE_TEXELSIZE_ID, this._sourceTexelSize);
  13240. (dest) && (dest._start());
  13241. var subShader = shader.getSubShaderAt(this._subShader);
  13242. var passes = subShader._passes;
  13243. for (var i = 0, n = passes.length; i < n; i++) {
  13244. var comDef = BlitScreenQuadCMD._compileDefine;
  13245. shaderData._defineDatas.cloneTo(comDef);
  13246. var shaderPass = passes[i].withCompile(comDef);
  13247. shaderPass.bind();
  13248. shaderPass.uploadUniforms(shaderPass._materialUniformParamsMap, shaderData, true);
  13249. shaderPass.uploadRenderStateBlendDepth(shaderData);
  13250. shaderPass.uploadRenderStateFrontFace(shaderData, false, null);
  13251. switch (this._screenType) {
  13252. case BlitScreenQuadCMD._SCREENTYPE_QUAD:
  13253. RenderContext3D._instance.invertY ? ScreenQuad.instance.renderInvertUV() : ScreenQuad.instance.render();
  13254. break;
  13255. case BlitScreenQuadCMD._SCREENTYPE_TRIANGLE:
  13256. RenderContext3D._instance.invertY ? ScreenTriangle.instance.renderInvertUV() : ScreenTriangle.instance.render();
  13257. break;
  13258. default:
  13259. throw "BlitScreenQuadCMD:unknown screen Type.";
  13260. }
  13261. }
  13262. (dest) && (dest._end());
  13263. }
  13264. recover() {
  13265. BlitScreenQuadCMD._pool.push(this);
  13266. this._source = null;
  13267. this._dest = null;
  13268. this._offsetScale = null;
  13269. this._shader = null;
  13270. this._shaderData = null;
  13271. super.recover();
  13272. }
  13273. }
  13274. BlitScreenQuadCMD._SCREENTYPE_QUAD = 0;
  13275. BlitScreenQuadCMD._SCREENTYPE_TRIANGLE = 1;
  13276. BlitScreenQuadCMD._compileDefine = new DefineDatas();
  13277. BlitScreenQuadCMD._pool = [];
  13278. BlitScreenQuadCMD._defaultOffsetScale = new Vector4(0, 0, 1, 1);
  13279. class SetRenderTargetCMD extends Command {
  13280. constructor() {
  13281. super(...arguments);
  13282. this._renderTexture = null;
  13283. }
  13284. static create(renderTexture) {
  13285. var cmd;
  13286. cmd = SetRenderTargetCMD._pool.length > 0 ? SetRenderTargetCMD._pool.pop() : new SetRenderTargetCMD();
  13287. cmd._renderTexture = renderTexture;
  13288. return cmd;
  13289. }
  13290. run() {
  13291. this._renderTexture._start();
  13292. }
  13293. recover() {
  13294. SetRenderTargetCMD._pool.push(this);
  13295. this._renderTexture = null;
  13296. }
  13297. }
  13298. SetRenderTargetCMD._pool = [];
  13299. class SetShaderDataTextureCMD extends Command {
  13300. constructor() {
  13301. super(...arguments);
  13302. this._shaderData = null;
  13303. this._nameID = 0;
  13304. this._texture = null;
  13305. }
  13306. static create(shaderData, nameID, texture) {
  13307. var cmd;
  13308. cmd = SetShaderDataTextureCMD._pool.length > 0 ? SetShaderDataTextureCMD._pool.pop() : new SetShaderDataTextureCMD();
  13309. cmd._shaderData = shaderData;
  13310. cmd._nameID = nameID;
  13311. cmd._texture = texture;
  13312. return cmd;
  13313. }
  13314. run() {
  13315. this._shaderData.setTexture(this._nameID, this._texture);
  13316. }
  13317. recover() {
  13318. SetShaderDataTextureCMD._pool.push(this);
  13319. this._shaderData = null;
  13320. this._nameID = 0;
  13321. this._texture = null;
  13322. }
  13323. }
  13324. SetShaderDataTextureCMD._pool = [];
  13325. class CommandBuffer {
  13326. constructor() {
  13327. this._camera = null;
  13328. this._commands = [];
  13329. }
  13330. _apply() {
  13331. for (var i = 0, n = this._commands.length; i < n; i++)
  13332. this._commands[i].run();
  13333. }
  13334. setShaderDataTexture(shaderData, nameID, source) {
  13335. this._commands.push(SetShaderDataTextureCMD.create(shaderData, nameID, source));
  13336. }
  13337. blitScreenQuad(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0) {
  13338. this._commands.push(BlitScreenQuadCMD.create(source, dest, offsetScale, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_QUAD));
  13339. }
  13340. blitScreenTriangle(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0) {
  13341. this._commands.push(BlitScreenQuadCMD.create(source, dest, offsetScale, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_TRIANGLE));
  13342. }
  13343. setRenderTarget(renderTexture) {
  13344. this._commands.push(SetRenderTargetCMD.create(renderTexture));
  13345. }
  13346. clear() {
  13347. for (var i = 0, n = this._commands.length; i < n; i++)
  13348. this._commands[i].recover();
  13349. this._commands.length = 0;
  13350. }
  13351. }
  13352. (function (CameraClearFlags) {
  13353. CameraClearFlags[CameraClearFlags["SolidColor"] = 0] = "SolidColor";
  13354. CameraClearFlags[CameraClearFlags["Sky"] = 1] = "Sky";
  13355. CameraClearFlags[CameraClearFlags["DepthOnly"] = 2] = "DepthOnly";
  13356. CameraClearFlags[CameraClearFlags["Nothing"] = 3] = "Nothing";
  13357. })(exports.CameraClearFlags || (exports.CameraClearFlags = {}));
  13358. class Camera extends BaseCamera {
  13359. constructor(aspectRatio = 0, nearPlane = 0.3, farPlane = 1000) {
  13360. super(nearPlane, farPlane);
  13361. this._updateViewMatrix = true;
  13362. this._postProcess = null;
  13363. this._enableHDR = false;
  13364. this._viewportParams = new Vector4();
  13365. this._projectionParams = new Vector4();
  13366. this._offScreenRenderTexture = null;
  13367. this._internalRenderTexture = null;
  13368. this._postProcessCommandBuffers = [];
  13369. this._clusterPlaneCacheFlag = new Vector2(-1, -1);
  13370. this._screenOffsetScale = new Vector4();
  13371. this.enableRender = true;
  13372. this.clearFlag = exports.CameraClearFlags.SolidColor;
  13373. this._viewMatrix = new Matrix4x4();
  13374. this._projectionMatrix = new Matrix4x4();
  13375. this._projectionViewMatrix = new Matrix4x4();
  13376. this._viewport = new Viewport(0, 0, 0, 0);
  13377. this._normalizedViewport = new Viewport(0, 0, 1, 1);
  13378. this._aspectRatio = aspectRatio;
  13379. this._boundFrustum = new BoundFrustum(Matrix4x4.DEFAULT);
  13380. if (Laya.Render.supportWebGLPlusCulling)
  13381. this._boundFrustumBuffer = new Float32Array(24);
  13382. this._calculateProjectionMatrix();
  13383. Laya.Laya.stage.on(Laya.Event.RESIZE, this, this._onScreenSizeChanged);
  13384. this.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  13385. }
  13386. get aspectRatio() {
  13387. if (this._aspectRatio === 0) {
  13388. var vp = this.viewport;
  13389. return vp.width / vp.height;
  13390. }
  13391. return this._aspectRatio;
  13392. }
  13393. set aspectRatio(value) {
  13394. if (value < 0)
  13395. throw new Error("Camera: the aspect ratio has to be a positive real number.");
  13396. this._aspectRatio = value;
  13397. this._calculateProjectionMatrix();
  13398. }
  13399. get viewport() {
  13400. if (this._offScreenRenderTexture)
  13401. this._calculationViewport(this._normalizedViewport, this._offScreenRenderTexture.width, this._offScreenRenderTexture.height);
  13402. else
  13403. this._calculationViewport(this._normalizedViewport, RenderContext3D.clientWidth, RenderContext3D.clientHeight);
  13404. return this._viewport;
  13405. }
  13406. set viewport(value) {
  13407. var width;
  13408. var height;
  13409. if (this._offScreenRenderTexture) {
  13410. width = this._offScreenRenderTexture.width;
  13411. height = this._offScreenRenderTexture.height;
  13412. }
  13413. else {
  13414. width = RenderContext3D.clientWidth;
  13415. height = RenderContext3D.clientHeight;
  13416. }
  13417. this._normalizedViewport.x = value.x / width;
  13418. this._normalizedViewport.y = value.y / height;
  13419. this._normalizedViewport.width = value.width / width;
  13420. this._normalizedViewport.height = value.height / height;
  13421. this._calculationViewport(this._normalizedViewport, width, height);
  13422. this._calculateProjectionMatrix();
  13423. }
  13424. get normalizedViewport() {
  13425. return this._normalizedViewport;
  13426. }
  13427. set normalizedViewport(value) {
  13428. var width;
  13429. var height;
  13430. if (this._offScreenRenderTexture) {
  13431. width = this._offScreenRenderTexture.width;
  13432. height = this._offScreenRenderTexture.height;
  13433. }
  13434. else {
  13435. width = RenderContext3D.clientWidth;
  13436. height = RenderContext3D.clientHeight;
  13437. }
  13438. if (this._normalizedViewport !== value)
  13439. value.cloneTo(this._normalizedViewport);
  13440. this._calculationViewport(value, width, height);
  13441. this._calculateProjectionMatrix();
  13442. }
  13443. get viewMatrix() {
  13444. if (this._updateViewMatrix) {
  13445. var scale = this.transform.getWorldLossyScale();
  13446. var scaleX = scale.x;
  13447. var scaleY = scale.y;
  13448. var scaleZ = scale.z;
  13449. var viewMatE = this._viewMatrix.elements;
  13450. this.transform.worldMatrix.cloneTo(this._viewMatrix);
  13451. viewMatE[0] /= scaleX;
  13452. viewMatE[1] /= scaleX;
  13453. viewMatE[2] /= scaleX;
  13454. viewMatE[4] /= scaleY;
  13455. viewMatE[5] /= scaleY;
  13456. viewMatE[6] /= scaleY;
  13457. viewMatE[8] /= scaleZ;
  13458. viewMatE[9] /= scaleZ;
  13459. viewMatE[10] /= scaleZ;
  13460. this._viewMatrix.invert(this._viewMatrix);
  13461. this._updateViewMatrix = false;
  13462. }
  13463. return this._viewMatrix;
  13464. }
  13465. get projectionMatrix() {
  13466. return this._projectionMatrix;
  13467. }
  13468. set projectionMatrix(value) {
  13469. this._projectionMatrix = value;
  13470. this._useUserProjectionMatrix = true;
  13471. }
  13472. get projectionViewMatrix() {
  13473. Matrix4x4.multiply(this.projectionMatrix, this.viewMatrix, this._projectionViewMatrix);
  13474. return this._projectionViewMatrix;
  13475. }
  13476. get boundFrustum() {
  13477. this._boundFrustum.matrix = this.projectionViewMatrix;
  13478. if (Laya.Render.supportWebGLPlusCulling) {
  13479. var near = this._boundFrustum.near;
  13480. var far = this._boundFrustum.far;
  13481. var left = this._boundFrustum.left;
  13482. var right = this._boundFrustum.right;
  13483. var top = this._boundFrustum.top;
  13484. var bottom = this._boundFrustum.bottom;
  13485. var nearNE = near.normal;
  13486. var farNE = far.normal;
  13487. var leftNE = left.normal;
  13488. var rightNE = right.normal;
  13489. var topNE = top.normal;
  13490. var bottomNE = bottom.normal;
  13491. var buffer = this._boundFrustumBuffer;
  13492. buffer[0] = nearNE.x, buffer[1] = nearNE.y, buffer[2] = nearNE.z, buffer[3] = near.distance;
  13493. buffer[4] = farNE.x, buffer[5] = farNE.y, buffer[6] = farNE.z, buffer[7] = far.distance;
  13494. buffer[8] = leftNE.x, buffer[9] = leftNE.y, buffer[10] = leftNE.z, buffer[11] = left.distance;
  13495. buffer[12] = rightNE.x, buffer[13] = rightNE.y, buffer[14] = rightNE.z, buffer[15] = right.distance;
  13496. buffer[16] = topNE.x, buffer[17] = topNE.y, buffer[18] = topNE.z, buffer[19] = top.distance;
  13497. buffer[20] = bottomNE.x, buffer[21] = bottomNE.y, buffer[22] = bottomNE.z, buffer[23] = bottom.distance;
  13498. }
  13499. return this._boundFrustum;
  13500. }
  13501. get renderTarget() {
  13502. return this._offScreenRenderTexture;
  13503. }
  13504. set renderTarget(value) {
  13505. var lastValue = this._offScreenRenderTexture;
  13506. if (lastValue !== value) {
  13507. (lastValue) && (lastValue._isCameraTarget = false);
  13508. (value) && (value._isCameraTarget = true);
  13509. this._offScreenRenderTexture = value;
  13510. this._calculateProjectionMatrix();
  13511. }
  13512. }
  13513. get postProcess() {
  13514. return this._postProcess;
  13515. }
  13516. set postProcess(value) {
  13517. this._postProcess = value;
  13518. var postProcessCommandBuffer = new CommandBuffer();
  13519. this.addCommandBuffer(Camera.CAMERAEVENT_POSTPROCESS, postProcessCommandBuffer);
  13520. value._init(this, postProcessCommandBuffer);
  13521. }
  13522. get enableHDR() {
  13523. return this._enableHDR;
  13524. }
  13525. set enableHDR(value) {
  13526. if (value && !SystemUtils.supportRenderTextureFormat(Laya.RenderTextureFormat.R16G16B16A16)) {
  13527. console.warn("Camera:can't enable HDR in this device.");
  13528. return;
  13529. }
  13530. this._enableHDR = value;
  13531. }
  13532. _calculationViewport(normalizedViewport, width, height) {
  13533. var lx = normalizedViewport.x * width;
  13534. var ly = normalizedViewport.y * height;
  13535. var rx = lx + Math.max(normalizedViewport.width * width, 0);
  13536. var ry = ly + Math.max(normalizedViewport.height * height, 0);
  13537. var ceilLeftX = Math.ceil(lx);
  13538. var ceilLeftY = Math.ceil(ly);
  13539. var floorRightX = Math.floor(rx);
  13540. var floorRightY = Math.floor(ry);
  13541. var pixelLeftX = ceilLeftX - lx >= 0.5 ? Math.floor(lx) : ceilLeftX;
  13542. var pixelLeftY = ceilLeftY - ly >= 0.5 ? Math.floor(ly) : ceilLeftY;
  13543. var pixelRightX = rx - floorRightX >= 0.5 ? Math.ceil(rx) : floorRightX;
  13544. var pixelRightY = ry - floorRightY >= 0.5 ? Math.ceil(ry) : floorRightY;
  13545. this._viewport.x = pixelLeftX;
  13546. this._viewport.y = pixelLeftY;
  13547. this._viewport.width = pixelRightX - pixelLeftX;
  13548. this._viewport.height = pixelRightY - pixelLeftY;
  13549. }
  13550. _calculateProjectionMatrix() {
  13551. if (!this._useUserProjectionMatrix) {
  13552. if (this._orthographic) {
  13553. var halfHeight = this.orthographicVerticalSize * 0.5;
  13554. var halfWidth = halfHeight * this.aspectRatio;
  13555. Matrix4x4.createOrthoOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, this.nearPlane, this.farPlane, this._projectionMatrix);
  13556. }
  13557. else {
  13558. Matrix4x4.createPerspective(3.1416 * this.fieldOfView / 180.0, this.aspectRatio, this.nearPlane, this.farPlane, this._projectionMatrix);
  13559. }
  13560. }
  13561. }
  13562. _isLayerVisible(layer) {
  13563. return (Math.pow(2, layer) & this.cullingMask) != 0;
  13564. }
  13565. _onTransformChanged(flag) {
  13566. flag &= Transform3D.TRANSFORM_WORLDMATRIX;
  13567. (flag) && (this._updateViewMatrix = true);
  13568. }
  13569. _parse(data, spriteMap) {
  13570. super._parse(data, spriteMap);
  13571. var clearFlagData = data.clearFlag;
  13572. (clearFlagData !== undefined) && (this.clearFlag = clearFlagData);
  13573. var viewport = data.viewport;
  13574. this.normalizedViewport = new Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);
  13575. var enableHDR = data.enableHDR;
  13576. (enableHDR !== undefined) && (this.enableHDR = enableHDR);
  13577. }
  13578. _getCanvasWidth() {
  13579. if (this._offScreenRenderTexture)
  13580. return this._offScreenRenderTexture.width;
  13581. else
  13582. return RenderContext3D.clientWidth;
  13583. }
  13584. _getCanvasHeight() {
  13585. if (this._offScreenRenderTexture)
  13586. return this._offScreenRenderTexture.height;
  13587. else
  13588. return RenderContext3D.clientHeight;
  13589. }
  13590. _getRenderTexture() {
  13591. return this._internalRenderTexture || this._offScreenRenderTexture;
  13592. }
  13593. _needInternalRenderTexture() {
  13594. return this._postProcess || this._enableHDR ? true : false;
  13595. }
  13596. _applyPostProcessCommandBuffers() {
  13597. for (var i = 0, n = this._postProcessCommandBuffers.length; i < n; i++)
  13598. this._postProcessCommandBuffers[i]._apply();
  13599. }
  13600. _getRenderTextureFormat() {
  13601. if (this._enableHDR)
  13602. return Laya.RenderTextureFormat.R16G16B16A16;
  13603. else
  13604. return Laya.RenderTextureFormat.R8G8B8;
  13605. }
  13606. _prepareCameraToRender() {
  13607. super._prepareCameraToRender();
  13608. var vp = this.viewport;
  13609. this._viewportParams.setValue(vp.x, vp.y, vp.width, vp.height);
  13610. this._projectionParams.setValue(this._nearPlane, this._farPlane, RenderContext3D._instance.invertY ? -1 : 1, 0);
  13611. this._shaderValues.setVector(BaseCamera.VIEWPORT, this._viewportParams);
  13612. this._shaderValues.setVector(BaseCamera.PROJECTION_PARAMS, this._projectionParams);
  13613. }
  13614. _applyViewProject(context, viewMat, proMat) {
  13615. var projectView;
  13616. var shaderData = this._shaderValues;
  13617. if (context.invertY) {
  13618. Matrix4x4.multiply(BaseCamera._invertYScaleMatrix, proMat, BaseCamera._invertYProjectionMatrix);
  13619. Matrix4x4.multiply(BaseCamera._invertYProjectionMatrix, viewMat, BaseCamera._invertYProjectionViewMatrix);
  13620. proMat = BaseCamera._invertYProjectionMatrix;
  13621. projectView = BaseCamera._invertYProjectionViewMatrix;
  13622. }
  13623. else {
  13624. Matrix4x4.multiply(proMat, viewMat, this._projectionViewMatrix);
  13625. projectView = this._projectionViewMatrix;
  13626. }
  13627. context.viewMatrix = viewMat;
  13628. context.projectionMatrix = proMat;
  13629. context.projectionViewMatrix = projectView;
  13630. shaderData.setMatrix4x4(BaseCamera.VIEWMATRIX, viewMat);
  13631. shaderData.setMatrix4x4(BaseCamera.PROJECTMATRIX, proMat);
  13632. shaderData.setMatrix4x4(BaseCamera.VIEWPROJECTMATRIX, projectView);
  13633. }
  13634. _updateClusterPlaneXY() {
  13635. var fieldOfView = this.fieldOfView;
  13636. var aspectRatio = this.aspectRatio;
  13637. if (this._clusterPlaneCacheFlag.x !== fieldOfView || this._clusterPlaneCacheFlag.y !== aspectRatio) {
  13638. var clusterCount = Config3D._config.lightClusterCount;
  13639. var xSlixe = clusterCount.x, ySlice = clusterCount.y;
  13640. var xCount = xSlixe + 1, yCount = ySlice + 1;
  13641. var xPlanes = this._clusterXPlanes, yPlanes = this._clusterYPlanes;
  13642. if (!xPlanes) {
  13643. xPlanes = this._clusterXPlanes = new Array(xCount);
  13644. yPlanes = this._clusterYPlanes = new Array(yCount);
  13645. for (var i = 0; i < xCount; i++)
  13646. xPlanes[i] = new Vector3();
  13647. for (var i = 0; i < yCount; i++)
  13648. yPlanes[i] = new Vector3();
  13649. }
  13650. var halfY = Math.tan((this.fieldOfView / 2) * Math.PI / 180);
  13651. var halfX = this.aspectRatio * halfY;
  13652. var yLengthPerCluster = 2 * halfY / xSlixe;
  13653. var xLengthPerCluster = 2 * halfX / ySlice;
  13654. for (var i = 0; i < xCount; i++) {
  13655. var angle = -halfX + xLengthPerCluster * i;
  13656. var bigHypot = Math.sqrt(1 + angle * angle);
  13657. var normX = 1 / bigHypot;
  13658. var xPlane = xPlanes[i];
  13659. xPlane.setValue(normX, 0, -angle * normX);
  13660. }
  13661. for (var i = 0; i < yCount; i++) {
  13662. var angle = halfY - yLengthPerCluster * i;
  13663. var bigHypot = Math.sqrt(1 + angle * angle);
  13664. var normY = -1 / bigHypot;
  13665. var yPlane = yPlanes[i];
  13666. yPlane.setValue(0, normY, -angle * normY);
  13667. }
  13668. this._clusterPlaneCacheFlag.x = fieldOfView;
  13669. this._clusterPlaneCacheFlag.y = aspectRatio;
  13670. }
  13671. }
  13672. render(shader = null, replacementTag = null) {
  13673. if (!this.activeInHierarchy)
  13674. return;
  13675. var viewport = this.viewport;
  13676. var needInternalRT = this._needInternalRenderTexture();
  13677. var gl = Laya.LayaGL.instance;
  13678. var context = RenderContext3D._instance;
  13679. var scene = context.scene = this._scene;
  13680. if (needInternalRT)
  13681. this._internalRenderTexture = RenderTexture.createFromPool(viewport.width, viewport.height, this._getRenderTextureFormat(), Laya.RenderTextureDepthFormat.DEPTH_16, Laya.BaseTexture.FILTERMODE_BILINEAR);
  13682. else
  13683. this._internalRenderTexture = null;
  13684. if (scene.parallelSplitShadowMaps[0]) {
  13685. ShaderData.setRuntimeValueMode(false);
  13686. var parallelSplitShadowMap = scene.parallelSplitShadowMaps[0];
  13687. parallelSplitShadowMap._calcAllLightCameraInfo(this);
  13688. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_CAST_SHADOW);
  13689. for (var i = 0, n = parallelSplitShadowMap.shadowMapCount; i < n; i++) {
  13690. var smCamera = parallelSplitShadowMap.cameras[i];
  13691. context.camera = smCamera;
  13692. FrustumCulling.renderObjectCulling(smCamera, scene, context, shader, replacementTag, true);
  13693. var shadowMap = parallelSplitShadowMap.cameras[i + 1].renderTarget;
  13694. shadowMap._start();
  13695. RenderContext3D._instance.invertY = false;
  13696. context.camera = smCamera;
  13697. Camera._updateMark++;
  13698. context.viewport = smCamera.viewport;
  13699. smCamera._prepareCameraToRender();
  13700. smCamera._applyViewProject(context, smCamera.viewMatrix, smCamera.projectionMatrix);
  13701. scene._clear(gl, context);
  13702. var queue = scene._opaqueQueue;
  13703. queue._render(context);
  13704. shadowMap._end();
  13705. }
  13706. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_CAST_SHADOW);
  13707. ShaderData.setRuntimeValueMode(true);
  13708. }
  13709. context.camera = this;
  13710. Camera._updateMark++;
  13711. scene._preRenderScript();
  13712. if (needInternalRT && !this._offScreenRenderTexture && (this.clearFlag == exports.CameraClearFlags.DepthOnly || this.clearFlag == exports.CameraClearFlags.Nothing)) {
  13713. if (this._enableHDR) {
  13714. var grabTexture = RenderTexture.createFromPool(viewport.width, viewport.height, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTH_16, Laya.BaseTexture.FILTERMODE_BILINEAR);
  13715. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, grabTexture._getSource());
  13716. gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, viewport.x, RenderContext3D.clientHeight - (viewport.y + viewport.height), viewport.width, viewport.height);
  13717. var blit = BlitScreenQuadCMD.create(grabTexture, this._internalRenderTexture);
  13718. blit.run();
  13719. blit.recover();
  13720. RenderTexture.recoverToPool(grabTexture);
  13721. }
  13722. else {
  13723. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, this._internalRenderTexture._getSource());
  13724. gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, viewport.x, RenderContext3D.clientHeight - (viewport.y + viewport.height), viewport.width, viewport.height);
  13725. }
  13726. }
  13727. var renderTex = this._getRenderTexture();
  13728. (renderTex) && (renderTex._start());
  13729. context.viewport = viewport;
  13730. this._prepareCameraToRender();
  13731. var multiLighting = Config3D._config._multiLighting;
  13732. (multiLighting) && (Cluster.instance.update(this, (this._scene)));
  13733. this._applyViewProject(context, this.viewMatrix, this._projectionMatrix);
  13734. scene._preCulling(context, this, shader, replacementTag);
  13735. scene._clear(gl, context);
  13736. scene._renderScene(context);
  13737. scene._postRenderScript();
  13738. (renderTex) && (renderTex._end());
  13739. if (needInternalRT) {
  13740. if (this._postProcess) {
  13741. this._postProcess._render();
  13742. this._applyPostProcessCommandBuffers();
  13743. }
  13744. else if (this._enableHDR) {
  13745. var canvasWidth = this._getCanvasWidth(), canvasHeight = this._getCanvasHeight();
  13746. this._screenOffsetScale.setValue(viewport.x / canvasWidth, viewport.y / canvasHeight, viewport.width / canvasWidth, viewport.height / canvasHeight);
  13747. var blit = BlitScreenQuadCMD.create(this._internalRenderTexture, this._offScreenRenderTexture ? this._offScreenRenderTexture : null, this._screenOffsetScale);
  13748. blit.run();
  13749. blit.recover();
  13750. }
  13751. RenderTexture.recoverToPool(this._internalRenderTexture);
  13752. }
  13753. }
  13754. viewportPointToRay(point, out) {
  13755. Picker.calculateCursorRay(point, this.viewport, this._projectionMatrix, this.viewMatrix, null, out);
  13756. }
  13757. normalizedViewportPointToRay(point, out) {
  13758. var finalPoint = Camera._tempVector20;
  13759. var vp = this.viewport;
  13760. finalPoint.x = point.x * vp.width;
  13761. finalPoint.y = point.y * vp.height;
  13762. Picker.calculateCursorRay(finalPoint, this.viewport, this._projectionMatrix, this.viewMatrix, null, out);
  13763. }
  13764. worldToViewportPoint(position, out) {
  13765. Matrix4x4.multiply(this._projectionMatrix, this._viewMatrix, this._projectionViewMatrix);
  13766. this.viewport.project(position, this._projectionViewMatrix, out);
  13767. out.x = out.x / Laya.Laya.stage.clientScaleX;
  13768. out.y = out.y / Laya.Laya.stage.clientScaleY;
  13769. }
  13770. worldToNormalizedViewportPoint(position, out) {
  13771. Matrix4x4.multiply(this._projectionMatrix, this._viewMatrix, this._projectionViewMatrix);
  13772. this.normalizedViewport.project(position, this._projectionViewMatrix, out);
  13773. out.x = out.x / Laya.Laya.stage.clientScaleX;
  13774. out.y = out.y / Laya.Laya.stage.clientScaleY;
  13775. }
  13776. convertScreenCoordToOrthographicCoord(source, out) {
  13777. if (this._orthographic) {
  13778. var clientWidth = RenderContext3D.clientWidth;
  13779. var clientHeight = RenderContext3D.clientHeight;
  13780. var ratioX = this.orthographicVerticalSize * this.aspectRatio / clientWidth;
  13781. var ratioY = this.orthographicVerticalSize / clientHeight;
  13782. out.x = (-clientWidth / 2 + source.x * Laya.Laya.stage.clientScaleX) * ratioX;
  13783. out.y = (clientHeight / 2 - source.y * Laya.Laya.stage.clientScaleY) * ratioY;
  13784. out.z = (this.nearPlane - this.farPlane) * (source.z + 1) / 2 - this.nearPlane;
  13785. Vector3.transformCoordinate(out, this.transform.worldMatrix, out);
  13786. return true;
  13787. }
  13788. else {
  13789. return false;
  13790. }
  13791. }
  13792. destroy(destroyChild = true) {
  13793. this._offScreenRenderTexture = null;
  13794. this.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  13795. super.destroy(destroyChild);
  13796. }
  13797. addCommandBuffer(event, commandBuffer) {
  13798. switch (event) {
  13799. case Camera.CAMERAEVENT_POSTPROCESS:
  13800. this._postProcessCommandBuffers.push(commandBuffer);
  13801. commandBuffer._camera = this;
  13802. break;
  13803. default:
  13804. throw "Camera:unknown event.";
  13805. }
  13806. }
  13807. removeCommandBuffer(event, commandBuffer) {
  13808. switch (event) {
  13809. case Camera.CAMERAEVENT_POSTPROCESS:
  13810. var index = this._postProcessCommandBuffers.indexOf(commandBuffer);
  13811. if (index !== -1)
  13812. this._postProcessCommandBuffers.splice(index, 1);
  13813. break;
  13814. default:
  13815. throw "Camera:unknown event.";
  13816. }
  13817. }
  13818. removeCommandBuffers(event) {
  13819. switch (event) {
  13820. case Camera.CAMERAEVENT_POSTPROCESS:
  13821. this._postProcessCommandBuffers.length = 0;
  13822. break;
  13823. default:
  13824. throw "Camera:unknown event.";
  13825. }
  13826. }
  13827. _create() {
  13828. return new Camera();
  13829. }
  13830. }
  13831. Camera.CAMERAEVENT_POSTPROCESS = 0;
  13832. Camera._tempVector20 = new Vector2();
  13833. Camera._updateMark = 0;
  13834. class RenderElement {
  13835. constructor() {
  13836. this.renderSubShader = null;
  13837. this.renderType = RenderElement.RENDERTYPE_NORMAL;
  13838. }
  13839. getInvertFront() {
  13840. return this._transform._isFrontFaceInvert;
  13841. }
  13842. setTransform(transform) {
  13843. this._transform = transform;
  13844. }
  13845. setGeometry(geometry) {
  13846. this._geometry = geometry;
  13847. }
  13848. addToOpaqueRenderQueue(context, queue) {
  13849. queue.elements.add(this);
  13850. }
  13851. addToTransparentRenderQueue(context, queue) {
  13852. queue.elements.add(this);
  13853. queue.lastTransparentBatched = false;
  13854. queue.lastTransparentRenderElement = this;
  13855. }
  13856. _update(scene, context, customShader, replacementTag) {
  13857. if (this.material) {
  13858. var subShader = this.material._shader.getSubShaderAt(0);
  13859. this.renderSubShader = null;
  13860. if (customShader) {
  13861. if (replacementTag) {
  13862. var oriTag = subShader.getFlag(replacementTag);
  13863. if (oriTag) {
  13864. var customSubShaders = customShader._subShaders;
  13865. for (var k = 0, p = customSubShaders.length; k < p; k++) {
  13866. var customSubShader = customSubShaders[k];
  13867. if (oriTag === customSubShader.getFlag(replacementTag)) {
  13868. this.renderSubShader = customSubShader;
  13869. break;
  13870. }
  13871. }
  13872. if (!this.renderSubShader)
  13873. return;
  13874. }
  13875. else {
  13876. return;
  13877. }
  13878. }
  13879. else {
  13880. this.renderSubShader = customShader.getSubShaderAt(0);
  13881. }
  13882. }
  13883. else {
  13884. this.renderSubShader = subShader;
  13885. }
  13886. var renderQueue = scene._getRenderQueue(this.material.renderQueue);
  13887. if (renderQueue.isTransparent)
  13888. this.addToTransparentRenderQueue(context, renderQueue);
  13889. else
  13890. this.addToOpaqueRenderQueue(context, renderQueue);
  13891. }
  13892. }
  13893. _render(context) {
  13894. var forceInvertFace = context.invertY;
  13895. var lastStateMaterial, lastStateShaderInstance, lastStateRender;
  13896. var updateMark = Camera._updateMark;
  13897. var scene = context.scene;
  13898. var camera = context.camera;
  13899. var transform = this._transform;
  13900. var geometry = this._geometry;
  13901. context.renderElement = this;
  13902. var updateRender = updateMark !== this.render._updateMark || this.renderType !== this.render._updateRenderType;
  13903. if (updateRender) {
  13904. this.render._renderUpdate(context, transform);
  13905. this.render._renderUpdateWithCamera(context, transform);
  13906. this.render._updateMark = updateMark;
  13907. this.render._updateRenderType = this.renderType;
  13908. }
  13909. else {
  13910. if (this.renderType == RenderElement.RENDERTYPE_INSTANCEBATCH) {
  13911. this.render._renderUpdate(context, transform);
  13912. this.render._renderUpdateWithCamera(context, transform);
  13913. }
  13914. }
  13915. if (geometry._prepareRender(context)) {
  13916. var passes = this.renderSubShader._passes;
  13917. for (var j = 0, m = passes.length; j < m; j++) {
  13918. var comDef = RenderElement._compileDefine;
  13919. scene._shaderValues._defineDatas.cloneTo(comDef);
  13920. comDef.removeDefineDatas(this.material._disablePublicDefineDatas);
  13921. comDef.addDefineDatas(this.render._shaderValues._defineDatas);
  13922. comDef.addDefineDatas(this.material._shaderValues._defineDatas);
  13923. var shaderIns = context.shader = passes[j].withCompile(comDef);
  13924. var switchShader = shaderIns.bind();
  13925. var switchUpdateMark = (updateMark !== shaderIns._uploadMark);
  13926. var uploadScene = (shaderIns._uploadScene !== scene) || switchUpdateMark;
  13927. if (uploadScene || switchShader) {
  13928. shaderIns.uploadUniforms(shaderIns._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  13929. shaderIns._uploadScene = scene;
  13930. }
  13931. var uploadSprite3D = (shaderIns._uploadRender !== this.render || shaderIns._uploadRenderType !== this.renderType) || switchUpdateMark;
  13932. if (uploadSprite3D || switchShader) {
  13933. shaderIns.uploadUniforms(shaderIns._spriteUniformParamsMap, this.render._shaderValues, uploadSprite3D);
  13934. shaderIns._uploadRender = this.render;
  13935. shaderIns._uploadRenderType = this.renderType;
  13936. }
  13937. var uploadCamera = shaderIns._uploadCamera !== camera || switchUpdateMark;
  13938. if (uploadCamera || switchShader) {
  13939. shaderIns.uploadUniforms(shaderIns._cameraUniformParamsMap, camera._shaderValues, uploadCamera);
  13940. shaderIns._uploadCamera = camera;
  13941. }
  13942. var uploadMaterial = (shaderIns._uploadMaterial !== this.material) || switchUpdateMark;
  13943. if (uploadMaterial || switchShader) {
  13944. shaderIns.uploadUniforms(shaderIns._materialUniformParamsMap, this.material._shaderValues, uploadMaterial);
  13945. shaderIns._uploadMaterial = this.material;
  13946. }
  13947. var matValues = this.material._shaderValues;
  13948. if (lastStateMaterial !== this.material || lastStateShaderInstance !== shaderIns) {
  13949. shaderIns.uploadRenderStateBlendDepth(matValues);
  13950. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, this.getInvertFront());
  13951. lastStateMaterial = this.material;
  13952. lastStateShaderInstance = shaderIns;
  13953. lastStateRender = this.render;
  13954. }
  13955. else {
  13956. if (lastStateRender !== this.render) {
  13957. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, this.getInvertFront());
  13958. lastStateRender = this.render;
  13959. }
  13960. }
  13961. geometry._render(context);
  13962. shaderIns._uploadMark = updateMark;
  13963. }
  13964. }
  13965. if (updateRender && this.renderType !== RenderElement.RENDERTYPE_NORMAL)
  13966. this.render._revertBatchRenderUpdate(context);
  13967. }
  13968. destroy() {
  13969. this._transform = null;
  13970. this._geometry = null;
  13971. this.material = null;
  13972. this.render = null;
  13973. }
  13974. }
  13975. RenderElement.RENDERTYPE_NORMAL = 0;
  13976. RenderElement.RENDERTYPE_STATICBATCH = 1;
  13977. RenderElement.RENDERTYPE_INSTANCEBATCH = 2;
  13978. RenderElement.RENDERTYPE_VERTEXBATCH = 3;
  13979. RenderElement._compileDefine = new DefineDatas();
  13980. class SubMeshRenderElement extends RenderElement {
  13981. constructor() {
  13982. super();
  13983. this._dynamicWorldPositionNormalNeedUpdate = true;
  13984. }
  13985. _onWorldMatrixChanged() {
  13986. this._dynamicWorldPositionNormalNeedUpdate = true;
  13987. }
  13988. _computeWorldPositionsAndNormals(positionOffset, normalOffset, multiSubMesh, vertexCount) {
  13989. if (this._dynamicWorldPositionNormalNeedUpdate) {
  13990. var subMesh = this._geometry;
  13991. var vertexBuffer = subMesh._vertexBuffer;
  13992. var vertexFloatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  13993. var oriVertexes = vertexBuffer.getFloat32Data();
  13994. var worldMat = this._transform.worldMatrix;
  13995. var rotation = this._transform.rotation;
  13996. var indices = subMesh._indices;
  13997. for (var i = 0; i < vertexCount; i++) {
  13998. var index = multiSubMesh ? indices[i] : i;
  13999. var oriOffset = index * vertexFloatCount;
  14000. var bakeOffset = i * 3;
  14001. Utils3D.transformVector3ArrayToVector3ArrayCoordinate(oriVertexes, oriOffset + positionOffset, worldMat, this._dynamicWorldPositions, bakeOffset);
  14002. (normalOffset !== -1) && (Utils3D.transformVector3ArrayByQuat(oriVertexes, oriOffset + normalOffset, rotation, this._dynamicWorldNormals, bakeOffset));
  14003. }
  14004. this._dynamicWorldPositionNormalNeedUpdate = false;
  14005. }
  14006. }
  14007. setTransform(transform) {
  14008. if (this._transform !== transform) {
  14009. (this._transform) && (this._transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatrixChanged));
  14010. (transform) && (transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatrixChanged));
  14011. this._dynamicWorldPositionNormalNeedUpdate = true;
  14012. this._transform = transform;
  14013. }
  14014. }
  14015. setGeometry(geometry) {
  14016. if (this._geometry !== geometry) {
  14017. var subMesh = geometry;
  14018. var mesh = subMesh._mesh;
  14019. if (mesh) {
  14020. var multiSubMesh = mesh._subMeshes.length > 1;
  14021. var dynBatVerCount = multiSubMesh ? subMesh._indexCount : mesh._vertexCount;
  14022. if (dynBatVerCount <= ILaya3D.SubMeshDynamicBatch.maxAllowVertexCount) {
  14023. var length = dynBatVerCount * 3;
  14024. this._dynamicVertexBatch = true;
  14025. this._dynamicWorldPositions = new Float32Array(length);
  14026. this._dynamicWorldNormals = new Float32Array(length);
  14027. this._dynamicVertexCount = dynBatVerCount;
  14028. this._dynamicMultiSubMesh = multiSubMesh;
  14029. }
  14030. else {
  14031. this._dynamicVertexBatch = false;
  14032. }
  14033. }
  14034. this._geometry = geometry;
  14035. }
  14036. }
  14037. addToOpaqueRenderQueue(context, queue) {
  14038. var subMeshStaticBatch = this.staticBatch;
  14039. var queueElements = queue.elements;
  14040. var elements = queueElements.elements;
  14041. if (subMeshStaticBatch) {
  14042. var staManager = ILaya3D.MeshRenderStaticBatchManager.instance;
  14043. var staBatchMarks = staManager.getBatchOpaquaMark(this.render.lightmapIndex + 1, this.render.receiveShadow, this.material.id, subMeshStaticBatch._batchID);
  14044. if (staManager._updateCountMark === staBatchMarks.updateMark) {
  14045. var staBatchIndex = staBatchMarks.indexInList;
  14046. if (staBatchMarks.batched) {
  14047. elements[staBatchIndex].staticBatchElementList.add(this);
  14048. }
  14049. else {
  14050. var staOriElement = elements[staBatchIndex];
  14051. var staOriRender = staOriElement.render;
  14052. var staBatchElement = staManager._getBatchRenderElementFromPool();
  14053. staBatchElement.renderType = RenderElement.RENDERTYPE_STATICBATCH;
  14054. staBatchElement.setGeometry(subMeshStaticBatch);
  14055. staBatchElement.material = staOriElement.material;
  14056. var staRootOwner = subMeshStaticBatch.batchOwner;
  14057. var staBatchTransform = staRootOwner ? staRootOwner._transform : null;
  14058. staBatchElement.setTransform(staBatchTransform);
  14059. staBatchElement.render = staOriRender;
  14060. staBatchElement.renderSubShader = staOriElement.renderSubShader;
  14061. var staBatchList = staBatchElement.staticBatchElementList;
  14062. staBatchList.length = 0;
  14063. staBatchList.add(staOriElement);
  14064. staBatchList.add(this);
  14065. elements[staBatchIndex] = staBatchElement;
  14066. staBatchMarks.batched = true;
  14067. }
  14068. }
  14069. else {
  14070. staBatchMarks.updateMark = staManager._updateCountMark;
  14071. staBatchMarks.indexInList = queueElements.length;
  14072. staBatchMarks.batched = false;
  14073. queueElements.add(this);
  14074. }
  14075. }
  14076. else if (this.renderSubShader._owner._enableInstancing && Laya.LayaGL.layaGPUInstance.supportInstance() && this.render.lightmapIndex < 0) {
  14077. var subMesh = this._geometry;
  14078. var insManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  14079. var insBatchMarks = insManager.getInstanceBatchOpaquaMark(this.render.receiveShadow, this.material.id, subMesh._id, this._transform._isFrontFaceInvert);
  14080. if (insManager._updateCountMark === insBatchMarks.updateMark) {
  14081. var insBatchIndex = insBatchMarks.indexInList;
  14082. if (insBatchMarks.batched) {
  14083. var instanceBatchElementList = elements[insBatchIndex].instanceBatchElementList;
  14084. if (instanceBatchElementList.length === SubMeshInstanceBatch.instance.maxInstanceCount) {
  14085. insBatchMarks.updateMark = insManager._updateCountMark;
  14086. insBatchMarks.indexInList = queueElements.length;
  14087. insBatchMarks.batched = false;
  14088. queueElements.add(this);
  14089. }
  14090. else {
  14091. instanceBatchElementList.add(this);
  14092. }
  14093. }
  14094. else {
  14095. var insOriElement = elements[insBatchIndex];
  14096. var insOriRender = insOriElement.render;
  14097. var insBatchElement = insManager._getBatchRenderElementFromPool();
  14098. insBatchElement.renderType = RenderElement.RENDERTYPE_INSTANCEBATCH;
  14099. insBatchElement.setGeometry(SubMeshInstanceBatch.instance);
  14100. insBatchElement.material = insOriElement.material;
  14101. insBatchElement.setTransform(null);
  14102. insBatchElement.render = insOriRender;
  14103. insBatchElement.instanceSubMesh = subMesh;
  14104. insBatchElement.renderSubShader = insOriElement.renderSubShader;
  14105. var insBatchList = insBatchElement.instanceBatchElementList;
  14106. insBatchList.length = 0;
  14107. insBatchList.add(insOriElement);
  14108. insBatchList.add(this);
  14109. elements[insBatchIndex] = insBatchElement;
  14110. insBatchMarks.batched = true;
  14111. }
  14112. }
  14113. else {
  14114. insBatchMarks.updateMark = insManager._updateCountMark;
  14115. insBatchMarks.indexInList = queueElements.length;
  14116. insBatchMarks.batched = false;
  14117. queueElements.add(this);
  14118. }
  14119. }
  14120. else if (this._dynamicVertexBatch) {
  14121. var verDec = this._geometry._vertexBuffer.vertexDeclaration;
  14122. var dynManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  14123. var dynBatchMarks = dynManager.getVertexBatchOpaquaMark(this.render.lightmapIndex + 1, this.render.receiveShadow, this.material.id, verDec.id);
  14124. if (dynManager._updateCountMark === dynBatchMarks.updateMark) {
  14125. var dynBatchIndex = dynBatchMarks.indexInList;
  14126. if (dynBatchMarks.batched) {
  14127. elements[dynBatchIndex].vertexBatchElementList.add(this);
  14128. }
  14129. else {
  14130. var dynOriElement = elements[dynBatchIndex];
  14131. var dynOriRender = dynOriElement.render;
  14132. var dynBatchElement = dynManager._getBatchRenderElementFromPool();
  14133. dynBatchElement.renderType = RenderElement.RENDERTYPE_VERTEXBATCH;
  14134. dynBatchElement.setGeometry(ILaya3D.SubMeshDynamicBatch.instance);
  14135. dynBatchElement.material = dynOriElement.material;
  14136. dynBatchElement.setTransform(null);
  14137. dynBatchElement.render = dynOriRender;
  14138. dynBatchElement.vertexBatchVertexDeclaration = verDec;
  14139. dynBatchElement.renderSubShader = dynOriElement.renderSubShader;
  14140. var dynBatchList = dynBatchElement.vertexBatchElementList;
  14141. dynBatchList.length = 0;
  14142. dynBatchList.add(dynOriElement);
  14143. dynBatchList.add(this);
  14144. elements[dynBatchIndex] = dynBatchElement;
  14145. dynBatchMarks.batched = true;
  14146. }
  14147. }
  14148. else {
  14149. dynBatchMarks.updateMark = dynManager._updateCountMark;
  14150. dynBatchMarks.indexInList = queueElements.length;
  14151. dynBatchMarks.batched = false;
  14152. queueElements.add(this);
  14153. }
  14154. }
  14155. else {
  14156. queueElements.add(this);
  14157. }
  14158. }
  14159. addToTransparentRenderQueue(context, queue) {
  14160. var subMeshStaticBatch = this.staticBatch;
  14161. var queueElements = queue.elements;
  14162. var elements = queueElements.elements;
  14163. if (subMeshStaticBatch) {
  14164. var staManager = ILaya3D.MeshRenderStaticBatchManager.instance;
  14165. var staLastElement = queue.lastTransparentRenderElement;
  14166. if (staLastElement) {
  14167. var staLastRender = staLastElement.render;
  14168. if (staLastElement._geometry._getType() !== this._geometry._getType() || staLastElement.staticBatch !== subMeshStaticBatch || staLastElement.material !== this.material || staLastRender.receiveShadow !== this.render.receiveShadow || staLastRender.lightmapIndex !== this.render.lightmapIndex) {
  14169. queueElements.add(this);
  14170. queue.lastTransparentBatched = false;
  14171. }
  14172. else {
  14173. if (queue.lastTransparentBatched) {
  14174. elements[queueElements.length - 1].staticBatchElementList.add((this));
  14175. }
  14176. else {
  14177. var staBatchElement = staManager._getBatchRenderElementFromPool();
  14178. staBatchElement.renderType = RenderElement.RENDERTYPE_STATICBATCH;
  14179. staBatchElement.setGeometry(subMeshStaticBatch);
  14180. staBatchElement.material = staLastElement.material;
  14181. var staRootOwner = subMeshStaticBatch.batchOwner;
  14182. var staBatchTransform = staRootOwner ? staRootOwner._transform : null;
  14183. staBatchElement.setTransform(staBatchTransform);
  14184. staBatchElement.render = this.render;
  14185. staBatchElement.renderSubShader = staLastElement.renderSubShader;
  14186. var staBatchList = staBatchElement.staticBatchElementList;
  14187. staBatchList.length = 0;
  14188. staBatchList.add(staLastElement);
  14189. staBatchList.add(this);
  14190. elements[queueElements.length - 1] = staBatchElement;
  14191. }
  14192. queue.lastTransparentBatched = true;
  14193. }
  14194. }
  14195. else {
  14196. queueElements.add(this);
  14197. queue.lastTransparentBatched = false;
  14198. }
  14199. }
  14200. else if (this.renderSubShader._owner._enableInstancing && Laya.LayaGL.layaGPUInstance.supportInstance() && this.render.lightmapIndex < 0) {
  14201. var subMesh = this._geometry;
  14202. var insManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  14203. var insLastElement = queue.lastTransparentRenderElement;
  14204. if (insLastElement) {
  14205. var insLastRender = insLastElement.render;
  14206. if (insLastElement._geometry._getType() !== this._geometry._getType() || insLastElement._geometry !== subMesh || insLastElement.material !== this.material || insLastRender.receiveShadow !== this.render.receiveShadow) {
  14207. queueElements.add(this);
  14208. queue.lastTransparentBatched = false;
  14209. }
  14210. else {
  14211. if (queue.lastTransparentBatched) {
  14212. var instanceBatchElementList = elements[queueElements.length - 1].instanceBatchElementList;
  14213. if (instanceBatchElementList.length === SubMeshInstanceBatch.instance.maxInstanceCount) {
  14214. queueElements.add(this);
  14215. queue.lastTransparentBatched = false;
  14216. }
  14217. else {
  14218. instanceBatchElementList.add(this);
  14219. queue.lastTransparentBatched = true;
  14220. }
  14221. }
  14222. else {
  14223. var insBatchElement = insManager._getBatchRenderElementFromPool();
  14224. insBatchElement.renderType = RenderElement.RENDERTYPE_INSTANCEBATCH;
  14225. insBatchElement.setGeometry(SubMeshInstanceBatch.instance);
  14226. insBatchElement.material = insLastElement.material;
  14227. insBatchElement.setTransform(null);
  14228. insBatchElement.render = this.render;
  14229. insBatchElement.instanceSubMesh = subMesh;
  14230. insBatchElement.renderSubShader = insLastElement.renderSubShader;
  14231. var insBatchList = insBatchElement.instanceBatchElementList;
  14232. insBatchList.length = 0;
  14233. insBatchList.add(insLastElement);
  14234. insBatchList.add(this);
  14235. elements[queueElements.length - 1] = insBatchElement;
  14236. queue.lastTransparentBatched = true;
  14237. }
  14238. }
  14239. }
  14240. else {
  14241. queueElements.add(this);
  14242. queue.lastTransparentBatched = false;
  14243. }
  14244. }
  14245. else if (this._dynamicVertexBatch) {
  14246. var verDec = this._geometry._vertexBuffer.vertexDeclaration;
  14247. var dynManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  14248. var dynLastElement = queue.lastTransparentRenderElement;
  14249. if (dynLastElement) {
  14250. var dynLastRender = dynLastElement.render;
  14251. if (dynLastElement._geometry._getType() !== this._geometry._getType() || dynLastElement._geometry._vertexBuffer._vertexDeclaration !== verDec || dynLastElement.material !== this.material || dynLastRender.receiveShadow !== this.render.receiveShadow || dynLastRender.lightmapIndex !== this.render.lightmapIndex) {
  14252. queueElements.add(this);
  14253. queue.lastTransparentBatched = false;
  14254. }
  14255. else {
  14256. if (queue.lastTransparentBatched) {
  14257. elements[queueElements.length - 1].vertexBatchElementList.add((this));
  14258. }
  14259. else {
  14260. var dynBatchElement = dynManager._getBatchRenderElementFromPool();
  14261. dynBatchElement.renderType = RenderElement.RENDERTYPE_VERTEXBATCH;
  14262. dynBatchElement.setGeometry(ILaya3D.SubMeshDynamicBatch.instance);
  14263. dynBatchElement.material = dynLastElement.material;
  14264. dynBatchElement.setTransform(null);
  14265. dynBatchElement.render = this.render;
  14266. dynBatchElement.vertexBatchVertexDeclaration = verDec;
  14267. dynBatchElement.renderSubShader = dynLastElement.renderSubShader;
  14268. var dynBatchList = dynBatchElement.vertexBatchElementList;
  14269. dynBatchList.length = 0;
  14270. dynBatchList.add(dynLastElement);
  14271. dynBatchList.add(this);
  14272. elements[queueElements.length - 1] = dynBatchElement;
  14273. }
  14274. queue.lastTransparentBatched = true;
  14275. }
  14276. }
  14277. else {
  14278. queueElements.add(this);
  14279. queue.lastTransparentBatched = false;
  14280. }
  14281. }
  14282. else {
  14283. queueElements.add(this);
  14284. }
  14285. queue.lastTransparentRenderElement = this;
  14286. }
  14287. getInvertFront() {
  14288. switch (this.renderType) {
  14289. case RenderElement.RENDERTYPE_NORMAL:
  14290. return this._transform._isFrontFaceInvert;
  14291. case RenderElement.RENDERTYPE_STATICBATCH:
  14292. case RenderElement.RENDERTYPE_VERTEXBATCH:
  14293. return false;
  14294. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  14295. return this.instanceBatchElementList.elements[0]._transform._isFrontFaceInvert;
  14296. default:
  14297. throw "SubMeshRenderElement: unknown renderType";
  14298. }
  14299. }
  14300. destroy() {
  14301. super.destroy();
  14302. this._dynamicWorldPositions = null;
  14303. this._dynamicWorldNormals = null;
  14304. this.staticBatch = null;
  14305. this.staticBatchElementList = null;
  14306. this.vertexBatchElementList = null;
  14307. this.vertexBatchVertexDeclaration = null;
  14308. }
  14309. }
  14310. class SubMeshStaticBatch extends GeometryElement {
  14311. constructor(batchOwner, vertexDeclaration) {
  14312. super();
  14313. this._bufferState = new BufferState();
  14314. this._batchID = SubMeshStaticBatch._batchIDCounter++;
  14315. this._batchElements = [];
  14316. this._currentBatchVertexCount = 0;
  14317. this._currentBatchIndexCount = 0;
  14318. this._vertexDeclaration = vertexDeclaration;
  14319. this.batchOwner = batchOwner;
  14320. }
  14321. _getStaticBatchBakedVertexs(batchVertices, batchOffset, batchOwnerTransform, transform, render, mesh) {
  14322. var vertexBuffer = mesh._vertexBuffer;
  14323. var vertexDeclaration = vertexBuffer.vertexDeclaration;
  14324. var positionOffset = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  14325. var normalElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_NORMAL0);
  14326. var normalOffset = normalElement ? normalElement._offset / 4 : -1;
  14327. var colorElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  14328. var colorOffset = colorElement ? colorElement._offset / 4 : -1;
  14329. var uv0Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  14330. var uv0Offset = uv0Element ? uv0Element._offset / 4 : -1;
  14331. var uv1Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE1);
  14332. var uv1Offset = uv1Element ? uv1Element._offset / 4 : -1;
  14333. var tangentElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TANGENT0);
  14334. var sTangentOffset = tangentElement ? tangentElement._offset / 4 : -1;
  14335. var bakeVertexFloatCount = 18;
  14336. var oriVertexFloatCount = vertexDeclaration.vertexStride / 4;
  14337. var oriVertexes = vertexBuffer.getFloat32Data();
  14338. var worldMat;
  14339. if (batchOwnerTransform) {
  14340. var rootMat = batchOwnerTransform.worldMatrix;
  14341. rootMat.invert(SubMeshStaticBatch._tempMatrix4x40);
  14342. worldMat = SubMeshStaticBatch._tempMatrix4x41;
  14343. Matrix4x4.multiply(SubMeshStaticBatch._tempMatrix4x40, transform.worldMatrix, worldMat);
  14344. }
  14345. else {
  14346. worldMat = transform.worldMatrix;
  14347. }
  14348. var normalMat = SubMeshStaticBatch._tempMatrix4x42;
  14349. worldMat.invert(normalMat);
  14350. normalMat.transpose();
  14351. var rotation = SubMeshStaticBatch._tempQuaternion0;
  14352. worldMat.decomposeTransRotScale(SubMeshStaticBatch._tempVector30, rotation, SubMeshStaticBatch._tempVector31);
  14353. var lightmapScaleOffset = render.lightmapScaleOffset;
  14354. var vertexCount = mesh.vertexCount;
  14355. for (var i = 0; i < vertexCount; i++) {
  14356. var oriOffset = i * oriVertexFloatCount;
  14357. var bakeOffset = (i + batchOffset) * bakeVertexFloatCount;
  14358. Utils3D.transformVector3ArrayToVector3ArrayCoordinate(oriVertexes, oriOffset + positionOffset, worldMat, batchVertices, bakeOffset + 0);
  14359. if (normalOffset !== -1)
  14360. Utils3D.transformVector3ArrayToVector3ArrayNormal(oriVertexes, oriOffset + normalOffset, normalMat, batchVertices, bakeOffset + 3);
  14361. var j, m;
  14362. var bakOff = bakeOffset + 6;
  14363. if (colorOffset !== -1) {
  14364. var oriOff = oriOffset + colorOffset;
  14365. for (j = 0, m = 4; j < m; j++)
  14366. batchVertices[bakOff + j] = oriVertexes[oriOff + j];
  14367. }
  14368. else {
  14369. for (j = 0, m = 4; j < m; j++)
  14370. batchVertices[bakOff + j] = 1.0;
  14371. }
  14372. if (uv0Offset !== -1) {
  14373. var absUv0Offset = oriOffset + uv0Offset;
  14374. batchVertices[bakeOffset + 10] = oriVertexes[absUv0Offset];
  14375. batchVertices[bakeOffset + 11] = oriVertexes[absUv0Offset + 1];
  14376. }
  14377. if (lightmapScaleOffset) {
  14378. if (uv1Offset !== -1)
  14379. Utils3D.transformLightingMapTexcoordArray(oriVertexes, oriOffset + uv1Offset, lightmapScaleOffset, batchVertices, bakeOffset + 12);
  14380. else
  14381. Utils3D.transformLightingMapTexcoordArray(oriVertexes, oriOffset + uv0Offset, lightmapScaleOffset, batchVertices, bakeOffset + 12);
  14382. }
  14383. if (sTangentOffset !== -1) {
  14384. var absSTanegntOffset = oriOffset + sTangentOffset;
  14385. batchVertices[bakeOffset + 14] = oriVertexes[absSTanegntOffset];
  14386. batchVertices[bakeOffset + 15] = oriVertexes[absSTanegntOffset + 1];
  14387. batchVertices[bakeOffset + 16] = oriVertexes[absSTanegntOffset + 2];
  14388. batchVertices[bakeOffset + 17] = oriVertexes[absSTanegntOffset + 3];
  14389. }
  14390. }
  14391. return vertexCount;
  14392. }
  14393. addTest(sprite) {
  14394. var vertexCount;
  14395. var subMeshVertexCount = sprite.meshFilter.sharedMesh.vertexCount;
  14396. vertexCount = this._currentBatchVertexCount + subMeshVertexCount;
  14397. if (vertexCount > SubMeshStaticBatch.maxBatchVertexCount)
  14398. return false;
  14399. return true;
  14400. }
  14401. add(sprite) {
  14402. var mesh = sprite.meshFilter.sharedMesh;
  14403. var subMeshVertexCount = mesh.vertexCount;
  14404. this._batchElements.push(sprite);
  14405. var render = sprite._render;
  14406. render._isPartOfStaticBatch = true;
  14407. render._staticBatch = this;
  14408. var renderElements = render._renderElements;
  14409. for (var i = 0, n = renderElements.length; i < n; i++)
  14410. renderElements[i].staticBatch = this;
  14411. this._currentBatchIndexCount += mesh._indexBuffer.indexCount;
  14412. this._currentBatchVertexCount += subMeshVertexCount;
  14413. }
  14414. remove(sprite) {
  14415. var mesh = sprite.meshFilter.sharedMesh;
  14416. var index = this._batchElements.indexOf(sprite);
  14417. if (index !== -1) {
  14418. this._batchElements.splice(index, 1);
  14419. var renderElements = sprite._render._renderElements;
  14420. for (var i = 0, n = renderElements.length; i < n; i++)
  14421. renderElements[i].staticBatch = null;
  14422. this._currentBatchIndexCount = this._currentBatchIndexCount - mesh._indexBuffer.indexCount;
  14423. this._currentBatchVertexCount = this._currentBatchVertexCount - mesh.vertexCount;
  14424. sprite._render._isPartOfStaticBatch = false;
  14425. }
  14426. }
  14427. finishInit() {
  14428. if (this._vertexBuffer) {
  14429. this._vertexBuffer.destroy();
  14430. this._indexBuffer.destroy();
  14431. Laya.Resource._addGPUMemory(-(this._vertexBuffer._byteLength + this._indexBuffer._byteLength));
  14432. }
  14433. var gl = Laya.LayaGL.instance;
  14434. var batchVertexCount = 0;
  14435. var batchIndexCount = 0;
  14436. var rootOwner = this.batchOwner;
  14437. var floatStride = this._vertexDeclaration.vertexStride / 4;
  14438. var vertexDatas = new Float32Array(floatStride * this._currentBatchVertexCount);
  14439. var indexDatas = new Uint16Array(this._currentBatchIndexCount);
  14440. this._vertexBuffer = new VertexBuffer3D(this._vertexDeclaration.vertexStride * this._currentBatchVertexCount, gl.STATIC_DRAW);
  14441. this._vertexBuffer.vertexDeclaration = this._vertexDeclaration;
  14442. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._currentBatchIndexCount, gl.STATIC_DRAW);
  14443. for (var i = 0, n = this._batchElements.length; i < n; i++) {
  14444. var sprite = this._batchElements[i];
  14445. var mesh = sprite.meshFilter.sharedMesh;
  14446. var meshVerCount = this._getStaticBatchBakedVertexs(vertexDatas, batchVertexCount, rootOwner ? rootOwner._transform : null, sprite._transform, sprite._render, mesh);
  14447. var indices = mesh._indexBuffer.getData();
  14448. var indexOffset = batchVertexCount;
  14449. var indexEnd = batchIndexCount + indices.length;
  14450. var elements = sprite._render._renderElements;
  14451. for (var j = 0, m = mesh.subMeshCount; j < m; j++) {
  14452. var subMesh = mesh._subMeshes[j];
  14453. var start = batchIndexCount + subMesh._indexStart;
  14454. var element = elements[j];
  14455. element.staticBatchIndexStart = start;
  14456. element.staticBatchIndexEnd = start + subMesh._indexCount;
  14457. }
  14458. indexDatas.set(indices, batchIndexCount);
  14459. var k;
  14460. var isInvert = rootOwner ? (sprite._transform._isFrontFaceInvert !== rootOwner.transform._isFrontFaceInvert) : sprite._transform._isFrontFaceInvert;
  14461. if (isInvert) {
  14462. for (k = batchIndexCount; k < indexEnd; k += 3) {
  14463. indexDatas[k] = indexOffset + indexDatas[k];
  14464. var index1 = indexDatas[k + 1];
  14465. var index2 = indexDatas[k + 2];
  14466. indexDatas[k + 1] = indexOffset + index2;
  14467. indexDatas[k + 2] = indexOffset + index1;
  14468. }
  14469. }
  14470. else {
  14471. for (k = batchIndexCount; k < indexEnd; k += 3) {
  14472. indexDatas[k] = indexOffset + indexDatas[k];
  14473. indexDatas[k + 1] = indexOffset + indexDatas[k + 1];
  14474. indexDatas[k + 2] = indexOffset + indexDatas[k + 2];
  14475. }
  14476. }
  14477. batchIndexCount += indices.length;
  14478. batchVertexCount += meshVerCount;
  14479. }
  14480. this._vertexBuffer.setData(vertexDatas.buffer);
  14481. this._indexBuffer.setData(indexDatas);
  14482. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  14483. Laya.Resource._addGPUMemory(memorySize);
  14484. this._bufferState.bind();
  14485. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  14486. this._bufferState.applyIndexBuffer(this._indexBuffer);
  14487. this._bufferState.unBind();
  14488. }
  14489. _render(state) {
  14490. this._bufferState.bind();
  14491. var gl = Laya.LayaGL.instance;
  14492. var element = state.renderElement;
  14493. var staticBatchElementList = element.staticBatchElementList;
  14494. var batchElementList = staticBatchElementList.elements;
  14495. var from = 0;
  14496. var end = 0;
  14497. var count = staticBatchElementList.length;
  14498. for (var i = 1; i < count; i++) {
  14499. var lastElement = batchElementList[i - 1];
  14500. if (lastElement.staticBatchIndexEnd === batchElementList[i].staticBatchIndexStart) {
  14501. end++;
  14502. continue;
  14503. }
  14504. else {
  14505. var start = batchElementList[from].staticBatchIndexStart;
  14506. var indexCount = batchElementList[end].staticBatchIndexEnd - start;
  14507. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, start * 2);
  14508. from = ++end;
  14509. Laya.Stat.trianglesFaces += indexCount / 3;
  14510. }
  14511. }
  14512. start = batchElementList[from].staticBatchIndexStart;
  14513. indexCount = batchElementList[end].staticBatchIndexEnd - start;
  14514. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, start * 2);
  14515. Laya.Stat.renderBatches++;
  14516. Laya.Stat.savedRenderBatches += count - 1;
  14517. Laya.Stat.trianglesFaces += indexCount / 3;
  14518. }
  14519. dispose() {
  14520. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  14521. Laya.Resource._addGPUMemory(-memorySize);
  14522. this._batchElements = null;
  14523. this.batchOwner = null;
  14524. this._vertexDeclaration = null;
  14525. this._bufferState.destroy();
  14526. this._vertexBuffer.destroy();
  14527. this._indexBuffer.destroy();
  14528. this._vertexBuffer = null;
  14529. this._indexBuffer = null;
  14530. this._bufferState = null;
  14531. }
  14532. }
  14533. SubMeshStaticBatch._tempVector30 = new Vector3();
  14534. SubMeshStaticBatch._tempVector31 = new Vector3();
  14535. SubMeshStaticBatch._tempQuaternion0 = new Quaternion();
  14536. SubMeshStaticBatch._tempMatrix4x40 = new Matrix4x4();
  14537. SubMeshStaticBatch._tempMatrix4x41 = new Matrix4x4();
  14538. SubMeshStaticBatch._tempMatrix4x42 = new Matrix4x4();
  14539. SubMeshStaticBatch.maxBatchVertexCount = 65535;
  14540. SubMeshStaticBatch._batchIDCounter = 0;
  14541. class SingletonList {
  14542. constructor() {
  14543. this.elements = [];
  14544. this.length = 0;
  14545. }
  14546. _add(element) {
  14547. if (this.length === this.elements.length)
  14548. this.elements.push(element);
  14549. else
  14550. this.elements[this.length] = element;
  14551. }
  14552. add(element) {
  14553. if (this.length === this.elements.length)
  14554. this.elements.push(element);
  14555. else
  14556. this.elements[this.length] = element;
  14557. this.length++;
  14558. }
  14559. }
  14560. class MeshRenderStaticBatchManager extends StaticBatchManager {
  14561. constructor() {
  14562. super();
  14563. this._opaqueBatchMarks = [];
  14564. this._updateCountMark = 0;
  14565. }
  14566. static __init__() {
  14567. MeshRenderStaticBatchManager._verDec = VertexMesh.getVertexDeclaration("POSITION,NORMAL,COLOR,UV,UV1,TANGENT");
  14568. }
  14569. _compare(left, right) {
  14570. var lRender = left._render, rRender = right._render;
  14571. var leftGeo = left.meshFilter.sharedMesh, rightGeo = right.meshFilter.sharedMesh;
  14572. var lightOffset = lRender.lightmapIndex - rRender.lightmapIndex;
  14573. if (lightOffset === 0) {
  14574. var receiveShadowOffset = (lRender.receiveShadow ? 1 : 0) - (rRender.receiveShadow ? 1 : 0);
  14575. if (receiveShadowOffset === 0) {
  14576. var materialOffset = (lRender.sharedMaterial && rRender.sharedMaterial) ? lRender.sharedMaterial.id - rRender.sharedMaterial.id : 0;
  14577. if (materialOffset === 0) {
  14578. var verDec = leftGeo._vertexBuffer.vertexDeclaration.id - rightGeo._vertexBuffer.vertexDeclaration.id;
  14579. if (verDec === 0) {
  14580. return rightGeo._indexBuffer.indexCount - leftGeo._indexBuffer.indexCount;
  14581. }
  14582. else {
  14583. return verDec;
  14584. }
  14585. }
  14586. else {
  14587. return materialOffset;
  14588. }
  14589. }
  14590. else {
  14591. return receiveShadowOffset;
  14592. }
  14593. }
  14594. else {
  14595. return lightOffset;
  14596. }
  14597. }
  14598. _getBatchRenderElementFromPool() {
  14599. var renderElement = this._batchRenderElementPool[this._batchRenderElementPoolIndex++];
  14600. if (!renderElement) {
  14601. renderElement = new SubMeshRenderElement();
  14602. this._batchRenderElementPool[this._batchRenderElementPoolIndex - 1] = renderElement;
  14603. renderElement.staticBatchElementList = new SingletonList();
  14604. }
  14605. return renderElement;
  14606. }
  14607. _getStaticBatch(staticBatches, rootOwner, number) {
  14608. var subMeshStaticBatch = staticBatches[number];
  14609. if (!subMeshStaticBatch) {
  14610. subMeshStaticBatch = staticBatches[number] = new SubMeshStaticBatch(rootOwner, MeshRenderStaticBatchManager._verDec);
  14611. this._staticBatches[subMeshStaticBatch._batchID] = subMeshStaticBatch;
  14612. }
  14613. return subMeshStaticBatch;
  14614. }
  14615. _initStaticBatchs(rootOwner) {
  14616. var initBatchSprites = this._initBatchSprites;
  14617. this._quickSort(initBatchSprites, 0, initBatchSprites.length - 1);
  14618. var staticBatches = [];
  14619. var lastCanMerage = false;
  14620. var curStaticBatch;
  14621. var batchNumber = 0;
  14622. for (var i = 0, n = initBatchSprites.length; i < n; i++) {
  14623. var sprite = initBatchSprites[i];
  14624. if (lastCanMerage) {
  14625. if (curStaticBatch.addTest(sprite)) {
  14626. curStaticBatch.add(sprite);
  14627. }
  14628. else {
  14629. lastCanMerage = false;
  14630. batchNumber++;
  14631. }
  14632. }
  14633. else {
  14634. var lastIndex = n - 1;
  14635. if (i !== lastIndex) {
  14636. curStaticBatch = this._getStaticBatch(staticBatches, rootOwner, batchNumber);
  14637. curStaticBatch.add(sprite);
  14638. lastCanMerage = true;
  14639. }
  14640. }
  14641. }
  14642. for (i = 0, n = staticBatches.length; i < n; i++) {
  14643. var staticBatch = staticBatches[i];
  14644. staticBatch && staticBatch.finishInit();
  14645. }
  14646. this._initBatchSprites.length = 0;
  14647. }
  14648. _removeRenderSprite(sprite) {
  14649. var render = sprite._render;
  14650. var staticBatch = render._staticBatch;
  14651. var batchElements = staticBatch._batchElements;
  14652. var index = batchElements.indexOf(sprite);
  14653. if (index !== -1) {
  14654. batchElements.splice(index, 1);
  14655. render._staticBatch = null;
  14656. var renderElements = render._renderElements;
  14657. for (var i = 0, n = renderElements.length; i < n; i++)
  14658. renderElements[i].staticBatch = null;
  14659. }
  14660. if (batchElements.length === 0) {
  14661. delete this._staticBatches[staticBatch._batchID];
  14662. staticBatch.dispose();
  14663. }
  14664. }
  14665. _clear() {
  14666. super._clear();
  14667. this._updateCountMark++;
  14668. }
  14669. _garbageCollection() {
  14670. for (var key in this._staticBatches) {
  14671. var staticBatch = this._staticBatches[key];
  14672. if (staticBatch._batchElements.length === 0) {
  14673. staticBatch.dispose();
  14674. delete this._staticBatches[key];
  14675. }
  14676. }
  14677. }
  14678. getBatchOpaquaMark(lightMapIndex, receiveShadow, materialID, staticBatchID) {
  14679. var receiveShadowIndex = receiveShadow ? 1 : 0;
  14680. var staLightMapMarks = (this._opaqueBatchMarks[lightMapIndex]) || (this._opaqueBatchMarks[lightMapIndex] = []);
  14681. var staReceiveShadowMarks = (staLightMapMarks[receiveShadowIndex]) || (staLightMapMarks[receiveShadowIndex] = []);
  14682. var staMaterialMarks = (staReceiveShadowMarks[materialID]) || (staReceiveShadowMarks[materialID] = []);
  14683. return (staMaterialMarks[staticBatchID]) || (staMaterialMarks[staticBatchID] = new BatchMark);
  14684. }
  14685. }
  14686. MeshRenderStaticBatchManager.instance = new MeshRenderStaticBatchManager();
  14687. class MeshSprite3DShaderDeclaration {
  14688. }
  14689. class BoundBox {
  14690. constructor(min, max) {
  14691. this.min = min;
  14692. this.max = max;
  14693. }
  14694. _rotateExtents(extents, rotation, out) {
  14695. var extentsX = extents.x;
  14696. var extentsY = extents.y;
  14697. var extentsZ = extents.z;
  14698. var matElements = rotation.elements;
  14699. out.x = Math.abs(matElements[0] * extentsX) + Math.abs(matElements[4] * extentsY) + Math.abs(matElements[8] * extentsZ);
  14700. out.y = Math.abs(matElements[1] * extentsX) + Math.abs(matElements[5] * extentsY) + Math.abs(matElements[9] * extentsZ);
  14701. out.z = Math.abs(matElements[2] * extentsX) + Math.abs(matElements[6] * extentsY) + Math.abs(matElements[10] * extentsZ);
  14702. }
  14703. getCorners(corners) {
  14704. corners.length = 8;
  14705. var minX = this.min.x;
  14706. var minY = this.min.y;
  14707. var minZ = this.min.z;
  14708. var maxX = this.max.x;
  14709. var maxY = this.max.y;
  14710. var maxZ = this.max.z;
  14711. corners[0] = new Vector3(minX, maxY, maxZ);
  14712. corners[1] = new Vector3(maxX, maxY, maxZ);
  14713. corners[2] = new Vector3(maxX, minY, maxZ);
  14714. corners[3] = new Vector3(minX, minY, maxZ);
  14715. corners[4] = new Vector3(minX, maxY, minZ);
  14716. corners[5] = new Vector3(maxX, maxY, minZ);
  14717. corners[6] = new Vector3(maxX, minY, minZ);
  14718. corners[7] = new Vector3(minX, minY, minZ);
  14719. }
  14720. getCenter(out) {
  14721. Vector3.add(this.min, this.max, out);
  14722. Vector3.scale(out, 0.5, out);
  14723. }
  14724. getExtent(out) {
  14725. Vector3.subtract(this.max, this.min, out);
  14726. Vector3.scale(out, 0.5, out);
  14727. }
  14728. setCenterAndExtent(center, extent) {
  14729. Vector3.subtract(center, extent, this.min);
  14730. Vector3.add(center, extent, this.max);
  14731. }
  14732. tranform(matrix, out) {
  14733. var center = BoundBox._tempVector30;
  14734. var extent = BoundBox._tempVector31;
  14735. this.getCenter(center);
  14736. this.getExtent(extent);
  14737. Vector3.transformCoordinate(center, matrix, center);
  14738. this._rotateExtents(extent, matrix, extent);
  14739. out.setCenterAndExtent(center, extent);
  14740. }
  14741. toDefault() {
  14742. this.min.toDefault();
  14743. this.max.toDefault();
  14744. }
  14745. static createfromPoints(points, out) {
  14746. if (points == null)
  14747. throw new Error("points");
  14748. var min = out.min;
  14749. var max = out.max;
  14750. min.x = Number.MAX_VALUE;
  14751. min.y = Number.MAX_VALUE;
  14752. min.z = Number.MAX_VALUE;
  14753. max.x = -Number.MAX_VALUE;
  14754. max.y = -Number.MAX_VALUE;
  14755. max.z = -Number.MAX_VALUE;
  14756. for (var i = 0, n = points.length; i < n; ++i) {
  14757. Vector3.min(min, points[i], min);
  14758. Vector3.max(max, points[i], max);
  14759. }
  14760. }
  14761. static merge(box1, box2, out) {
  14762. Vector3.min(box1.min, box2.min, out.min);
  14763. Vector3.max(box1.max, box2.max, out.max);
  14764. }
  14765. cloneTo(destObject) {
  14766. var dest = destObject;
  14767. this.min.cloneTo(dest.min);
  14768. this.max.cloneTo(dest.max);
  14769. }
  14770. clone() {
  14771. var dest = new BoundBox(new Vector3(), new Vector3());
  14772. this.cloneTo(dest);
  14773. return dest;
  14774. }
  14775. }
  14776. BoundBox._tempVector30 = new Vector3();
  14777. BoundBox._tempVector31 = new Vector3();
  14778. class Bounds {
  14779. constructor(min, max) {
  14780. this._updateFlag = 0;
  14781. this._center = new Vector3();
  14782. this._extent = new Vector3();
  14783. this._boundBox = new BoundBox(new Vector3(), new Vector3());
  14784. min.cloneTo(this._boundBox.min);
  14785. max.cloneTo(this._boundBox.max);
  14786. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  14787. }
  14788. setMin(value) {
  14789. var min = this._boundBox.min;
  14790. if (value !== min)
  14791. value.cloneTo(min);
  14792. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  14793. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  14794. }
  14795. getMin() {
  14796. var min = this._boundBox.min;
  14797. if (this._getUpdateFlag(Bounds._UPDATE_MIN)) {
  14798. this._getMin(this.getCenter(), this.getExtent(), min);
  14799. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  14800. }
  14801. return min;
  14802. }
  14803. setMax(value) {
  14804. var max = this._boundBox.max;
  14805. if (value !== max)
  14806. value.cloneTo(max);
  14807. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  14808. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  14809. }
  14810. getMax() {
  14811. var max = this._boundBox.max;
  14812. if (this._getUpdateFlag(Bounds._UPDATE_MAX)) {
  14813. this._getMax(this.getCenter(), this.getExtent(), max);
  14814. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  14815. }
  14816. return max;
  14817. }
  14818. setCenter(value) {
  14819. if (value !== this._center)
  14820. value.cloneTo(this._center);
  14821. this._setUpdateFlag(Bounds._UPDATE_MIN | Bounds._UPDATE_MAX, true);
  14822. this._setUpdateFlag(Bounds._UPDATE_CENTER, false);
  14823. }
  14824. getCenter() {
  14825. if (this._getUpdateFlag(Bounds._UPDATE_CENTER)) {
  14826. this._getCenter(this.getMin(), this.getMax(), this._center);
  14827. this._setUpdateFlag(Bounds._UPDATE_CENTER, false);
  14828. }
  14829. return this._center;
  14830. }
  14831. setExtent(value) {
  14832. if (value !== this._extent)
  14833. value.cloneTo(this._extent);
  14834. this._setUpdateFlag(Bounds._UPDATE_MIN | Bounds._UPDATE_MAX, true);
  14835. this._setUpdateFlag(Bounds._UPDATE_EXTENT, false);
  14836. }
  14837. getExtent() {
  14838. if (this._getUpdateFlag(Bounds._UPDATE_EXTENT)) {
  14839. this._getExtent(this.getMin(), this.getMax(), this._extent);
  14840. this._setUpdateFlag(Bounds._UPDATE_EXTENT, false);
  14841. }
  14842. return this._extent;
  14843. }
  14844. _getUpdateFlag(type) {
  14845. return (this._updateFlag & type) != 0;
  14846. }
  14847. _setUpdateFlag(type, value) {
  14848. if (value)
  14849. this._updateFlag |= type;
  14850. else
  14851. this._updateFlag &= ~type;
  14852. }
  14853. _getCenter(min, max, out) {
  14854. Vector3.add(min, max, out);
  14855. Vector3.scale(out, 0.5, out);
  14856. }
  14857. _getExtent(min, max, out) {
  14858. Vector3.subtract(max, min, out);
  14859. Vector3.scale(out, 0.5, out);
  14860. }
  14861. _getMin(center, extent, out) {
  14862. Vector3.subtract(center, extent, out);
  14863. }
  14864. _getMax(center, extent, out) {
  14865. Vector3.add(center, extent, out);
  14866. }
  14867. _rotateExtents(extents, rotation, out) {
  14868. var extentsX = extents.x;
  14869. var extentsY = extents.y;
  14870. var extentsZ = extents.z;
  14871. var matE = rotation.elements;
  14872. out.x = Math.abs(matE[0] * extentsX) + Math.abs(matE[4] * extentsY) + Math.abs(matE[8] * extentsZ);
  14873. out.y = Math.abs(matE[1] * extentsX) + Math.abs(matE[5] * extentsY) + Math.abs(matE[9] * extentsZ);
  14874. out.z = Math.abs(matE[2] * extentsX) + Math.abs(matE[6] * extentsY) + Math.abs(matE[10] * extentsZ);
  14875. }
  14876. _tranform(matrix, out) {
  14877. var outCen = out._center;
  14878. var outExt = out._extent;
  14879. Vector3.transformCoordinate(this.getCenter(), matrix, outCen);
  14880. this._rotateExtents(this.getExtent(), matrix, outExt);
  14881. out._boundBox.setCenterAndExtent(outCen, outExt);
  14882. out._updateFlag = 0;
  14883. }
  14884. _getBoundBox() {
  14885. if (this._updateFlag & Bounds._UPDATE_MIN) {
  14886. var min = this._boundBox.min;
  14887. this._getMin(this.getCenter(), this.getExtent(), min);
  14888. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  14889. }
  14890. if (this._updateFlag & Bounds._UPDATE_MAX) {
  14891. var max = this._boundBox.max;
  14892. this._getMax(this.getCenter(), this.getExtent(), max);
  14893. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  14894. }
  14895. return this._boundBox;
  14896. }
  14897. cloneTo(destObject) {
  14898. var destBounds = destObject;
  14899. this.getMin().cloneTo(destBounds._boundBox.min);
  14900. this.getMax().cloneTo(destBounds._boundBox.max);
  14901. this.getCenter().cloneTo(destBounds._center);
  14902. this.getExtent().cloneTo(destBounds._extent);
  14903. destBounds._updateFlag = 0;
  14904. }
  14905. clone() {
  14906. var dest = new Bounds(new Vector3(), new Vector3());
  14907. this.cloneTo(dest);
  14908. return dest;
  14909. }
  14910. }
  14911. Bounds._UPDATE_MIN = 0x01;
  14912. Bounds._UPDATE_MAX = 0x02;
  14913. Bounds._UPDATE_CENTER = 0x04;
  14914. Bounds._UPDATE_EXTENT = 0x08;
  14915. class BaseRender extends Laya.EventDispatcher {
  14916. constructor(owner) {
  14917. super();
  14918. this._indexInList = -1;
  14919. this._indexInCastShadowList = -1;
  14920. this._boundsChange = true;
  14921. this._castShadow = false;
  14922. this._supportOctree = true;
  14923. this._sharedMaterials = [];
  14924. this._visible = true;
  14925. this._indexInOctreeMotionList = -1;
  14926. this._updateMark = -1;
  14927. this._updateRenderType = -1;
  14928. this._isPartOfStaticBatch = false;
  14929. this._staticBatch = null;
  14930. this._id = ++BaseRender._uniqueIDCounter;
  14931. this._indexInCastShadowList = -1;
  14932. this._bounds = new Bounds(Vector3._ZERO, Vector3._ZERO);
  14933. if (Laya.Render.supportWebGLPlusCulling) {
  14934. var length = FrustumCulling._cullingBufferLength;
  14935. this._cullingBufferIndex = length;
  14936. var cullingBuffer = FrustumCulling._cullingBuffer;
  14937. var resizeLength = length + 7;
  14938. if (resizeLength >= cullingBuffer.length) {
  14939. var temp = cullingBuffer;
  14940. cullingBuffer = FrustumCulling._cullingBuffer = new Float32Array(cullingBuffer.length + 4096);
  14941. cullingBuffer.set(temp, 0);
  14942. }
  14943. cullingBuffer[length] = 2;
  14944. FrustumCulling._cullingBufferLength = resizeLength;
  14945. }
  14946. this._renderElements = [];
  14947. this._owner = owner;
  14948. this._enable = true;
  14949. this._materialsInstance = [];
  14950. this._shaderValues = new ShaderData(null);
  14951. this.lightmapIndex = -1;
  14952. this.receiveShadow = false;
  14953. this.sortingFudge = 0.0;
  14954. (owner) && (this._owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  14955. }
  14956. get id() {
  14957. return this._id;
  14958. }
  14959. get lightmapIndex() {
  14960. return this._lightmapIndex;
  14961. }
  14962. set lightmapIndex(value) {
  14963. if (this._lightmapIndex !== value) {
  14964. this._lightmapIndex = value;
  14965. this._applyLightMapParams();
  14966. }
  14967. }
  14968. get lightmapScaleOffset() {
  14969. return this._lightmapScaleOffset;
  14970. }
  14971. set lightmapScaleOffset(value) {
  14972. this._lightmapScaleOffset = value;
  14973. this._shaderValues.setVector(RenderableSprite3D.LIGHTMAPSCALEOFFSET, value);
  14974. this._shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV);
  14975. }
  14976. get enable() {
  14977. return this._enable;
  14978. }
  14979. set enable(value) {
  14980. this._enable = !!value;
  14981. }
  14982. get material() {
  14983. var material = this._sharedMaterials[0];
  14984. if (material && !this._materialsInstance[0]) {
  14985. var insMat = this._getInstanceMaterial(material, 0);
  14986. var renderElement = this._renderElements[0];
  14987. (renderElement) && (renderElement.material = insMat);
  14988. }
  14989. return this._sharedMaterials[0];
  14990. }
  14991. set material(value) {
  14992. this.sharedMaterial = value;
  14993. }
  14994. get materials() {
  14995. for (var i = 0, n = this._sharedMaterials.length; i < n; i++) {
  14996. if (!this._materialsInstance[i]) {
  14997. var insMat = this._getInstanceMaterial(this._sharedMaterials[i], i);
  14998. var renderElement = this._renderElements[i];
  14999. (renderElement) && (renderElement.material = insMat);
  15000. }
  15001. }
  15002. return this._sharedMaterials.slice();
  15003. }
  15004. set materials(value) {
  15005. this.sharedMaterials = value;
  15006. }
  15007. get sharedMaterial() {
  15008. return this._sharedMaterials[0];
  15009. }
  15010. set sharedMaterial(value) {
  15011. var lastValue = this._sharedMaterials[0];
  15012. if (lastValue !== value) {
  15013. this._sharedMaterials[0] = value;
  15014. this._materialsInstance[0] = false;
  15015. this._changeMaterialReference(lastValue, value);
  15016. var renderElement = this._renderElements[0];
  15017. (renderElement) && (renderElement.material = value);
  15018. }
  15019. }
  15020. get sharedMaterials() {
  15021. return this._sharedMaterials.slice();
  15022. }
  15023. set sharedMaterials(value) {
  15024. var materialsInstance = this._materialsInstance;
  15025. var sharedMats = this._sharedMaterials;
  15026. for (var i = 0, n = sharedMats.length; i < n; i++) {
  15027. var lastMat = sharedMats[i];
  15028. (lastMat) && (lastMat._removeReference());
  15029. }
  15030. if (value) {
  15031. var count = value.length;
  15032. materialsInstance.length = count;
  15033. sharedMats.length = count;
  15034. for (i = 0; i < count; i++) {
  15035. lastMat = sharedMats[i];
  15036. var mat = value[i];
  15037. if (lastMat !== mat) {
  15038. materialsInstance[i] = false;
  15039. var renderElement = this._renderElements[i];
  15040. (renderElement) && (renderElement.material = mat);
  15041. }
  15042. if (mat) {
  15043. mat._addReference();
  15044. }
  15045. sharedMats[i] = mat;
  15046. }
  15047. }
  15048. else {
  15049. throw new Error("BaseRender: shadredMaterials value can't be null.");
  15050. }
  15051. }
  15052. get bounds() {
  15053. if (this._boundsChange) {
  15054. this._calculateBoundingBox();
  15055. this._boundsChange = false;
  15056. }
  15057. return this._bounds;
  15058. }
  15059. set receiveShadow(value) {
  15060. if (this._receiveShadow !== value) {
  15061. this._receiveShadow = value;
  15062. if (value)
  15063. this._shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW);
  15064. else
  15065. this._shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW);
  15066. }
  15067. }
  15068. get receiveShadow() {
  15069. return this._receiveShadow;
  15070. }
  15071. get castShadow() {
  15072. return this._castShadow;
  15073. }
  15074. set castShadow(value) {
  15075. this._castShadow = value;
  15076. }
  15077. get isPartOfStaticBatch() {
  15078. return this._isPartOfStaticBatch;
  15079. }
  15080. _getOctreeNode() {
  15081. return this._octreeNode;
  15082. }
  15083. _setOctreeNode(value) {
  15084. this._octreeNode = value;
  15085. }
  15086. _getIndexInMotionList() {
  15087. return this._indexInOctreeMotionList;
  15088. }
  15089. _setIndexInMotionList(value) {
  15090. this._indexInOctreeMotionList = value;
  15091. }
  15092. _changeMaterialReference(lastValue, value) {
  15093. (lastValue) && (lastValue._removeReference());
  15094. value._addReference();
  15095. }
  15096. _getInstanceMaterial(material, index) {
  15097. var insMat = material.clone();
  15098. insMat.name = insMat.name + "(Instance)";
  15099. this._materialsInstance[index] = true;
  15100. this._changeMaterialReference(this._sharedMaterials[index], insMat);
  15101. this._sharedMaterials[index] = insMat;
  15102. return insMat;
  15103. }
  15104. _applyLightMapParams() {
  15105. if (this._scene && this._lightmapIndex >= 0) {
  15106. var lightMaps = this._scene.getlightmaps();
  15107. if (this._lightmapIndex < lightMaps.length) {
  15108. this._shaderValues.addDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  15109. this._shaderValues.setTexture(RenderableSprite3D.LIGHTMAP, lightMaps[this._lightmapIndex]);
  15110. }
  15111. else {
  15112. this._shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  15113. }
  15114. }
  15115. else {
  15116. this._shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  15117. }
  15118. }
  15119. _onWorldMatNeedChange(flag) {
  15120. this._boundsChange = true;
  15121. if (this._octreeNode) {
  15122. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  15123. if (flag) {
  15124. if (this._indexInOctreeMotionList === -1)
  15125. this._octreeNode._octree.addMotionObject(this);
  15126. }
  15127. }
  15128. }
  15129. _calculateBoundingBox() {
  15130. throw ("BaseRender: must override it.");
  15131. }
  15132. _getIndexInList() {
  15133. return this._indexInList;
  15134. }
  15135. _setIndexInList(index) {
  15136. this._indexInList = index;
  15137. }
  15138. _setBelongScene(scene) {
  15139. if (this._scene !== scene) {
  15140. this._scene = scene;
  15141. this._applyLightMapParams();
  15142. }
  15143. }
  15144. _needRender(boundFrustum, context) {
  15145. return true;
  15146. }
  15147. _renderUpdate(context, transform) {
  15148. }
  15149. _renderUpdateWithCamera(context, transform) {
  15150. }
  15151. _revertBatchRenderUpdate(context) {
  15152. }
  15153. _destroy() {
  15154. (this._indexInOctreeMotionList !== -1) && (this._octreeNode._octree.removeMotionObject(this));
  15155. this.offAll();
  15156. var i = 0, n = 0;
  15157. for (i = 0, n = this._renderElements.length; i < n; i++)
  15158. this._renderElements[i].destroy();
  15159. for (i = 0, n = this._sharedMaterials.length; i < n; i++)
  15160. (this._sharedMaterials[i].destroyed) || (this._sharedMaterials[i]._removeReference());
  15161. this._renderElements = null;
  15162. this._owner = null;
  15163. this._sharedMaterials = null;
  15164. this._bounds = null;
  15165. this._lightmapScaleOffset = null;
  15166. }
  15167. markAsUnStatic() {
  15168. if (this._isPartOfStaticBatch) {
  15169. MeshRenderStaticBatchManager.instance._removeRenderSprite(this._owner);
  15170. this._isPartOfStaticBatch = false;
  15171. }
  15172. }
  15173. }
  15174. BaseRender._tempBoundBoxCorners = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  15175. BaseRender._uniqueIDCounter = 0;
  15176. class MeshRenderer extends BaseRender {
  15177. constructor(owner) {
  15178. super(owner);
  15179. this._revertStaticBatchDefineUV1 = false;
  15180. this._revertStaticBatchDefineLightMapUV = false;
  15181. this._projectionViewWorldMatrix = new Matrix4x4();
  15182. }
  15183. _createRenderElement() {
  15184. return new SubMeshRenderElement();
  15185. }
  15186. _onMeshChange(mesh) {
  15187. if (mesh) {
  15188. var count = mesh.subMeshCount;
  15189. this._renderElements.length = count;
  15190. for (var i = 0; i < count; i++) {
  15191. var renderElement = this._renderElements[i];
  15192. if (!renderElement) {
  15193. var material = this.sharedMaterials[i];
  15194. renderElement = this._renderElements[i] = this._createRenderElement();
  15195. renderElement.setTransform(this._owner._transform);
  15196. renderElement.render = this;
  15197. renderElement.material = material ? material : BlinnPhongMaterial.defaultMaterial;
  15198. }
  15199. renderElement.setGeometry(mesh.getSubMesh(i));
  15200. }
  15201. }
  15202. else {
  15203. this._renderElements.length = 0;
  15204. }
  15205. this._boundsChange = true;
  15206. }
  15207. _calculateBoundingBox() {
  15208. var sharedMesh = this._owner.meshFilter.sharedMesh;
  15209. if (sharedMesh) {
  15210. var worldMat = this._owner.transform.worldMatrix;
  15211. sharedMesh.bounds._tranform(worldMat, this._bounds);
  15212. }
  15213. if (Laya.Render.supportWebGLPlusCulling) {
  15214. var min = this._bounds.getMin();
  15215. var max = this._bounds.getMax();
  15216. var buffer = FrustumCulling._cullingBuffer;
  15217. buffer[this._cullingBufferIndex + 1] = min.x;
  15218. buffer[this._cullingBufferIndex + 2] = min.y;
  15219. buffer[this._cullingBufferIndex + 3] = min.z;
  15220. buffer[this._cullingBufferIndex + 4] = max.x;
  15221. buffer[this._cullingBufferIndex + 5] = max.y;
  15222. buffer[this._cullingBufferIndex + 6] = max.z;
  15223. }
  15224. }
  15225. _needRender(boundFrustum, context) {
  15226. if (boundFrustum)
  15227. return boundFrustum.intersects(this.bounds._getBoundBox());
  15228. else
  15229. return true;
  15230. }
  15231. _renderUpdate(context, transform) {
  15232. var element = context.renderElement;
  15233. switch (element.renderType) {
  15234. case RenderElement.RENDERTYPE_NORMAL:
  15235. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  15236. break;
  15237. case RenderElement.RENDERTYPE_STATICBATCH:
  15238. if (transform)
  15239. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  15240. else
  15241. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  15242. if (!this._shaderValues.hasDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1)) {
  15243. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  15244. this._revertStaticBatchDefineUV1 = true;
  15245. }
  15246. else {
  15247. this._revertStaticBatchDefineUV1 = false;
  15248. }
  15249. if (this._shaderValues.hasDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV)) {
  15250. this._shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV);
  15251. this._revertStaticBatchDefineLightMapUV = true;
  15252. }
  15253. else {
  15254. this._revertStaticBatchDefineLightMapUV = false;
  15255. }
  15256. break;
  15257. case RenderElement.RENDERTYPE_VERTEXBATCH:
  15258. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  15259. break;
  15260. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  15261. var worldMatrixData = SubMeshInstanceBatch.instance.instanceWorldMatrixData;
  15262. var insBatches = element.instanceBatchElementList;
  15263. var elements = insBatches.elements;
  15264. var count = insBatches.length;
  15265. for (var i = 0; i < count; i++)
  15266. worldMatrixData.set(elements[i]._transform.worldMatrix.elements, i * 16);
  15267. SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer.setData(worldMatrixData.buffer, 0, 0, count * 16 * 4);
  15268. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  15269. break;
  15270. }
  15271. }
  15272. _renderUpdateWithCamera(context, transform) {
  15273. var projectionView = context.projectionViewMatrix;
  15274. var element = context.renderElement;
  15275. switch (element.renderType) {
  15276. case RenderElement.RENDERTYPE_NORMAL:
  15277. case RenderElement.RENDERTYPE_STATICBATCH:
  15278. case RenderElement.RENDERTYPE_VERTEXBATCH:
  15279. if (transform) {
  15280. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  15281. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  15282. }
  15283. else {
  15284. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  15285. }
  15286. break;
  15287. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  15288. var mvpMatrixData = SubMeshInstanceBatch.instance.instanceMVPMatrixData;
  15289. var insBatches = element.instanceBatchElementList;
  15290. var elements = insBatches.elements;
  15291. var count = insBatches.length;
  15292. for (var i = 0; i < count; i++) {
  15293. var worldMat = elements[i]._transform.worldMatrix;
  15294. Utils3D.mulMatrixByArray(projectionView.elements, 0, worldMat.elements, 0, mvpMatrixData, i * 16);
  15295. }
  15296. SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer.setData(mvpMatrixData.buffer, 0, 0, count * 16 * 4);
  15297. break;
  15298. }
  15299. }
  15300. _revertBatchRenderUpdate(context) {
  15301. var element = context.renderElement;
  15302. switch (element.renderType) {
  15303. case RenderElement.RENDERTYPE_STATICBATCH:
  15304. if (this._revertStaticBatchDefineUV1)
  15305. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  15306. if (this._revertStaticBatchDefineLightMapUV)
  15307. this._shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV);
  15308. break;
  15309. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  15310. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  15311. break;
  15312. }
  15313. }
  15314. _destroy() {
  15315. (this._isPartOfStaticBatch) && (MeshRenderStaticBatchManager.instance._removeRenderSprite(this._owner));
  15316. super._destroy();
  15317. }
  15318. }
  15319. class MeshFilter {
  15320. constructor(owner) {
  15321. this._owner = owner;
  15322. }
  15323. get sharedMesh() {
  15324. return this._sharedMesh;
  15325. }
  15326. set sharedMesh(value) {
  15327. if (this._sharedMesh !== value) {
  15328. var defineDatas = this._owner._render._shaderValues;
  15329. var lastValue = this._sharedMesh;
  15330. if (lastValue) {
  15331. lastValue._removeReference();
  15332. this._getMeshDefine(lastValue, MeshFilter._meshVerticeDefine);
  15333. for (var i = 0, n = MeshFilter._meshVerticeDefine.length; i < n; i++)
  15334. defineDatas.removeDefine(MeshFilter._meshVerticeDefine[i]);
  15335. }
  15336. if (value) {
  15337. value._addReference();
  15338. this._getMeshDefine(value, MeshFilter._meshVerticeDefine);
  15339. for (var i = 0, n = MeshFilter._meshVerticeDefine.length; i < n; i++)
  15340. defineDatas.addDefine(MeshFilter._meshVerticeDefine[i]);
  15341. }
  15342. this._owner._render._onMeshChange(value);
  15343. this._sharedMesh = value;
  15344. }
  15345. }
  15346. _getMeshDefine(mesh, out) {
  15347. out.length = 0;
  15348. var define;
  15349. for (var i = 0, n = mesh._subMeshes.length; i < n; i++) {
  15350. var subMesh = mesh.getSubMesh(i);
  15351. var vertexElements = subMesh._vertexBuffer._vertexDeclaration._vertexElements;
  15352. for (var j = 0, m = vertexElements.length; j < m; j++) {
  15353. var vertexElement = vertexElements[j];
  15354. var name = vertexElement._elementUsage;
  15355. switch (name) {
  15356. case VertexMesh.MESH_COLOR0:
  15357. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_COLOR);
  15358. break;
  15359. case VertexMesh.MESH_TEXTURECOORDINATE0:
  15360. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV0);
  15361. break;
  15362. case VertexMesh.MESH_TEXTURECOORDINATE1:
  15363. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  15364. break;
  15365. }
  15366. }
  15367. }
  15368. return define;
  15369. }
  15370. destroy() {
  15371. this._owner = null;
  15372. (this._sharedMesh) && (this._sharedMesh._removeReference(), this._sharedMesh = null);
  15373. }
  15374. }
  15375. MeshFilter._meshVerticeDefine = [];
  15376. class SubMeshDynamicBatch extends GeometryElement {
  15377. constructor() {
  15378. super();
  15379. this._bufferState = new BufferState();
  15380. var gl = Laya.LayaGL.instance;
  15381. var maxVerDec = VertexMesh.getVertexDeclaration("POSITION,NORMAL,COLOR,UV,UV1,TANGENT");
  15382. var maxByteCount = maxVerDec.vertexStride * SubMeshDynamicBatch.maxIndicesCount;
  15383. this._vertices = new Float32Array(maxByteCount / 4);
  15384. this._vertexBuffer = new VertexBuffer3D(maxByteCount, gl.DYNAMIC_DRAW);
  15385. this._indices = new Int16Array(SubMeshDynamicBatch.maxIndicesCount);
  15386. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._indices.length, gl.DYNAMIC_DRAW);
  15387. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  15388. Laya.Resource._addMemory(memorySize, memorySize);
  15389. }
  15390. static __init__() {
  15391. SubMeshDynamicBatch.instance = new SubMeshDynamicBatch();
  15392. }
  15393. _getBatchVertices(vertexDeclaration, batchVertices, batchOffset, transform, element, subMesh) {
  15394. var vertexFloatCount = vertexDeclaration.vertexStride / 4;
  15395. var oriVertexes = subMesh._vertexBuffer.getFloat32Data();
  15396. var lightmapScaleOffset = element.render.lightmapScaleOffset;
  15397. var multiSubMesh = element._dynamicMultiSubMesh;
  15398. var vertexCount = element._dynamicVertexCount;
  15399. element._computeWorldPositionsAndNormals(this._positionOffset, this._normalOffset, multiSubMesh, vertexCount);
  15400. var worldPositions = element._dynamicWorldPositions;
  15401. var worldNormals = element._dynamicWorldNormals;
  15402. var indices = subMesh._indices;
  15403. for (var i = 0; i < vertexCount; i++) {
  15404. var index = multiSubMesh ? indices[i] : i;
  15405. var oriOffset = index * vertexFloatCount;
  15406. var bakeOffset = (i + batchOffset) * vertexFloatCount;
  15407. var oriOff = i * 3;
  15408. var bakOff = bakeOffset + this._positionOffset;
  15409. batchVertices[bakOff] = worldPositions[oriOff];
  15410. batchVertices[bakOff + 1] = worldPositions[oriOff + 1];
  15411. batchVertices[bakOff + 2] = worldPositions[oriOff + 2];
  15412. if (this._normalOffset !== -1) {
  15413. bakOff = bakeOffset + this._normalOffset;
  15414. batchVertices[bakOff] = worldNormals[oriOff];
  15415. batchVertices[bakOff + 1] = worldNormals[oriOff + 1];
  15416. batchVertices[bakOff + 2] = worldNormals[oriOff + 2];
  15417. }
  15418. if (this._colorOffset !== -1) {
  15419. bakOff = bakeOffset + this._colorOffset;
  15420. oriOff = oriOffset + this._colorOffset;
  15421. batchVertices[bakOff] = oriVertexes[oriOff];
  15422. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  15423. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  15424. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  15425. }
  15426. if (this._uv0Offset !== -1) {
  15427. bakOff = bakeOffset + this._uv0Offset;
  15428. oriOff = oriOffset + this._uv0Offset;
  15429. batchVertices[bakOff] = oriVertexes[oriOff];
  15430. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  15431. }
  15432. if (this._sTangentOffset !== -1) {
  15433. bakOff = bakeOffset + this._sTangentOffset;
  15434. oriOff = oriOffset + this._sTangentOffset;
  15435. batchVertices[bakOff] = oriVertexes[oriOff];
  15436. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  15437. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  15438. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  15439. bakOff = bakeOffset + this._sTangentOffset;
  15440. oriOff = oriOffset + this._sTangentOffset;
  15441. batchVertices[bakOff] = oriVertexes[oriOff];
  15442. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  15443. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  15444. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  15445. }
  15446. }
  15447. }
  15448. _getBatchIndices(batchIndices, batchIndexCount, batchVertexCount, transform, subMesh, multiSubMesh) {
  15449. var subIndices = subMesh._indices;
  15450. var k, m, batchOffset;
  15451. var isInvert = transform._isFrontFaceInvert;
  15452. if (multiSubMesh) {
  15453. if (isInvert) {
  15454. for (k = 0, m = subIndices.length; k < m; k += 3) {
  15455. batchOffset = batchIndexCount + k;
  15456. var index = batchVertexCount + k;
  15457. batchIndices[batchOffset] = index;
  15458. batchIndices[batchOffset + 1] = index + 2;
  15459. batchIndices[batchOffset + 2] = index + 1;
  15460. }
  15461. }
  15462. else {
  15463. for (k = 0, m = subIndices.length; k < m; k += 3) {
  15464. batchOffset = batchIndexCount + k;
  15465. index = batchVertexCount + k;
  15466. batchIndices[batchOffset] = index;
  15467. batchIndices[batchOffset + 1] = index + 1;
  15468. batchIndices[batchOffset + 2] = index + 2;
  15469. }
  15470. }
  15471. }
  15472. else {
  15473. if (isInvert) {
  15474. for (k = 0, m = subIndices.length; k < m; k += 3) {
  15475. batchOffset = batchIndexCount + k;
  15476. batchIndices[batchOffset] = batchVertexCount + subIndices[k];
  15477. batchIndices[batchOffset + 1] = batchVertexCount + subIndices[k + 2];
  15478. batchIndices[batchOffset + 2] = batchVertexCount + subIndices[k + 1];
  15479. }
  15480. }
  15481. else {
  15482. for (k = 0, m = subIndices.length; k < m; k += 3) {
  15483. batchOffset = batchIndexCount + k;
  15484. batchIndices[batchOffset] = batchVertexCount + subIndices[k];
  15485. batchIndices[batchOffset + 1] = batchVertexCount + subIndices[k + 1];
  15486. batchIndices[batchOffset + 2] = batchVertexCount + subIndices[k + 2];
  15487. }
  15488. }
  15489. }
  15490. }
  15491. _flush(vertexCount, indexCount) {
  15492. var gl = Laya.LayaGL.instance;
  15493. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, vertexCount * (this._bufferState.vertexDeclaration.vertexStride));
  15494. this._indexBuffer.setData(this._indices, 0, 0, indexCount);
  15495. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  15496. }
  15497. _prepareRender(state) {
  15498. var element = state.renderElement;
  15499. var vertexDeclaration = element.vertexBatchVertexDeclaration;
  15500. this._bufferState = ILaya3D.MeshRenderDynamicBatchManager.instance._getBufferState(vertexDeclaration);
  15501. this._positionOffset = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  15502. var normalElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_NORMAL0);
  15503. this._normalOffset = normalElement ? normalElement._offset / 4 : -1;
  15504. var colorElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  15505. this._colorOffset = colorElement ? colorElement._offset / 4 : -1;
  15506. var uv0Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  15507. this._uv0Offset = uv0Element ? uv0Element._offset / 4 : -1;
  15508. var uv1Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE1);
  15509. this._uv1Offset = uv1Element ? uv1Element._offset / 4 : -1;
  15510. var tangentElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TANGENT0);
  15511. this._sTangentOffset = tangentElement ? tangentElement._offset / 4 : -1;
  15512. return true;
  15513. }
  15514. _render(context) {
  15515. this._bufferState.bind();
  15516. var element = context.renderElement;
  15517. var vertexDeclaration = element.vertexBatchVertexDeclaration;
  15518. var batchElements = element.vertexBatchElementList;
  15519. var batchVertexCount = 0;
  15520. var batchIndexCount = 0;
  15521. var floatStride = vertexDeclaration.vertexStride / 4;
  15522. var renderBatchCount = 0;
  15523. var elementCount = batchElements.length;
  15524. var elements = batchElements.elements;
  15525. for (var i = 0; i < elementCount; i++) {
  15526. var subElement = elements[i];
  15527. var subMesh = subElement._geometry;
  15528. var indexCount = subMesh._indexCount;
  15529. if (batchIndexCount + indexCount > SubMeshDynamicBatch.maxIndicesCount) {
  15530. this._flush(batchVertexCount, batchIndexCount);
  15531. renderBatchCount++;
  15532. Laya.Stat.trianglesFaces += batchIndexCount / 3;
  15533. batchVertexCount = batchIndexCount = 0;
  15534. }
  15535. var transform = subElement._transform;
  15536. this._getBatchVertices(vertexDeclaration, this._vertices, batchVertexCount, transform, subElement, subMesh);
  15537. this._getBatchIndices(this._indices, batchIndexCount, batchVertexCount, transform, subMesh, subElement._dynamicMultiSubMesh);
  15538. batchVertexCount += subElement._dynamicVertexCount;
  15539. batchIndexCount += indexCount;
  15540. }
  15541. this._flush(batchVertexCount, batchIndexCount);
  15542. renderBatchCount++;
  15543. Laya.Stat.renderBatches += renderBatchCount;
  15544. Laya.Stat.savedRenderBatches += elementCount - renderBatchCount;
  15545. Laya.Stat.trianglesFaces += batchIndexCount / 3;
  15546. }
  15547. }
  15548. SubMeshDynamicBatch.maxAllowVertexCount = 10;
  15549. SubMeshDynamicBatch.maxAllowAttribueCount = 900;
  15550. SubMeshDynamicBatch.maxIndicesCount = 32000;
  15551. class MeshRenderDynamicBatchManager extends DynamicBatchManager {
  15552. constructor() {
  15553. super();
  15554. this._instanceBatchOpaqueMarks = [];
  15555. this._vertexBatchOpaqueMarks = [];
  15556. this._cacheBufferStates = [];
  15557. this._updateCountMark = 0;
  15558. }
  15559. getInstanceBatchOpaquaMark(receiveShadow, materialID, subMeshID, invertFace) {
  15560. var instanceReceiveShadowMarks = (this._instanceBatchOpaqueMarks[receiveShadow ? 0 : 1]) || (this._instanceBatchOpaqueMarks[receiveShadow ? 0 : 1] = []);
  15561. var instanceMaterialMarks = (instanceReceiveShadowMarks[materialID]) || (instanceReceiveShadowMarks[materialID] = []);
  15562. var instancSubMeshMarks = (instanceMaterialMarks[subMeshID]) || (instanceMaterialMarks[subMeshID] = []);
  15563. return instancSubMeshMarks[invertFace ? 1 : 0] || (instancSubMeshMarks[invertFace ? 1 : 0] = new BatchMark());
  15564. }
  15565. getVertexBatchOpaquaMark(lightMapIndex, receiveShadow, materialID, verDecID) {
  15566. var dynLightMapMarks = (this._vertexBatchOpaqueMarks[lightMapIndex]) || (this._vertexBatchOpaqueMarks[lightMapIndex] = []);
  15567. var dynReceiveShadowMarks = (dynLightMapMarks[receiveShadow ? 0 : 1]) || (dynLightMapMarks[receiveShadow ? 0 : 1] = []);
  15568. var dynMaterialMarks = (dynReceiveShadowMarks[materialID]) || (dynReceiveShadowMarks[materialID] = []);
  15569. return dynMaterialMarks[verDecID] || (dynMaterialMarks[verDecID] = new BatchMark());
  15570. }
  15571. _getBufferState(vertexDeclaration) {
  15572. var bufferState = this._cacheBufferStates[vertexDeclaration.id];
  15573. if (!bufferState) {
  15574. var instance = SubMeshDynamicBatch.instance;
  15575. bufferState = new BufferState();
  15576. bufferState.bind();
  15577. var vertexBuffer = instance._vertexBuffer;
  15578. vertexBuffer.vertexDeclaration = vertexDeclaration;
  15579. bufferState.applyVertexBuffer(vertexBuffer);
  15580. bufferState.applyIndexBuffer(instance._indexBuffer);
  15581. bufferState.unBind();
  15582. this._cacheBufferStates[vertexDeclaration.id] = bufferState;
  15583. }
  15584. return bufferState;
  15585. }
  15586. _getBatchRenderElementFromPool() {
  15587. var renderElement = this._batchRenderElementPool[this._batchRenderElementPoolIndex++];
  15588. if (!renderElement) {
  15589. renderElement = new SubMeshRenderElement();
  15590. this._batchRenderElementPool[this._batchRenderElementPoolIndex - 1] = renderElement;
  15591. renderElement.vertexBatchElementList = new SingletonList();
  15592. renderElement.instanceBatchElementList = new SingletonList();
  15593. }
  15594. return renderElement;
  15595. }
  15596. _clear() {
  15597. super._clear();
  15598. this._updateCountMark++;
  15599. }
  15600. }
  15601. MeshRenderDynamicBatchManager.instance = new MeshRenderDynamicBatchManager();
  15602. class MeshSprite3D extends RenderableSprite3D {
  15603. static __init__() {
  15604. MeshSprite3DShaderDeclaration.SHADERDEFINE_UV0 = Shader3D.getDefineByName("UV");
  15605. MeshSprite3DShaderDeclaration.SHADERDEFINE_COLOR = Shader3D.getDefineByName("COLOR");
  15606. MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1 = Shader3D.getDefineByName("UV1");
  15607. MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE = Shader3D.getDefineByName("GPU_INSTANCE");
  15608. StaticBatchManager._registerManager(MeshRenderStaticBatchManager.instance);
  15609. DynamicBatchManager._registerManager(MeshRenderDynamicBatchManager.instance);
  15610. }
  15611. get meshFilter() {
  15612. return this._meshFilter;
  15613. }
  15614. get meshRenderer() {
  15615. return this._render;
  15616. }
  15617. constructor(mesh = null, name = null) {
  15618. super(name);
  15619. this._meshFilter = new MeshFilter(this);
  15620. this._render = new MeshRenderer(this);
  15621. (mesh) && (this._meshFilter.sharedMesh = mesh);
  15622. }
  15623. _parse(data, spriteMap) {
  15624. super._parse(data, spriteMap);
  15625. var render = this.meshRenderer;
  15626. var lightmapIndex = data.lightmapIndex;
  15627. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  15628. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  15629. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  15630. (data.meshPath != undefined) && (this.meshFilter.sharedMesh = Laya.Loader.getRes(data.meshPath));
  15631. (data.enableRender != undefined) && (this.meshRenderer.enable = data.enableRender);
  15632. var materials = data.materials;
  15633. if (materials) {
  15634. var sharedMaterials = render.sharedMaterials;
  15635. var materialCount = materials.length;
  15636. sharedMaterials.length = materialCount;
  15637. for (var i = 0; i < materialCount; i++) {
  15638. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  15639. }
  15640. render.sharedMaterials = sharedMaterials;
  15641. }
  15642. }
  15643. _addToInitStaticBatchManager() {
  15644. if (this.meshFilter.sharedMesh)
  15645. MeshRenderStaticBatchManager.instance._addBatchSprite(this);
  15646. }
  15647. _cloneTo(destObject, rootSprite, dstSprite) {
  15648. var meshSprite3D = destObject;
  15649. meshSprite3D._meshFilter.sharedMesh = this._meshFilter.sharedMesh;
  15650. var meshRender = this._render;
  15651. var destMeshRender = meshSprite3D._render;
  15652. destMeshRender.enable = meshRender.enable;
  15653. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  15654. destMeshRender.castShadow = meshRender.castShadow;
  15655. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  15656. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  15657. destMeshRender.lightmapIndex = meshRender.lightmapIndex;
  15658. destMeshRender.receiveShadow = meshRender.receiveShadow;
  15659. destMeshRender.sortingFudge = meshRender.sortingFudge;
  15660. super._cloneTo(destObject, rootSprite, dstSprite);
  15661. }
  15662. destroy(destroyChild = true) {
  15663. if (this.destroyed)
  15664. return;
  15665. super.destroy(destroyChild);
  15666. this._meshFilter.destroy();
  15667. }
  15668. _create() {
  15669. return new MeshSprite3D();
  15670. }
  15671. }
  15672. class GradientMode {
  15673. }
  15674. GradientMode.Blend = 0;
  15675. GradientMode.Fixed = 1;
  15676. class Gradient {
  15677. constructor(maxColorRGBKeyCount, maxColorAlphaKeyCount) {
  15678. this._mode = 0;
  15679. this._maxColorRGBKeysCount = 0;
  15680. this._maxColorAlphaKeysCount = 0;
  15681. this._colorRGBKeysCount = 0;
  15682. this._colorAlphaKeysCount = 0;
  15683. this._alphaElements = null;
  15684. this._rgbElements = null;
  15685. this._maxColorRGBKeysCount = maxColorRGBKeyCount;
  15686. this._maxColorAlphaKeysCount = maxColorAlphaKeyCount;
  15687. this._rgbElements = new Float32Array(maxColorRGBKeyCount * 4);
  15688. this._alphaElements = new Float32Array(maxColorAlphaKeyCount * 2);
  15689. }
  15690. get mode() {
  15691. return this._mode;
  15692. }
  15693. set mode(value) {
  15694. this._mode = value;
  15695. }
  15696. get colorRGBKeysCount() {
  15697. return this._colorRGBKeysCount;
  15698. }
  15699. get colorAlphaKeysCount() {
  15700. return this._colorAlphaKeysCount;
  15701. }
  15702. get maxColorRGBKeysCount() {
  15703. return this._maxColorRGBKeysCount;
  15704. }
  15705. get maxColorAlphaKeysCount() {
  15706. return this._maxColorAlphaKeysCount;
  15707. }
  15708. addColorRGB(key, value) {
  15709. if (this._colorRGBKeysCount < this._maxColorRGBKeysCount) {
  15710. var offset = this._colorRGBKeysCount * 4;
  15711. this._rgbElements[offset] = key;
  15712. this._rgbElements[offset + 1] = value.r;
  15713. this._rgbElements[offset + 2] = value.g;
  15714. this._rgbElements[offset + 3] = value.b;
  15715. this._colorRGBKeysCount++;
  15716. }
  15717. else {
  15718. console.warn("Gradient:warning:data count must lessEqual than " + this._maxColorRGBKeysCount);
  15719. }
  15720. }
  15721. addColorAlpha(key, value) {
  15722. if (this._colorAlphaKeysCount < this._maxColorAlphaKeysCount) {
  15723. var offset = this._colorAlphaKeysCount * 2;
  15724. this._alphaElements[offset] = key;
  15725. this._alphaElements[offset + 1] = value;
  15726. this._colorAlphaKeysCount++;
  15727. }
  15728. else {
  15729. console.warn("Gradient:warning:data count must lessEqual than " + this._maxColorAlphaKeysCount);
  15730. }
  15731. }
  15732. updateColorRGB(index, key, value) {
  15733. if (index < this._colorRGBKeysCount) {
  15734. var offset = index * 4;
  15735. this._rgbElements[offset] = key;
  15736. this._rgbElements[offset + 1] = value.r;
  15737. this._rgbElements[offset + 2] = value.g;
  15738. this._rgbElements[offset + 3] = value.b;
  15739. }
  15740. else {
  15741. console.warn("Gradient:warning:index must lessEqual than colorRGBKeysCount:" + this._colorRGBKeysCount);
  15742. }
  15743. }
  15744. updateColorAlpha(index, key, value) {
  15745. if (index < this._colorAlphaKeysCount) {
  15746. var offset = index * 2;
  15747. this._alphaElements[offset] = key;
  15748. this._alphaElements[offset + 1] = value;
  15749. }
  15750. else {
  15751. console.warn("Gradient:warning:index must lessEqual than colorAlphaKeysCount:" + this._colorAlphaKeysCount);
  15752. }
  15753. }
  15754. evaluateColorRGB(lerpFactor, out, startSearchIndex = 0, reverseSearch = false) {
  15755. lerpFactor = Math.min(Math.max(lerpFactor, 0.0), 1.0);
  15756. var rgbElements = this._rgbElements;
  15757. var curIndex = startSearchIndex;
  15758. if (reverseSearch) {
  15759. for (var i = curIndex; i >= 0; i--) {
  15760. var offset = i * 4;
  15761. var left = rgbElements[offset];
  15762. if (lerpFactor === left) {
  15763. out.r = rgbElements[offset + 1];
  15764. out.g = rgbElements[offset + 2];
  15765. out.b = rgbElements[offset + 3];
  15766. return curIndex;
  15767. }
  15768. switch (this._mode) {
  15769. case GradientMode.Blend:
  15770. if (lerpFactor > left) {
  15771. var right = rgbElements[offset + 4];
  15772. if (lerpFactor > right)
  15773. throw "Gradient:wrong startSearchIndex.";
  15774. var diff = right - left;
  15775. var y1 = right - lerpFactor;
  15776. var y2 = lerpFactor - left;
  15777. out.r = (y1 * rgbElements[offset + 1] + y2 * rgbElements[offset + 5]) / diff;
  15778. out.g = (y1 * rgbElements[offset + 2] + y2 * rgbElements[offset + 6]) / diff;
  15779. out.b = (y1 * rgbElements[offset + 3] + y2 * rgbElements[offset + 7]) / diff;
  15780. return curIndex;
  15781. }
  15782. else {
  15783. curIndex--;
  15784. continue;
  15785. }
  15786. case GradientMode.Fixed:
  15787. if (lerpFactor > left) {
  15788. if (lerpFactor > rgbElements[offset + 4])
  15789. throw "Gradient:wrong startSearchIndex.";
  15790. out.r = rgbElements[offset + 5];
  15791. out.g = rgbElements[offset + 6];
  15792. out.b = rgbElements[offset + 7];
  15793. return curIndex;
  15794. }
  15795. else {
  15796. curIndex--;
  15797. continue;
  15798. }
  15799. default:
  15800. throw "Gradient:unknown mode.";
  15801. }
  15802. }
  15803. }
  15804. else {
  15805. for (var i = 0, n = this._rgbElements.length; i < n; i++) {
  15806. offset = i * 4;
  15807. var right = rgbElements[offset];
  15808. if (lerpFactor === right) {
  15809. out.r = rgbElements[offset + 1];
  15810. out.g = rgbElements[offset + 2];
  15811. out.b = rgbElements[offset + 3];
  15812. return curIndex;
  15813. }
  15814. switch (this._mode) {
  15815. case GradientMode.Blend:
  15816. if (lerpFactor < right) {
  15817. var left = rgbElements[offset - 4];
  15818. if (lerpFactor < left)
  15819. throw "Gradient:wrong startSearchIndex.";
  15820. var diff = right - left;
  15821. var y1 = right - lerpFactor;
  15822. var y2 = lerpFactor - left;
  15823. out.r = (y1 * rgbElements[offset - 3] + y2 * rgbElements[offset + 1]) / diff;
  15824. out.g = (y1 * rgbElements[offset - 2] + y2 * rgbElements[offset + 2]) / diff;
  15825. out.b = (y1 * rgbElements[offset - 1] + y2 * rgbElements[offset + 3]) / diff;
  15826. return curIndex;
  15827. }
  15828. else {
  15829. curIndex++;
  15830. continue;
  15831. }
  15832. case GradientMode.Fixed:
  15833. if (lerpFactor < right) {
  15834. if (lerpFactor < rgbElements[offset - 4])
  15835. throw "Gradient:wrong startSearchIndex.";
  15836. out.r = rgbElements[offset + 1];
  15837. out.g = rgbElements[offset + 2];
  15838. out.b = rgbElements[offset + 3];
  15839. return curIndex;
  15840. }
  15841. else {
  15842. curIndex++;
  15843. continue;
  15844. }
  15845. default:
  15846. throw "Gradient:unknown mode.";
  15847. }
  15848. }
  15849. }
  15850. return curIndex;
  15851. }
  15852. evaluateColorAlpha(lerpFactor, outColor, startSearchIndex = 0, reverseSearch = false) {
  15853. lerpFactor = Math.min(Math.max(lerpFactor, 0.0), 1.0);
  15854. var alphaElements = this._alphaElements;
  15855. var curIndex = startSearchIndex;
  15856. if (reverseSearch) {
  15857. for (var i = curIndex; i >= 0; i--) {
  15858. var offset = i * 2;
  15859. var left = alphaElements[offset];
  15860. if (lerpFactor === left) {
  15861. outColor.a = alphaElements[offset + 1];
  15862. return curIndex;
  15863. }
  15864. switch (this._mode) {
  15865. case GradientMode.Blend:
  15866. if (lerpFactor > left) {
  15867. var right = alphaElements[offset + 2];
  15868. if (lerpFactor > right)
  15869. throw "Gradient:wrong startSearchIndex.";
  15870. var diff = right - left;
  15871. var x1 = right - lerpFactor;
  15872. var x2 = lerpFactor - left;
  15873. outColor.a = (x1 * alphaElements[offset + 1] + x2 * alphaElements[offset + 3]) / diff;
  15874. return curIndex;
  15875. }
  15876. else {
  15877. curIndex--;
  15878. continue;
  15879. }
  15880. case GradientMode.Fixed:
  15881. if (lerpFactor > left) {
  15882. if (lerpFactor > alphaElements[offset + 2])
  15883. throw "Gradient:wrong startSearchIndex.";
  15884. outColor.a = alphaElements[offset + 3];
  15885. return curIndex;
  15886. }
  15887. else {
  15888. curIndex--;
  15889. continue;
  15890. }
  15891. default:
  15892. throw "Gradient:unknown mode.";
  15893. }
  15894. }
  15895. }
  15896. else {
  15897. for (var i = curIndex, n = this._alphaElements.length; i < n; i++) {
  15898. var offset = i * 2;
  15899. var right = alphaElements[offset];
  15900. if (lerpFactor === right) {
  15901. outColor.a = alphaElements[offset + 1];
  15902. return curIndex;
  15903. }
  15904. switch (this._mode) {
  15905. case GradientMode.Blend:
  15906. if (lerpFactor < right) {
  15907. var left = alphaElements[offset - 2];
  15908. if (lerpFactor < left)
  15909. throw "Gradient:wrong startSearchIndex.";
  15910. var diff = right - left;
  15911. var x1 = right - lerpFactor;
  15912. var x2 = lerpFactor - left;
  15913. outColor.a = (x1 * alphaElements[offset - 1] + x2 * alphaElements[offset + 1]) / diff;
  15914. return curIndex;
  15915. }
  15916. else {
  15917. curIndex++;
  15918. continue;
  15919. }
  15920. case GradientMode.Fixed:
  15921. if (lerpFactor < right) {
  15922. if (lerpFactor < alphaElements[offset - 2])
  15923. throw "Gradient:wrong startSearchIndex.";
  15924. outColor.a = alphaElements[offset + 1];
  15925. return curIndex;
  15926. }
  15927. else {
  15928. curIndex++;
  15929. continue;
  15930. }
  15931. default:
  15932. throw "Gradient:unknown mode.";
  15933. }
  15934. }
  15935. }
  15936. return curIndex;
  15937. }
  15938. cloneTo(destObject) {
  15939. var destGradientDataColor = destObject;
  15940. var i, n;
  15941. destGradientDataColor._colorAlphaKeysCount = this._colorAlphaKeysCount;
  15942. var destAlphaElements = destGradientDataColor._alphaElements;
  15943. for (i = 0, n = this._alphaElements.length; i < n; i++)
  15944. destAlphaElements[i] = this._alphaElements[i];
  15945. destGradientDataColor._colorRGBKeysCount = this._colorRGBKeysCount;
  15946. var destRGBElements = destGradientDataColor._rgbElements;
  15947. for (i = 0, n = this._rgbElements.length; i < n; i++)
  15948. destRGBElements[i] = this._rgbElements[i];
  15949. }
  15950. clone() {
  15951. var destGradientDataColor = new Gradient(this._maxColorRGBKeysCount, this._maxColorAlphaKeysCount);
  15952. this.cloneTo(destGradientDataColor);
  15953. return destGradientDataColor;
  15954. }
  15955. }
  15956. class Burst {
  15957. get time() {
  15958. return this._time;
  15959. }
  15960. get minCount() {
  15961. return this._minCount;
  15962. }
  15963. get maxCount() {
  15964. return this._maxCount;
  15965. }
  15966. constructor(time, minCount, maxCount) {
  15967. this._time = time;
  15968. this._minCount = minCount;
  15969. this._maxCount = maxCount;
  15970. }
  15971. cloneTo(destObject) {
  15972. var destBurst = destObject;
  15973. destBurst._time = this._time;
  15974. destBurst._minCount = this._minCount;
  15975. destBurst._maxCount = this._maxCount;
  15976. }
  15977. clone() {
  15978. var destBurst = new Burst(this._time, this._minCount, this._maxCount);
  15979. this.cloneTo(destBurst);
  15980. return destBurst;
  15981. }
  15982. }
  15983. class GradientColor {
  15984. constructor() {
  15985. this._type = 0;
  15986. this._constant = null;
  15987. this._constantMin = null;
  15988. this._constantMax = null;
  15989. this._gradient = null;
  15990. this._gradientMin = null;
  15991. this._gradientMax = null;
  15992. }
  15993. static createByConstant(constant) {
  15994. var gradientColor = new GradientColor();
  15995. gradientColor._type = 0;
  15996. gradientColor._constant = constant;
  15997. return gradientColor;
  15998. }
  15999. static createByGradient(gradient) {
  16000. var gradientColor = new GradientColor();
  16001. gradientColor._type = 1;
  16002. gradientColor._gradient = gradient;
  16003. return gradientColor;
  16004. }
  16005. static createByRandomTwoConstant(minConstant, maxConstant) {
  16006. var gradientColor = new GradientColor();
  16007. gradientColor._type = 2;
  16008. gradientColor._constantMin = minConstant;
  16009. gradientColor._constantMax = maxConstant;
  16010. return gradientColor;
  16011. }
  16012. static createByRandomTwoGradient(minGradient, maxGradient) {
  16013. var gradientColor = new GradientColor();
  16014. gradientColor._type = 3;
  16015. gradientColor._gradientMin = minGradient;
  16016. gradientColor._gradientMax = maxGradient;
  16017. return gradientColor;
  16018. }
  16019. get type() {
  16020. return this._type;
  16021. }
  16022. get constant() {
  16023. return this._constant;
  16024. }
  16025. get constantMin() {
  16026. return this._constantMin;
  16027. }
  16028. get constantMax() {
  16029. return this._constantMax;
  16030. }
  16031. get gradient() {
  16032. return this._gradient;
  16033. }
  16034. get gradientMin() {
  16035. return this._gradientMin;
  16036. }
  16037. get gradientMax() {
  16038. return this._gradientMax;
  16039. }
  16040. cloneTo(destObject) {
  16041. var destGradientColor = destObject;
  16042. destGradientColor._type = this._type;
  16043. this._constant.cloneTo(destGradientColor._constant);
  16044. this._constantMin.cloneTo(destGradientColor._constantMin);
  16045. this._constantMax.cloneTo(destGradientColor._constantMax);
  16046. this._gradient.cloneTo(destGradientColor._gradient);
  16047. this._gradientMin.cloneTo(destGradientColor._gradientMin);
  16048. this._gradientMax.cloneTo(destGradientColor._gradientMax);
  16049. }
  16050. clone() {
  16051. var destGradientColor = new GradientColor();
  16052. this.cloneTo(destGradientColor);
  16053. return destGradientColor;
  16054. }
  16055. }
  16056. class ColorOverLifetime {
  16057. get color() {
  16058. return this._color;
  16059. }
  16060. constructor(color) {
  16061. this._color = color;
  16062. }
  16063. cloneTo(destObject) {
  16064. var destColorOverLifetime = destObject;
  16065. this._color.cloneTo(destColorOverLifetime._color);
  16066. destColorOverLifetime.enable = this.enable;
  16067. }
  16068. clone() {
  16069. var destColor;
  16070. switch (this._color.type) {
  16071. case 0:
  16072. destColor = GradientColor.createByConstant(this._color.constant.clone());
  16073. break;
  16074. case 1:
  16075. destColor = GradientColor.createByGradient(this._color.gradient.clone());
  16076. break;
  16077. case 2:
  16078. destColor = GradientColor.createByRandomTwoConstant(this._color.constantMin.clone(), this._color.constantMax.clone());
  16079. break;
  16080. case 3:
  16081. destColor = GradientColor.createByRandomTwoGradient(this._color.gradientMin.clone(), this._color.gradientMax.clone());
  16082. break;
  16083. }
  16084. var destColorOverLifetime = new ColorOverLifetime(destColor);
  16085. destColorOverLifetime.enable = this.enable;
  16086. return destColorOverLifetime;
  16087. }
  16088. }
  16089. class FrameOverTime {
  16090. constructor() {
  16091. this._type = 0;
  16092. this._constant = 0;
  16093. this._overTime = null;
  16094. this._constantMin = 0;
  16095. this._constantMax = 0;
  16096. this._overTimeMin = null;
  16097. this._overTimeMax = null;
  16098. }
  16099. static createByConstant(constant = 0) {
  16100. var rotationOverLifetime = new FrameOverTime();
  16101. rotationOverLifetime._type = 0;
  16102. rotationOverLifetime._constant = constant;
  16103. return rotationOverLifetime;
  16104. }
  16105. static createByOverTime(overTime) {
  16106. var rotationOverLifetime = new FrameOverTime();
  16107. rotationOverLifetime._type = 1;
  16108. rotationOverLifetime._overTime = overTime;
  16109. return rotationOverLifetime;
  16110. }
  16111. static createByRandomTwoConstant(constantMin = 0, constantMax = 0) {
  16112. var rotationOverLifetime = new FrameOverTime();
  16113. rotationOverLifetime._type = 2;
  16114. rotationOverLifetime._constantMin = constantMin;
  16115. rotationOverLifetime._constantMax = constantMax;
  16116. return rotationOverLifetime;
  16117. }
  16118. static createByRandomTwoOverTime(gradientFrameMin, gradientFrameMax) {
  16119. var rotationOverLifetime = new FrameOverTime();
  16120. rotationOverLifetime._type = 3;
  16121. rotationOverLifetime._overTimeMin = gradientFrameMin;
  16122. rotationOverLifetime._overTimeMax = gradientFrameMax;
  16123. return rotationOverLifetime;
  16124. }
  16125. get type() {
  16126. return this._type;
  16127. }
  16128. get constant() {
  16129. return this._constant;
  16130. }
  16131. get frameOverTimeData() {
  16132. return this._overTime;
  16133. }
  16134. get constantMin() {
  16135. return this._constantMin;
  16136. }
  16137. get constantMax() {
  16138. return this._constantMax;
  16139. }
  16140. get frameOverTimeDataMin() {
  16141. return this._overTimeMin;
  16142. }
  16143. get frameOverTimeDataMax() {
  16144. return this._overTimeMax;
  16145. }
  16146. cloneTo(destObject) {
  16147. var destFrameOverTime = destObject;
  16148. destFrameOverTime._type = this._type;
  16149. destFrameOverTime._constant = this._constant;
  16150. (this._overTime) && (this._overTime.cloneTo(destFrameOverTime._overTime));
  16151. destFrameOverTime._constantMin = this._constantMin;
  16152. destFrameOverTime._constantMax = this._constantMax;
  16153. (this._overTimeMin) && (this._overTimeMin.cloneTo(destFrameOverTime._overTimeMin));
  16154. (this._overTimeMax) && (this._overTimeMax.cloneTo(destFrameOverTime._overTimeMax));
  16155. }
  16156. clone() {
  16157. var destFrameOverTime = new FrameOverTime();
  16158. this.cloneTo(destFrameOverTime);
  16159. return destFrameOverTime;
  16160. }
  16161. }
  16162. class GradientAngularVelocity {
  16163. constructor() {
  16164. this._type = 0;
  16165. this._separateAxes = false;
  16166. this._constant = 0;
  16167. this._constantSeparate = null;
  16168. this._gradient = null;
  16169. this._gradientX = null;
  16170. this._gradientY = null;
  16171. this._gradientZ = null;
  16172. this._gradientW = null;
  16173. this._constantMin = 0;
  16174. this._constantMax = 0;
  16175. this._constantMinSeparate = null;
  16176. this._constantMaxSeparate = null;
  16177. this._gradientMin = null;
  16178. this._gradientMax = null;
  16179. this._gradientXMin = null;
  16180. this._gradientXMax = null;
  16181. this._gradientYMin = null;
  16182. this._gradientYMax = null;
  16183. this._gradientZMin = null;
  16184. this._gradientZMax = null;
  16185. this._gradientWMin = null;
  16186. this._gradientWMax = null;
  16187. }
  16188. static createByConstant(constant) {
  16189. var gradientAngularVelocity = new GradientAngularVelocity();
  16190. gradientAngularVelocity._type = 0;
  16191. gradientAngularVelocity._separateAxes = false;
  16192. gradientAngularVelocity._constant = constant;
  16193. return gradientAngularVelocity;
  16194. }
  16195. static createByConstantSeparate(separateConstant) {
  16196. var gradientAngularVelocity = new GradientAngularVelocity();
  16197. gradientAngularVelocity._type = 0;
  16198. gradientAngularVelocity._separateAxes = true;
  16199. gradientAngularVelocity._constantSeparate = separateConstant;
  16200. return gradientAngularVelocity;
  16201. }
  16202. static createByGradient(gradient) {
  16203. var gradientAngularVelocity = new GradientAngularVelocity();
  16204. gradientAngularVelocity._type = 1;
  16205. gradientAngularVelocity._separateAxes = false;
  16206. gradientAngularVelocity._gradient = gradient;
  16207. return gradientAngularVelocity;
  16208. }
  16209. static createByGradientSeparate(gradientX, gradientY, gradientZ) {
  16210. var gradientAngularVelocity = new GradientAngularVelocity();
  16211. gradientAngularVelocity._type = 1;
  16212. gradientAngularVelocity._separateAxes = true;
  16213. gradientAngularVelocity._gradientX = gradientX;
  16214. gradientAngularVelocity._gradientY = gradientY;
  16215. gradientAngularVelocity._gradientZ = gradientZ;
  16216. return gradientAngularVelocity;
  16217. }
  16218. static createByRandomTwoConstant(constantMin, constantMax) {
  16219. var gradientAngularVelocity = new GradientAngularVelocity();
  16220. gradientAngularVelocity._type = 2;
  16221. gradientAngularVelocity._separateAxes = false;
  16222. gradientAngularVelocity._constantMin = constantMin;
  16223. gradientAngularVelocity._constantMax = constantMax;
  16224. return gradientAngularVelocity;
  16225. }
  16226. static createByRandomTwoConstantSeparate(separateConstantMin, separateConstantMax) {
  16227. var gradientAngularVelocity = new GradientAngularVelocity();
  16228. gradientAngularVelocity._type = 2;
  16229. gradientAngularVelocity._separateAxes = true;
  16230. gradientAngularVelocity._constantMinSeparate = separateConstantMin;
  16231. gradientAngularVelocity._constantMaxSeparate = separateConstantMax;
  16232. return gradientAngularVelocity;
  16233. }
  16234. static createByRandomTwoGradient(gradientMin, gradientMax) {
  16235. var gradientAngularVelocity = new GradientAngularVelocity();
  16236. gradientAngularVelocity._type = 3;
  16237. gradientAngularVelocity._separateAxes = false;
  16238. gradientAngularVelocity._gradientMin = gradientMin;
  16239. gradientAngularVelocity._gradientMax = gradientMax;
  16240. return gradientAngularVelocity;
  16241. }
  16242. static createByRandomTwoGradientSeparate(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax, gradientWMin, gradientWMax) {
  16243. var gradientAngularVelocity = new GradientAngularVelocity();
  16244. gradientAngularVelocity._type = 3;
  16245. gradientAngularVelocity._separateAxes = true;
  16246. gradientAngularVelocity._gradientXMin = gradientXMin;
  16247. gradientAngularVelocity._gradientXMax = gradientXMax;
  16248. gradientAngularVelocity._gradientYMin = gradientYMin;
  16249. gradientAngularVelocity._gradientYMax = gradientYMax;
  16250. gradientAngularVelocity._gradientZMin = gradientZMin;
  16251. gradientAngularVelocity._gradientZMax = gradientZMax;
  16252. gradientAngularVelocity._gradientWMin = gradientWMin;
  16253. gradientAngularVelocity._gradientWMax = gradientWMax;
  16254. return gradientAngularVelocity;
  16255. }
  16256. get type() {
  16257. return this._type;
  16258. }
  16259. get separateAxes() {
  16260. return this._separateAxes;
  16261. }
  16262. get constant() {
  16263. return this._constant;
  16264. }
  16265. get constantSeparate() {
  16266. return this._constantSeparate;
  16267. }
  16268. get gradient() {
  16269. return this._gradient;
  16270. }
  16271. get gradientX() {
  16272. return this._gradientX;
  16273. }
  16274. get gradientY() {
  16275. return this._gradientY;
  16276. }
  16277. get gradientZ() {
  16278. return this._gradientZ;
  16279. }
  16280. get gradientW() {
  16281. return this._gradientW;
  16282. }
  16283. get constantMin() {
  16284. return this._constantMin;
  16285. }
  16286. get constantMax() {
  16287. return this._constantMax;
  16288. }
  16289. get constantMinSeparate() {
  16290. return this._constantMinSeparate;
  16291. }
  16292. get constantMaxSeparate() {
  16293. return this._constantMaxSeparate;
  16294. }
  16295. get gradientMin() {
  16296. return this._gradientMin;
  16297. }
  16298. get gradientMax() {
  16299. return this._gradientMax;
  16300. }
  16301. get gradientXMin() {
  16302. return this._gradientXMin;
  16303. }
  16304. get gradientXMax() {
  16305. return this._gradientXMax;
  16306. }
  16307. get gradientYMin() {
  16308. return this._gradientYMin;
  16309. }
  16310. get gradientYMax() {
  16311. return this._gradientYMax;
  16312. }
  16313. get gradientZMin() {
  16314. return this._gradientZMin;
  16315. }
  16316. get gradientZMax() {
  16317. return this._gradientZMax;
  16318. }
  16319. get gradientWMin() {
  16320. return this._gradientWMin;
  16321. }
  16322. get gradientWMax() {
  16323. return this._gradientWMax;
  16324. }
  16325. cloneTo(destObject) {
  16326. var destGradientAngularVelocity = destObject;
  16327. destGradientAngularVelocity._type = this._type;
  16328. destGradientAngularVelocity._separateAxes = this._separateAxes;
  16329. destGradientAngularVelocity._constant = this._constant;
  16330. this._constantSeparate.cloneTo(destGradientAngularVelocity._constantSeparate);
  16331. this._gradient.cloneTo(destGradientAngularVelocity._gradient);
  16332. this._gradientX.cloneTo(destGradientAngularVelocity._gradientX);
  16333. this._gradientY.cloneTo(destGradientAngularVelocity._gradientY);
  16334. this._gradientZ.cloneTo(destGradientAngularVelocity._gradientZ);
  16335. destGradientAngularVelocity._constantMin = this._constantMin;
  16336. destGradientAngularVelocity._constantMax = this._constantMax;
  16337. this._constantMinSeparate.cloneTo(destGradientAngularVelocity._constantMinSeparate);
  16338. this._constantMaxSeparate.cloneTo(destGradientAngularVelocity._constantMaxSeparate);
  16339. this._gradientMin.cloneTo(destGradientAngularVelocity._gradientMin);
  16340. this._gradientMax.cloneTo(destGradientAngularVelocity._gradientMax);
  16341. this._gradientXMin.cloneTo(destGradientAngularVelocity._gradientXMin);
  16342. this._gradientXMax.cloneTo(destGradientAngularVelocity._gradientXMax);
  16343. this._gradientYMin.cloneTo(destGradientAngularVelocity._gradientYMin);
  16344. this._gradientYMax.cloneTo(destGradientAngularVelocity._gradientYMax);
  16345. this._gradientZMin.cloneTo(destGradientAngularVelocity._gradientZMin);
  16346. this._gradientZMax.cloneTo(destGradientAngularVelocity._gradientZMax);
  16347. }
  16348. clone() {
  16349. var destGradientAngularVelocity = new GradientAngularVelocity();
  16350. this.cloneTo(destGradientAngularVelocity);
  16351. return destGradientAngularVelocity;
  16352. }
  16353. }
  16354. class GradientDataInt {
  16355. constructor() {
  16356. this._currentLength = 0;
  16357. this._elements = new Float32Array(8);
  16358. }
  16359. get gradientCount() {
  16360. return this._currentLength / 2;
  16361. }
  16362. add(key, value) {
  16363. if (this._currentLength < 8) {
  16364. if ((this._currentLength === 6) && ((key !== 1))) {
  16365. key = 1;
  16366. console.log("Warning:the forth key is be force set to 1.");
  16367. }
  16368. this._elements[this._currentLength++] = key;
  16369. this._elements[this._currentLength++] = value;
  16370. }
  16371. else {
  16372. console.log("Warning:data count must lessEqual than 4");
  16373. }
  16374. }
  16375. cloneTo(destObject) {
  16376. var destGradientDataInt = destObject;
  16377. destGradientDataInt._currentLength = this._currentLength;
  16378. var destElements = destGradientDataInt._elements;
  16379. for (var i = 0, n = this._elements.length; i < n; i++) {
  16380. destElements[i] = this._elements[i];
  16381. }
  16382. }
  16383. clone() {
  16384. var destGradientDataInt = new GradientDataInt();
  16385. this.cloneTo(destGradientDataInt);
  16386. return destGradientDataInt;
  16387. }
  16388. }
  16389. class GradientDataNumber {
  16390. constructor() {
  16391. this._currentLength = 0;
  16392. this._elements = new Float32Array(8);
  16393. }
  16394. get gradientCount() {
  16395. return this._currentLength / 2;
  16396. }
  16397. add(key, value) {
  16398. if (this._currentLength < 8) {
  16399. if ((this._currentLength === 6) && ((key !== 1))) {
  16400. key = 1;
  16401. console.log("GradientDataNumber warning:the forth key is be force set to 1.");
  16402. }
  16403. this._elements[this._currentLength++] = key;
  16404. this._elements[this._currentLength++] = value;
  16405. }
  16406. else {
  16407. console.log("GradientDataNumber warning:data count must lessEqual than 4");
  16408. }
  16409. }
  16410. getKeyByIndex(index) {
  16411. return this._elements[index * 2];
  16412. }
  16413. getValueByIndex(index) {
  16414. return this._elements[index * 2 + 1];
  16415. }
  16416. getAverageValue() {
  16417. var total = 0;
  16418. for (var i = 0, n = this._currentLength - 2; i < n; i += 2) {
  16419. var subValue = this._elements[i + 1];
  16420. subValue += this._elements[i + 3];
  16421. subValue = subValue * (this._elements[i + 2] - this._elements[i]);
  16422. }
  16423. return total / 2;
  16424. }
  16425. cloneTo(destObject) {
  16426. var destGradientDataNumber = destObject;
  16427. destGradientDataNumber._currentLength = this._currentLength;
  16428. var destElements = destGradientDataNumber._elements;
  16429. for (var i = 0, n = this._elements.length; i < n; i++)
  16430. destElements[i] = this._elements[i];
  16431. }
  16432. clone() {
  16433. var destGradientDataNumber = new GradientDataNumber();
  16434. this.cloneTo(destGradientDataNumber);
  16435. return destGradientDataNumber;
  16436. }
  16437. }
  16438. class GradientSize {
  16439. constructor() {
  16440. this._type = 0;
  16441. this._separateAxes = false;
  16442. this._gradient = null;
  16443. this._gradientX = null;
  16444. this._gradientY = null;
  16445. this._gradientZ = null;
  16446. this._constantMin = 0;
  16447. this._constantMax = 0;
  16448. this._constantMinSeparate = null;
  16449. this._constantMaxSeparate = null;
  16450. this._gradientMin = null;
  16451. this._gradientMax = null;
  16452. this._gradientXMin = null;
  16453. this._gradientXMax = null;
  16454. this._gradientYMin = null;
  16455. this._gradientYMax = null;
  16456. this._gradientZMin = null;
  16457. this._gradientZMax = null;
  16458. }
  16459. static createByGradient(gradient) {
  16460. var gradientSize = new GradientSize();
  16461. gradientSize._type = 0;
  16462. gradientSize._separateAxes = false;
  16463. gradientSize._gradient = gradient;
  16464. return gradientSize;
  16465. }
  16466. static createByGradientSeparate(gradientX, gradientY, gradientZ) {
  16467. var gradientSize = new GradientSize();
  16468. gradientSize._type = 0;
  16469. gradientSize._separateAxes = true;
  16470. gradientSize._gradientX = gradientX;
  16471. gradientSize._gradientY = gradientY;
  16472. gradientSize._gradientZ = gradientZ;
  16473. return gradientSize;
  16474. }
  16475. static createByRandomTwoConstant(constantMin, constantMax) {
  16476. var gradientSize = new GradientSize();
  16477. gradientSize._type = 1;
  16478. gradientSize._separateAxes = false;
  16479. gradientSize._constantMin = constantMin;
  16480. gradientSize._constantMax = constantMax;
  16481. return gradientSize;
  16482. }
  16483. static createByRandomTwoConstantSeparate(constantMinSeparate, constantMaxSeparate) {
  16484. var gradientSize = new GradientSize();
  16485. gradientSize._type = 1;
  16486. gradientSize._separateAxes = true;
  16487. gradientSize._constantMinSeparate = constantMinSeparate;
  16488. gradientSize._constantMaxSeparate = constantMaxSeparate;
  16489. return gradientSize;
  16490. }
  16491. static createByRandomTwoGradient(gradientMin, gradientMax) {
  16492. var gradientSize = new GradientSize();
  16493. gradientSize._type = 2;
  16494. gradientSize._separateAxes = false;
  16495. gradientSize._gradientMin = gradientMin;
  16496. gradientSize._gradientMax = gradientMax;
  16497. return gradientSize;
  16498. }
  16499. static createByRandomTwoGradientSeparate(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax) {
  16500. var gradientSize = new GradientSize();
  16501. gradientSize._type = 2;
  16502. gradientSize._separateAxes = true;
  16503. gradientSize._gradientXMin = gradientXMin;
  16504. gradientSize._gradientXMax = gradientXMax;
  16505. gradientSize._gradientYMin = gradientYMin;
  16506. gradientSize._gradientYMax = gradientYMax;
  16507. gradientSize._gradientZMin = gradientZMin;
  16508. gradientSize._gradientZMax = gradientZMax;
  16509. return gradientSize;
  16510. }
  16511. get type() {
  16512. return this._type;
  16513. }
  16514. get separateAxes() {
  16515. return this._separateAxes;
  16516. }
  16517. get gradient() {
  16518. return this._gradient;
  16519. }
  16520. get gradientX() {
  16521. return this._gradientX;
  16522. }
  16523. get gradientY() {
  16524. return this._gradientY;
  16525. }
  16526. get gradientZ() {
  16527. return this._gradientZ;
  16528. }
  16529. get constantMin() {
  16530. return this._constantMin;
  16531. }
  16532. get constantMax() {
  16533. return this._constantMax;
  16534. }
  16535. get constantMinSeparate() {
  16536. return this._constantMinSeparate;
  16537. }
  16538. get constantMaxSeparate() {
  16539. return this._constantMaxSeparate;
  16540. }
  16541. get gradientMin() {
  16542. return this._gradientMin;
  16543. }
  16544. get gradientMax() {
  16545. return this._gradientMax;
  16546. }
  16547. get gradientXMin() {
  16548. return this._gradientXMin;
  16549. }
  16550. get gradientXMax() {
  16551. return this._gradientXMax;
  16552. }
  16553. get gradientYMin() {
  16554. return this._gradientYMin;
  16555. }
  16556. get gradientYMax() {
  16557. return this._gradientYMax;
  16558. }
  16559. get gradientZMin() {
  16560. return this._gradientZMin;
  16561. }
  16562. get gradientZMax() {
  16563. return this._gradientZMax;
  16564. }
  16565. getMaxSizeInGradient() {
  16566. var i, n;
  16567. var maxSize = -Number.MAX_VALUE;
  16568. switch (this._type) {
  16569. case 0:
  16570. if (this._separateAxes) {
  16571. for (i = 0, n = this._gradientX.gradientCount; i < n; i++)
  16572. maxSize = Math.max(maxSize, this._gradientX.getValueByIndex(i));
  16573. for (i = 0, n = this._gradientY.gradientCount; i < n; i++)
  16574. maxSize = Math.max(maxSize, this._gradientY.getValueByIndex(i));
  16575. }
  16576. else {
  16577. for (i = 0, n = this._gradient.gradientCount; i < n; i++)
  16578. maxSize = Math.max(maxSize, this._gradient.getValueByIndex(i));
  16579. }
  16580. break;
  16581. case 1:
  16582. if (this._separateAxes) {
  16583. maxSize = Math.max(this._constantMinSeparate.x, this._constantMaxSeparate.x);
  16584. maxSize = Math.max(maxSize, this._constantMinSeparate.y);
  16585. maxSize = Math.max(maxSize, this._constantMaxSeparate.y);
  16586. }
  16587. else {
  16588. maxSize = Math.max(this._constantMin, this._constantMax);
  16589. }
  16590. break;
  16591. case 2:
  16592. if (this._separateAxes) {
  16593. for (i = 0, n = this._gradientXMin.gradientCount; i < n; i++)
  16594. maxSize = Math.max(maxSize, this._gradientXMin.getValueByIndex(i));
  16595. for (i = 0, n = this._gradientXMax.gradientCount; i < n; i++)
  16596. maxSize = Math.max(maxSize, this._gradientXMax.getValueByIndex(i));
  16597. for (i = 0, n = this._gradientYMin.gradientCount; i < n; i++)
  16598. maxSize = Math.max(maxSize, this._gradientYMin.getValueByIndex(i));
  16599. for (i = 0, n = this._gradientZMax.gradientCount; i < n; i++)
  16600. maxSize = Math.max(maxSize, this._gradientZMax.getValueByIndex(i));
  16601. }
  16602. else {
  16603. for (i = 0, n = this._gradientMin.gradientCount; i < n; i++)
  16604. maxSize = Math.max(maxSize, this._gradientMin.getValueByIndex(i));
  16605. for (i = 0, n = this._gradientMax.gradientCount; i < n; i++)
  16606. maxSize = Math.max(maxSize, this._gradientMax.getValueByIndex(i));
  16607. }
  16608. break;
  16609. }
  16610. return maxSize;
  16611. }
  16612. cloneTo(destObject) {
  16613. var destGradientSize = destObject;
  16614. destGradientSize._type = this._type;
  16615. destGradientSize._separateAxes = this._separateAxes;
  16616. this._gradient.cloneTo(destGradientSize._gradient);
  16617. this._gradientX.cloneTo(destGradientSize._gradientX);
  16618. this._gradientY.cloneTo(destGradientSize._gradientY);
  16619. this._gradientZ.cloneTo(destGradientSize._gradientZ);
  16620. destGradientSize._constantMin = this._constantMin;
  16621. destGradientSize._constantMax = this._constantMax;
  16622. this._constantMinSeparate.cloneTo(destGradientSize._constantMinSeparate);
  16623. this._constantMaxSeparate.cloneTo(destGradientSize._constantMaxSeparate);
  16624. this._gradientMin.cloneTo(destGradientSize._gradientMin);
  16625. this._gradientMax.cloneTo(destGradientSize._gradientMax);
  16626. this._gradientXMin.cloneTo(destGradientSize._gradientXMin);
  16627. this._gradientXMax.cloneTo(destGradientSize._gradientXMax);
  16628. this._gradientYMin.cloneTo(destGradientSize._gradientYMin);
  16629. this._gradientYMax.cloneTo(destGradientSize._gradientYMax);
  16630. this._gradientZMin.cloneTo(destGradientSize._gradientZMin);
  16631. this._gradientZMax.cloneTo(destGradientSize._gradientZMax);
  16632. }
  16633. clone() {
  16634. var destGradientSize = new GradientSize();
  16635. this.cloneTo(destGradientSize);
  16636. return destGradientSize;
  16637. }
  16638. }
  16639. class GradientVelocity {
  16640. constructor() {
  16641. this._type = 0;
  16642. this._constant = null;
  16643. this._gradientX = null;
  16644. this._gradientY = null;
  16645. this._gradientZ = null;
  16646. this._constantMin = null;
  16647. this._constantMax = null;
  16648. this._gradientXMin = null;
  16649. this._gradientXMax = null;
  16650. this._gradientYMin = null;
  16651. this._gradientYMax = null;
  16652. this._gradientZMin = null;
  16653. this._gradientZMax = null;
  16654. }
  16655. static createByConstant(constant) {
  16656. var gradientVelocity = new GradientVelocity();
  16657. gradientVelocity._type = 0;
  16658. gradientVelocity._constant = constant;
  16659. return gradientVelocity;
  16660. }
  16661. static createByGradient(gradientX, gradientY, gradientZ) {
  16662. var gradientVelocity = new GradientVelocity();
  16663. gradientVelocity._type = 1;
  16664. gradientVelocity._gradientX = gradientX;
  16665. gradientVelocity._gradientY = gradientY;
  16666. gradientVelocity._gradientZ = gradientZ;
  16667. return gradientVelocity;
  16668. }
  16669. static createByRandomTwoConstant(constantMin, constantMax) {
  16670. var gradientVelocity = new GradientVelocity();
  16671. gradientVelocity._type = 2;
  16672. gradientVelocity._constantMin = constantMin;
  16673. gradientVelocity._constantMax = constantMax;
  16674. return gradientVelocity;
  16675. }
  16676. static createByRandomTwoGradient(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax) {
  16677. var gradientVelocity = new GradientVelocity();
  16678. gradientVelocity._type = 3;
  16679. gradientVelocity._gradientXMin = gradientXMin;
  16680. gradientVelocity._gradientXMax = gradientXMax;
  16681. gradientVelocity._gradientYMin = gradientYMin;
  16682. gradientVelocity._gradientYMax = gradientYMax;
  16683. gradientVelocity._gradientZMin = gradientZMin;
  16684. gradientVelocity._gradientZMax = gradientZMax;
  16685. return gradientVelocity;
  16686. }
  16687. get type() {
  16688. return this._type;
  16689. }
  16690. get constant() {
  16691. return this._constant;
  16692. }
  16693. get gradientX() {
  16694. return this._gradientX;
  16695. }
  16696. get gradientY() {
  16697. return this._gradientY;
  16698. }
  16699. get gradientZ() {
  16700. return this._gradientZ;
  16701. }
  16702. get constantMin() {
  16703. return this._constantMin;
  16704. }
  16705. get constantMax() {
  16706. return this._constantMax;
  16707. }
  16708. get gradientXMin() {
  16709. return this._gradientXMin;
  16710. }
  16711. get gradientXMax() {
  16712. return this._gradientXMax;
  16713. }
  16714. get gradientYMin() {
  16715. return this._gradientYMin;
  16716. }
  16717. get gradientYMax() {
  16718. return this._gradientYMax;
  16719. }
  16720. get gradientZMin() {
  16721. return this._gradientZMin;
  16722. }
  16723. get gradientZMax() {
  16724. return this._gradientZMax;
  16725. }
  16726. cloneTo(destObject) {
  16727. var destGradientVelocity = destObject;
  16728. destGradientVelocity._type = this._type;
  16729. this._constant.cloneTo(destGradientVelocity._constant);
  16730. this._gradientX.cloneTo(destGradientVelocity._gradientX);
  16731. this._gradientY.cloneTo(destGradientVelocity._gradientY);
  16732. this._gradientZ.cloneTo(destGradientVelocity._gradientZ);
  16733. this._constantMin.cloneTo(destGradientVelocity._constantMin);
  16734. this._constantMax.cloneTo(destGradientVelocity._constantMax);
  16735. this._gradientXMin.cloneTo(destGradientVelocity._gradientXMin);
  16736. this._gradientXMax.cloneTo(destGradientVelocity._gradientXMax);
  16737. this._gradientYMin.cloneTo(destGradientVelocity._gradientYMin);
  16738. this._gradientYMax.cloneTo(destGradientVelocity._gradientYMax);
  16739. this._gradientZMin.cloneTo(destGradientVelocity._gradientZMin);
  16740. this._gradientZMax.cloneTo(destGradientVelocity._gradientZMax);
  16741. }
  16742. clone() {
  16743. var destGradientVelocity = new GradientVelocity();
  16744. this.cloneTo(destGradientVelocity);
  16745. return destGradientVelocity;
  16746. }
  16747. }
  16748. class RotationOverLifetime {
  16749. get angularVelocity() {
  16750. return this._angularVelocity;
  16751. }
  16752. constructor(angularVelocity) {
  16753. this._angularVelocity = angularVelocity;
  16754. }
  16755. cloneTo(destObject) {
  16756. var destRotationOverLifetime = destObject;
  16757. this._angularVelocity.cloneTo(destRotationOverLifetime._angularVelocity);
  16758. destRotationOverLifetime.enable = this.enable;
  16759. }
  16760. clone() {
  16761. var destAngularVelocity;
  16762. switch (this._angularVelocity.type) {
  16763. case 0:
  16764. if (this._angularVelocity.separateAxes)
  16765. destAngularVelocity = GradientAngularVelocity.createByConstantSeparate(this._angularVelocity.constantSeparate.clone());
  16766. else
  16767. destAngularVelocity = GradientAngularVelocity.createByConstant(this._angularVelocity.constant);
  16768. break;
  16769. case 1:
  16770. if (this._angularVelocity.separateAxes)
  16771. destAngularVelocity = GradientAngularVelocity.createByGradientSeparate(this._angularVelocity.gradientX.clone(), this._angularVelocity.gradientY.clone(), this._angularVelocity.gradientZ.clone());
  16772. else
  16773. destAngularVelocity = GradientAngularVelocity.createByGradient(this._angularVelocity.gradient.clone());
  16774. break;
  16775. case 2:
  16776. if (this._angularVelocity.separateAxes)
  16777. destAngularVelocity = GradientAngularVelocity.createByRandomTwoConstantSeparate(this._angularVelocity.constantMinSeparate.clone(), this._angularVelocity.constantMaxSeparate.clone());
  16778. else
  16779. destAngularVelocity = GradientAngularVelocity.createByRandomTwoConstant(this._angularVelocity.constantMin, this._angularVelocity.constantMax);
  16780. break;
  16781. case 3:
  16782. if (this._angularVelocity.separateAxes)
  16783. destAngularVelocity = GradientAngularVelocity.createByRandomTwoGradientSeparate(this._angularVelocity.gradientXMin.clone(), this._angularVelocity.gradientYMin.clone(), this._angularVelocity.gradientZMin.clone(), this._angularVelocity.gradientWMin.clone(), this._angularVelocity.gradientXMax.clone(), this._angularVelocity.gradientYMax.clone(), this._angularVelocity.gradientZMax.clone(), this._angularVelocity.gradientWMax.clone());
  16784. else
  16785. destAngularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._angularVelocity.gradientMin.clone(), this._angularVelocity.gradientMax.clone());
  16786. break;
  16787. }
  16788. var destRotationOverLifetime = new RotationOverLifetime(destAngularVelocity);
  16789. destRotationOverLifetime.enable = this.enable;
  16790. return destRotationOverLifetime;
  16791. }
  16792. }
  16793. class BaseShape {
  16794. constructor() {
  16795. this.enable = true;
  16796. this.randomDirection = 0;
  16797. }
  16798. _getShapeBoundBox(boundBox) {
  16799. throw new Error("BaseShape: must override it.");
  16800. }
  16801. _getSpeedBoundBox(boundBox) {
  16802. throw new Error("BaseShape: must override it.");
  16803. }
  16804. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  16805. throw new Error("BaseShape: must override it.");
  16806. }
  16807. _calculateProceduralBounds(boundBox, emitterPosScale, minMaxBounds) {
  16808. this._getShapeBoundBox(boundBox);
  16809. var min = boundBox.min;
  16810. var max = boundBox.max;
  16811. Vector3.multiply(min, emitterPosScale, min);
  16812. Vector3.multiply(max, emitterPosScale, max);
  16813. var speedBounds = new BoundBox(new Vector3(), new Vector3());
  16814. if (this.randomDirection) {
  16815. speedBounds.min = new Vector3(-1, -1, -1);
  16816. speedBounds.max = new Vector3(1, 1, 1);
  16817. }
  16818. else {
  16819. this._getSpeedBoundBox(speedBounds);
  16820. }
  16821. var maxSpeedBound = new BoundBox(new Vector3(), new Vector3());
  16822. var maxSpeedMin = maxSpeedBound.min;
  16823. var maxSpeedMax = maxSpeedBound.max;
  16824. Vector3.scale(speedBounds.min, minMaxBounds.y, maxSpeedMin);
  16825. Vector3.scale(speedBounds.max, minMaxBounds.y, maxSpeedMax);
  16826. Vector3.add(boundBox.min, maxSpeedMin, maxSpeedMin);
  16827. Vector3.add(boundBox.max, maxSpeedMax, maxSpeedMax);
  16828. Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
  16829. Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
  16830. var minSpeedBound = new BoundBox(new Vector3(), new Vector3());
  16831. var minSpeedMin = minSpeedBound.min;
  16832. var minSpeedMax = minSpeedBound.max;
  16833. Vector3.scale(speedBounds.min, minMaxBounds.x, minSpeedMin);
  16834. Vector3.scale(speedBounds.max, minMaxBounds.x, minSpeedMax);
  16835. Vector3.min(minSpeedBound.min, minSpeedMax, maxSpeedMin);
  16836. Vector3.max(minSpeedBound.min, minSpeedMax, maxSpeedMax);
  16837. Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
  16838. Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
  16839. }
  16840. cloneTo(destObject) {
  16841. var destShape = destObject;
  16842. destShape.enable = this.enable;
  16843. }
  16844. clone() {
  16845. var destShape = new BaseShape();
  16846. this.cloneTo(destShape);
  16847. return destShape;
  16848. }
  16849. }
  16850. class ShapeUtils {
  16851. static _randomPointUnitArcCircle(arc, out, rand = null) {
  16852. var angle;
  16853. if (rand)
  16854. angle = rand.getFloat() * arc;
  16855. else
  16856. angle = Math.random() * arc;
  16857. out.x = Math.cos(angle);
  16858. out.y = Math.sin(angle);
  16859. }
  16860. static _randomPointInsideUnitArcCircle(arc, out, rand = null) {
  16861. ShapeUtils._randomPointUnitArcCircle(arc, out, rand);
  16862. var range;
  16863. if (rand)
  16864. range = Math.pow(rand.getFloat(), 1.0 / 2.0);
  16865. else
  16866. range = Math.pow(Math.random(), 1.0 / 2.0);
  16867. out.x = out.x * range;
  16868. out.y = out.y * range;
  16869. }
  16870. static _randomPointUnitCircle(out, rand = null) {
  16871. var angle;
  16872. if (rand)
  16873. angle = rand.getFloat() * Math.PI * 2;
  16874. else
  16875. angle = Math.random() * Math.PI * 2;
  16876. out.x = Math.cos(angle);
  16877. out.y = Math.sin(angle);
  16878. }
  16879. static _randomPointInsideUnitCircle(out, rand = null) {
  16880. ShapeUtils._randomPointUnitCircle(out);
  16881. var range;
  16882. if (rand)
  16883. range = Math.pow(rand.getFloat(), 1.0 / 2.0);
  16884. else
  16885. range = Math.pow(Math.random(), 1.0 / 2.0);
  16886. out.x = out.x * range;
  16887. out.y = out.y * range;
  16888. }
  16889. static _randomPointUnitSphere(out, rand = null) {
  16890. var z;
  16891. var a;
  16892. if (rand) {
  16893. z = out.z = rand.getFloat() * 2 - 1.0;
  16894. a = rand.getFloat() * Math.PI * 2;
  16895. }
  16896. else {
  16897. z = out.z = Math.random() * 2 - 1.0;
  16898. a = Math.random() * Math.PI * 2;
  16899. }
  16900. var r = Math.sqrt(1.0 - z * z);
  16901. out.x = r * Math.cos(a);
  16902. out.y = r * Math.sin(a);
  16903. }
  16904. static _randomPointInsideUnitSphere(out, rand = null) {
  16905. ShapeUtils._randomPointUnitSphere(out);
  16906. var range;
  16907. if (rand)
  16908. range = Math.pow(rand.getFloat(), 1.0 / 3.0);
  16909. else
  16910. range = Math.pow(Math.random(), 1.0 / 3.0);
  16911. out.x = out.x * range;
  16912. out.y = out.y * range;
  16913. out.z = out.z * range;
  16914. }
  16915. static _randomPointInsideHalfUnitBox(out, rand = null) {
  16916. if (rand) {
  16917. out.x = (rand.getFloat() - 0.5);
  16918. out.y = (rand.getFloat() - 0.5);
  16919. out.z = (rand.getFloat() - 0.5);
  16920. }
  16921. else {
  16922. out.x = (Math.random() - 0.5);
  16923. out.y = (Math.random() - 0.5);
  16924. out.z = (Math.random() - 0.5);
  16925. }
  16926. }
  16927. constructor() {
  16928. }
  16929. }
  16930. class BoxShape extends BaseShape {
  16931. constructor() {
  16932. super();
  16933. this.x = 1.0;
  16934. this.y = 1.0;
  16935. this.z = 1.0;
  16936. }
  16937. _getShapeBoundBox(boundBox) {
  16938. var min = boundBox.min;
  16939. min.x = -this.x * 0.5;
  16940. min.y = -this.y * 0.5;
  16941. min.z = -this.z * 0.5;
  16942. var max = boundBox.max;
  16943. max.x = this.x * 0.5;
  16944. max.y = this.y * 0.5;
  16945. max.z = this.z * 0.5;
  16946. }
  16947. _getSpeedBoundBox(boundBox) {
  16948. var min = boundBox.min;
  16949. min.x = 0.0;
  16950. min.y = 0.0;
  16951. min.z = 0.0;
  16952. var max = boundBox.max;
  16953. max.x = 0.0;
  16954. max.y = 1.0;
  16955. max.z = 0.0;
  16956. }
  16957. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  16958. if (rand) {
  16959. rand.seed = randomSeeds[16];
  16960. ShapeUtils._randomPointInsideHalfUnitBox(position, rand);
  16961. randomSeeds[16] = rand.seed;
  16962. }
  16963. else {
  16964. ShapeUtils._randomPointInsideHalfUnitBox(position);
  16965. }
  16966. position.x = this.x * position.x;
  16967. position.y = this.y * position.y;
  16968. position.z = this.z * position.z;
  16969. if (this.randomDirection) {
  16970. if (rand) {
  16971. rand.seed = randomSeeds[17];
  16972. ShapeUtils._randomPointUnitSphere(direction, rand);
  16973. randomSeeds[17] = rand.seed;
  16974. }
  16975. else {
  16976. ShapeUtils._randomPointUnitSphere(direction);
  16977. }
  16978. }
  16979. else {
  16980. direction.x = 0.0;
  16981. direction.y = 0.0;
  16982. direction.z = 1.0;
  16983. }
  16984. }
  16985. cloneTo(destObject) {
  16986. super.cloneTo(destObject);
  16987. var destShape = destObject;
  16988. destShape.x = this.x;
  16989. destShape.y = this.y;
  16990. destShape.z = this.z;
  16991. destShape.randomDirection = this.randomDirection;
  16992. }
  16993. clone() {
  16994. var destShape = new BoxShape();
  16995. this.cloneTo(destShape);
  16996. return destShape;
  16997. }
  16998. }
  16999. class CircleShape extends BaseShape {
  17000. constructor() {
  17001. super();
  17002. this.radius = 1.0;
  17003. this.arc = 360.0 / 180.0 * Math.PI;
  17004. this.emitFromEdge = false;
  17005. }
  17006. _getShapeBoundBox(boundBox) {
  17007. var min = boundBox.min;
  17008. min.x = min.z = -this.radius;
  17009. min.y = 0;
  17010. var max = boundBox.max;
  17011. max.x = max.z = this.radius;
  17012. max.y = 0;
  17013. }
  17014. _getSpeedBoundBox(boundBox) {
  17015. var min = boundBox.min;
  17016. min.x = min.y = -1;
  17017. min.z = 0;
  17018. var max = boundBox.max;
  17019. max.x = max.y = 1;
  17020. max.z = 0;
  17021. }
  17022. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  17023. var positionPoint = CircleShape._tempPositionPoint;
  17024. if (rand) {
  17025. rand.seed = randomSeeds[16];
  17026. if (this.emitFromEdge)
  17027. ShapeUtils._randomPointUnitArcCircle(this.arc, CircleShape._tempPositionPoint, rand);
  17028. else
  17029. ShapeUtils._randomPointInsideUnitArcCircle(this.arc, CircleShape._tempPositionPoint, rand);
  17030. randomSeeds[16] = rand.seed;
  17031. }
  17032. else {
  17033. if (this.emitFromEdge)
  17034. ShapeUtils._randomPointUnitArcCircle(this.arc, CircleShape._tempPositionPoint);
  17035. else
  17036. ShapeUtils._randomPointInsideUnitArcCircle(this.arc, CircleShape._tempPositionPoint);
  17037. }
  17038. position.x = -positionPoint.x;
  17039. position.y = positionPoint.y;
  17040. position.z = 0;
  17041. Vector3.scale(position, this.radius, position);
  17042. if (this.randomDirection) {
  17043. if (rand) {
  17044. rand.seed = randomSeeds[17];
  17045. ShapeUtils._randomPointUnitSphere(direction, rand);
  17046. randomSeeds[17] = rand.seed;
  17047. }
  17048. else {
  17049. ShapeUtils._randomPointUnitSphere(direction);
  17050. }
  17051. }
  17052. else {
  17053. position.cloneTo(direction);
  17054. }
  17055. }
  17056. cloneTo(destObject) {
  17057. super.cloneTo(destObject);
  17058. var destShape = destObject;
  17059. destShape.radius = this.radius;
  17060. destShape.arc = this.arc;
  17061. destShape.emitFromEdge = this.emitFromEdge;
  17062. destShape.randomDirection = this.randomDirection;
  17063. }
  17064. clone() {
  17065. var destShape = new CircleShape();
  17066. this.cloneTo(destShape);
  17067. return destShape;
  17068. }
  17069. }
  17070. CircleShape._tempPositionPoint = new Vector2();
  17071. class ConeShape extends BaseShape {
  17072. constructor() {
  17073. super();
  17074. this.angle = 25.0 / 180.0 * Math.PI;
  17075. this.radius = 1.0;
  17076. this.length = 5.0;
  17077. this.emitType = 0;
  17078. }
  17079. _getShapeBoundBox(boundBox) {
  17080. const coneRadius2 = this.radius + this.length * Math.sin(this.angle);
  17081. const coneLength = this.length * Math.cos(this.angle);
  17082. var min = boundBox.min;
  17083. min.x = min.y = -coneRadius2;
  17084. min.z = 0;
  17085. var max = boundBox.max;
  17086. max.x = max.y = coneRadius2;
  17087. max.z = coneLength;
  17088. }
  17089. _getSpeedBoundBox(boundBox) {
  17090. const sinA = Math.sin(this.angle);
  17091. var min = boundBox.min;
  17092. min.x = min.y = -sinA;
  17093. min.z = 0;
  17094. var max = boundBox.max;
  17095. max.x = max.y = sinA;
  17096. max.z = 1;
  17097. }
  17098. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  17099. var positionPointE = ConeShape._tempPositionPoint;
  17100. var positionX;
  17101. var positionY;
  17102. var directionPointE;
  17103. var dirCosA = Math.cos(this.angle);
  17104. var dirSinA = Math.sin(this.angle);
  17105. switch (this.emitType) {
  17106. case 0:
  17107. if (rand) {
  17108. rand.seed = randomSeeds[16];
  17109. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint, rand);
  17110. randomSeeds[16] = rand.seed;
  17111. }
  17112. else {
  17113. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint);
  17114. }
  17115. positionX = positionPointE.x;
  17116. positionY = positionPointE.y;
  17117. position.x = positionX * this.radius;
  17118. position.y = positionY * this.radius;
  17119. position.z = 0;
  17120. if (this.randomDirection) {
  17121. if (rand) {
  17122. rand.seed = randomSeeds[17];
  17123. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint, rand);
  17124. randomSeeds[17] = rand.seed;
  17125. }
  17126. else {
  17127. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint);
  17128. }
  17129. directionPointE = ConeShape._tempDirectionPoint;
  17130. direction.x = directionPointE.x * dirSinA;
  17131. direction.y = directionPointE.y * dirSinA;
  17132. }
  17133. else {
  17134. direction.x = positionX * dirSinA;
  17135. direction.y = positionY * dirSinA;
  17136. }
  17137. direction.z = dirCosA;
  17138. break;
  17139. case 1:
  17140. if (rand) {
  17141. rand.seed = randomSeeds[16];
  17142. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint, rand);
  17143. randomSeeds[16] = rand.seed;
  17144. }
  17145. else {
  17146. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint);
  17147. }
  17148. positionX = positionPointE.x;
  17149. positionY = positionPointE.y;
  17150. position.x = positionX * this.radius;
  17151. position.y = positionY * this.radius;
  17152. position.z = 0;
  17153. if (this.randomDirection) {
  17154. if (rand) {
  17155. rand.seed = randomSeeds[17];
  17156. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint, rand);
  17157. randomSeeds[17] = rand.seed;
  17158. }
  17159. else {
  17160. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint);
  17161. }
  17162. directionPointE = ConeShape._tempDirectionPoint;
  17163. direction.x = directionPointE.x * dirSinA;
  17164. direction.y = directionPointE.y * dirSinA;
  17165. }
  17166. else {
  17167. direction.x = positionX * dirSinA;
  17168. direction.y = positionY * dirSinA;
  17169. }
  17170. direction.z = dirCosA;
  17171. break;
  17172. case 2:
  17173. if (rand) {
  17174. rand.seed = randomSeeds[16];
  17175. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint, rand);
  17176. }
  17177. else {
  17178. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint);
  17179. }
  17180. positionX = positionPointE.x;
  17181. positionY = positionPointE.y;
  17182. position.x = positionX * this.radius;
  17183. position.y = positionY * this.radius;
  17184. position.z = 0;
  17185. direction.x = positionX * dirSinA;
  17186. direction.y = positionY * dirSinA;
  17187. direction.z = dirCosA;
  17188. Vector3.normalize(direction, direction);
  17189. if (rand) {
  17190. Vector3.scale(direction, this.length * rand.getFloat(), direction);
  17191. randomSeeds[16] = rand.seed;
  17192. }
  17193. else {
  17194. Vector3.scale(direction, this.length * Math.random(), direction);
  17195. }
  17196. Vector3.add(position, direction, position);
  17197. if (this.randomDirection) {
  17198. if (rand) {
  17199. rand.seed = randomSeeds[17];
  17200. ShapeUtils._randomPointUnitSphere(direction, rand);
  17201. randomSeeds[17] = rand.seed;
  17202. }
  17203. else {
  17204. ShapeUtils._randomPointUnitSphere(direction);
  17205. }
  17206. }
  17207. break;
  17208. case 3:
  17209. if (rand) {
  17210. rand.seed = randomSeeds[16];
  17211. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint, rand);
  17212. }
  17213. else {
  17214. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint);
  17215. }
  17216. positionX = positionPointE.x;
  17217. positionY = positionPointE.y;
  17218. position.x = positionX * this.radius;
  17219. position.y = positionY * this.radius;
  17220. position.z = 0;
  17221. direction.x = positionX * dirSinA;
  17222. direction.y = positionY * dirSinA;
  17223. direction.z = dirCosA;
  17224. Vector3.normalize(direction, direction);
  17225. if (rand) {
  17226. Vector3.scale(direction, this.length * rand.getFloat(), direction);
  17227. randomSeeds[16] = rand.seed;
  17228. }
  17229. else {
  17230. Vector3.scale(direction, this.length * Math.random(), direction);
  17231. }
  17232. Vector3.add(position, direction, position);
  17233. if (this.randomDirection) {
  17234. if (rand) {
  17235. rand.seed = randomSeeds[17];
  17236. ShapeUtils._randomPointUnitSphere(direction, rand);
  17237. randomSeeds[17] = rand.seed;
  17238. }
  17239. else {
  17240. ShapeUtils._randomPointUnitSphere(direction);
  17241. }
  17242. }
  17243. break;
  17244. default:
  17245. throw new Error("ConeShape:emitType is invalid.");
  17246. }
  17247. }
  17248. cloneTo(destObject) {
  17249. super.cloneTo(destObject);
  17250. var destShape = destObject;
  17251. destShape.angle = this.angle;
  17252. destShape.radius = this.radius;
  17253. destShape.length = this.length;
  17254. destShape.emitType = this.emitType;
  17255. destShape.randomDirection = this.randomDirection;
  17256. }
  17257. clone() {
  17258. var destShape = new ConeShape();
  17259. this.cloneTo(destShape);
  17260. return destShape;
  17261. }
  17262. }
  17263. ConeShape._tempPositionPoint = new Vector2();
  17264. ConeShape._tempDirectionPoint = new Vector2();
  17265. class HemisphereShape extends BaseShape {
  17266. constructor() {
  17267. super();
  17268. this.radius = 1.0;
  17269. this.emitFromShell = false;
  17270. }
  17271. _getShapeBoundBox(boundBox) {
  17272. var min = boundBox.min;
  17273. min.x = min.y = min.z = -this.radius;
  17274. var max = boundBox.max;
  17275. max.x = max.y = this.radius;
  17276. max.z = 0;
  17277. }
  17278. _getSpeedBoundBox(boundBox) {
  17279. var min = boundBox.min;
  17280. min.x = min.y = -1;
  17281. min.z = 0;
  17282. var max = boundBox.max;
  17283. max.x = max.y = max.z = 1;
  17284. }
  17285. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  17286. if (rand) {
  17287. rand.seed = randomSeeds[16];
  17288. if (this.emitFromShell)
  17289. ShapeUtils._randomPointUnitSphere(position, rand);
  17290. else
  17291. ShapeUtils._randomPointInsideUnitSphere(position, rand);
  17292. randomSeeds[16] = rand.seed;
  17293. }
  17294. else {
  17295. if (this.emitFromShell)
  17296. ShapeUtils._randomPointUnitSphere(position);
  17297. else
  17298. ShapeUtils._randomPointInsideUnitSphere(position);
  17299. }
  17300. Vector3.scale(position, this.radius, position);
  17301. var z = position.z;
  17302. (z < 0.0) && (position.z = z * -1.0);
  17303. if (this.randomDirection) {
  17304. if (rand) {
  17305. rand.seed = randomSeeds[17];
  17306. ShapeUtils._randomPointUnitSphere(direction, rand);
  17307. randomSeeds[17] = rand.seed;
  17308. }
  17309. else {
  17310. ShapeUtils._randomPointUnitSphere(direction);
  17311. }
  17312. }
  17313. else {
  17314. position.cloneTo(direction);
  17315. }
  17316. }
  17317. cloneTo(destObject) {
  17318. super.cloneTo(destObject);
  17319. var destShape = destObject;
  17320. destShape.radius = this.radius;
  17321. destShape.emitFromShell = this.emitFromShell;
  17322. destShape.randomDirection = this.randomDirection;
  17323. }
  17324. clone() {
  17325. var destShape = new HemisphereShape();
  17326. this.cloneTo(destShape);
  17327. return destShape;
  17328. }
  17329. }
  17330. class SphereShape extends BaseShape {
  17331. constructor() {
  17332. super();
  17333. this.radius = 1.0;
  17334. this.emitFromShell = false;
  17335. }
  17336. _getShapeBoundBox(boundBox) {
  17337. var min = boundBox.min;
  17338. min.x = min.y = min.z = -this.radius;
  17339. var max = boundBox.max;
  17340. max.x = max.y = max.z = this.radius;
  17341. }
  17342. _getSpeedBoundBox(boundBox) {
  17343. var min = boundBox.min;
  17344. min.x = min.y = min.z = -1;
  17345. var max = boundBox.max;
  17346. max.x = max.y = max.z = 1;
  17347. }
  17348. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  17349. if (rand) {
  17350. rand.seed = randomSeeds[16];
  17351. if (this.emitFromShell)
  17352. ShapeUtils._randomPointUnitSphere(position, rand);
  17353. else
  17354. ShapeUtils._randomPointInsideUnitSphere(position, rand);
  17355. randomSeeds[16] = rand.seed;
  17356. }
  17357. else {
  17358. if (this.emitFromShell)
  17359. ShapeUtils._randomPointUnitSphere(position);
  17360. else
  17361. ShapeUtils._randomPointInsideUnitSphere(position);
  17362. }
  17363. Vector3.scale(position, this.radius, position);
  17364. if (this.randomDirection) {
  17365. if (rand) {
  17366. rand.seed = randomSeeds[17];
  17367. ShapeUtils._randomPointUnitSphere(direction, rand);
  17368. randomSeeds[17] = rand.seed;
  17369. }
  17370. else {
  17371. ShapeUtils._randomPointUnitSphere(direction);
  17372. }
  17373. }
  17374. else {
  17375. position.cloneTo(direction);
  17376. }
  17377. }
  17378. cloneTo(destObject) {
  17379. super.cloneTo(destObject);
  17380. var destShape = destObject;
  17381. destShape.radius = this.radius;
  17382. destShape.emitFromShell = this.emitFromShell;
  17383. destShape.randomDirection = this.randomDirection;
  17384. }
  17385. clone() {
  17386. var destShape = new SphereShape();
  17387. this.cloneTo(destShape);
  17388. return destShape;
  17389. }
  17390. }
  17391. class SizeOverLifetime {
  17392. get size() {
  17393. return this._size;
  17394. }
  17395. constructor(size) {
  17396. this._size = size;
  17397. }
  17398. cloneTo(destObject) {
  17399. var destSizeOverLifetime = destObject;
  17400. this._size.cloneTo(destSizeOverLifetime._size);
  17401. destSizeOverLifetime.enable = this.enable;
  17402. }
  17403. clone() {
  17404. var destSize;
  17405. switch (this._size.type) {
  17406. case 0:
  17407. if (this._size.separateAxes)
  17408. destSize = GradientSize.createByGradientSeparate(this._size.gradientX.clone(), this._size.gradientY.clone(), this._size.gradientZ.clone());
  17409. else
  17410. destSize = GradientSize.createByGradient(this._size.gradient.clone());
  17411. break;
  17412. case 1:
  17413. if (this._size.separateAxes)
  17414. destSize = GradientSize.createByRandomTwoConstantSeparate(this._size.constantMinSeparate.clone(), this._size.constantMaxSeparate.clone());
  17415. else
  17416. destSize = GradientSize.createByRandomTwoConstant(this._size.constantMin, this._size.constantMax);
  17417. break;
  17418. case 2:
  17419. if (this._size.separateAxes)
  17420. destSize = GradientSize.createByRandomTwoGradientSeparate(this._size.gradientXMin.clone(), this._size.gradientYMin.clone(), this._size.gradientZMin.clone(), this._size.gradientXMax.clone(), this._size.gradientYMax.clone(), this._size.gradientZMax.clone());
  17421. else
  17422. destSize = GradientSize.createByRandomTwoGradient(this._size.gradientMin.clone(), this._size.gradientMax.clone());
  17423. break;
  17424. }
  17425. var destSizeOverLifetime = new SizeOverLifetime(destSize);
  17426. destSizeOverLifetime.enable = this.enable;
  17427. return destSizeOverLifetime;
  17428. }
  17429. }
  17430. class StartFrame {
  17431. constructor() {
  17432. this._type = 0;
  17433. this._constant = 0;
  17434. this._constantMin = 0;
  17435. this._constantMax = 0;
  17436. }
  17437. static createByConstant(constant = 0) {
  17438. var rotationOverLifetime = new StartFrame();
  17439. rotationOverLifetime._type = 0;
  17440. rotationOverLifetime._constant = constant;
  17441. return rotationOverLifetime;
  17442. }
  17443. static createByRandomTwoConstant(constantMin = 0, constantMax = 0) {
  17444. var rotationOverLifetime = new StartFrame();
  17445. rotationOverLifetime._type = 1;
  17446. rotationOverLifetime._constantMin = constantMin;
  17447. rotationOverLifetime._constantMax = constantMax;
  17448. return rotationOverLifetime;
  17449. }
  17450. get type() {
  17451. return this._type;
  17452. }
  17453. get constant() {
  17454. return this._constant;
  17455. }
  17456. get constantMin() {
  17457. return this._constantMin;
  17458. }
  17459. get constantMax() {
  17460. return this._constantMax;
  17461. }
  17462. cloneTo(destObject) {
  17463. var destStartFrame = destObject;
  17464. destStartFrame._type = this._type;
  17465. destStartFrame._constant = this._constant;
  17466. destStartFrame._constantMin = this._constantMin;
  17467. destStartFrame._constantMax = this._constantMax;
  17468. }
  17469. clone() {
  17470. var destStartFrame = new StartFrame();
  17471. this.cloneTo(destStartFrame);
  17472. return destStartFrame;
  17473. }
  17474. }
  17475. class TextureSheetAnimation {
  17476. constructor(frame, startFrame) {
  17477. this.type = 0;
  17478. this.randomRow = false;
  17479. this.rowIndex = 0;
  17480. this.cycles = 0;
  17481. this.enableUVChannels = 0;
  17482. this.enable = false;
  17483. this.tiles = new Vector2(1, 1);
  17484. this.type = 0;
  17485. this.randomRow = true;
  17486. this.rowIndex = 0;
  17487. this.cycles = 1;
  17488. this.enableUVChannels = 1;
  17489. this._frame = frame;
  17490. this._startFrame = startFrame;
  17491. }
  17492. get frame() {
  17493. return this._frame;
  17494. }
  17495. get startFrame() {
  17496. return this._startFrame;
  17497. }
  17498. cloneTo(destObject) {
  17499. var destTextureSheetAnimation = destObject;
  17500. this.tiles.cloneTo(destTextureSheetAnimation.tiles);
  17501. destTextureSheetAnimation.type = this.type;
  17502. destTextureSheetAnimation.randomRow = this.randomRow;
  17503. destTextureSheetAnimation.rowIndex = this.rowIndex;
  17504. destTextureSheetAnimation.cycles = this.cycles;
  17505. destTextureSheetAnimation.enableUVChannels = this.enableUVChannels;
  17506. destTextureSheetAnimation.enable = this.enable;
  17507. this._frame.cloneTo(destTextureSheetAnimation._frame);
  17508. this._startFrame.cloneTo(destTextureSheetAnimation._startFrame);
  17509. }
  17510. clone() {
  17511. var destFrame;
  17512. switch (this._frame.type) {
  17513. case 0:
  17514. destFrame = FrameOverTime.createByConstant(this._frame.constant);
  17515. break;
  17516. case 1:
  17517. destFrame = FrameOverTime.createByOverTime(this._frame.frameOverTimeData.clone());
  17518. break;
  17519. case 2:
  17520. destFrame = FrameOverTime.createByRandomTwoConstant(this._frame.constantMin, this._frame.constantMax);
  17521. break;
  17522. case 3:
  17523. destFrame = FrameOverTime.createByRandomTwoOverTime(this._frame.frameOverTimeDataMin.clone(), this._frame.frameOverTimeDataMax.clone());
  17524. break;
  17525. }
  17526. var destStartFrame;
  17527. switch (this._startFrame.type) {
  17528. case 0:
  17529. destStartFrame = StartFrame.createByConstant(this._startFrame.constant);
  17530. break;
  17531. case 1:
  17532. destStartFrame = StartFrame.createByRandomTwoConstant(this._startFrame.constantMin, this._startFrame.constantMax);
  17533. break;
  17534. }
  17535. var destTextureSheetAnimation = new TextureSheetAnimation(destFrame, destStartFrame);
  17536. this.cloneTo(destTextureSheetAnimation);
  17537. return destTextureSheetAnimation;
  17538. }
  17539. }
  17540. class VelocityOverLifetime {
  17541. constructor(velocity) {
  17542. this.enable = false;
  17543. this.space = 0;
  17544. this._velocity = velocity;
  17545. }
  17546. get velocity() {
  17547. return this._velocity;
  17548. }
  17549. cloneTo(destObject) {
  17550. var destVelocityOverLifetime = destObject;
  17551. this._velocity.cloneTo(destVelocityOverLifetime._velocity);
  17552. destVelocityOverLifetime.enable = this.enable;
  17553. destVelocityOverLifetime.space = this.space;
  17554. }
  17555. clone() {
  17556. var destVelocity;
  17557. switch (this._velocity.type) {
  17558. case 0:
  17559. destVelocity = GradientVelocity.createByConstant(this._velocity.constant.clone());
  17560. break;
  17561. case 1:
  17562. destVelocity = GradientVelocity.createByGradient(this._velocity.gradientX.clone(), this._velocity.gradientY.clone(), this._velocity.gradientZ.clone());
  17563. break;
  17564. case 2:
  17565. destVelocity = GradientVelocity.createByRandomTwoConstant(this._velocity.constantMin.clone(), this._velocity.constantMax.clone());
  17566. break;
  17567. case 3:
  17568. destVelocity = GradientVelocity.createByRandomTwoGradient(this._velocity.gradientXMin.clone(), this._velocity.gradientYMin.clone(), this._velocity.gradientZMin.clone(), this._velocity.gradientXMax.clone(), this._velocity.gradientYMax.clone(), this._velocity.gradientZMax.clone());
  17569. break;
  17570. }
  17571. var destVelocityOverLifetime = new VelocityOverLifetime(destVelocity);
  17572. destVelocityOverLifetime.enable = this.enable;
  17573. destVelocityOverLifetime.space = this.space;
  17574. return destVelocityOverLifetime;
  17575. }
  17576. }
  17577. class ShuriKenParticle3DShaderDeclaration {
  17578. }
  17579. ShuriKenParticle3DShaderDeclaration.WORLDPOSITION = Shader3D.propertyNameToID("u_WorldPosition");
  17580. ShuriKenParticle3DShaderDeclaration.WORLDROTATION = Shader3D.propertyNameToID("u_WorldRotation");
  17581. ShuriKenParticle3DShaderDeclaration.POSITIONSCALE = Shader3D.propertyNameToID("u_PositionScale");
  17582. ShuriKenParticle3DShaderDeclaration.SIZESCALE = Shader3D.propertyNameToID("u_SizeScale");
  17583. ShuriKenParticle3DShaderDeclaration.SCALINGMODE = Shader3D.propertyNameToID("u_ScalingMode");
  17584. ShuriKenParticle3DShaderDeclaration.GRAVITY = Shader3D.propertyNameToID("u_Gravity");
  17585. ShuriKenParticle3DShaderDeclaration.THREEDSTARTROTATION = Shader3D.propertyNameToID("u_ThreeDStartRotation");
  17586. ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDLENGTHSCALE = Shader3D.propertyNameToID("u_StretchedBillboardLengthScale");
  17587. ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDSPEEDSCALE = Shader3D.propertyNameToID("u_StretchedBillboardSpeedScale");
  17588. ShuriKenParticle3DShaderDeclaration.SIMULATIONSPACE = Shader3D.propertyNameToID("u_SimulationSpace");
  17589. ShuriKenParticle3DShaderDeclaration.CURRENTTIME = Shader3D.propertyNameToID("u_CurrentTime");
  17590. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST = Shader3D.propertyNameToID("u_VOLVelocityConst");
  17591. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX = Shader3D.propertyNameToID("u_VOLVelocityGradientX");
  17592. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY = Shader3D.propertyNameToID("u_VOLVelocityGradientY");
  17593. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ = Shader3D.propertyNameToID("u_VOLVelocityGradientZ");
  17594. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONSTMAX = Shader3D.propertyNameToID("u_VOLVelocityConstMax");
  17595. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTXMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxX");
  17596. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTYMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxY");
  17597. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxZ");
  17598. ShuriKenParticle3DShaderDeclaration.VOLSPACETYPE = Shader3D.propertyNameToID("u_VOLSpaceType");
  17599. ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS = Shader3D.propertyNameToID("u_ColorOverLifeGradientAlphas");
  17600. ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS = Shader3D.propertyNameToID("u_ColorOverLifeGradientColors");
  17601. ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS = Shader3D.propertyNameToID("u_MaxColorOverLifeGradientAlphas");
  17602. ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS = Shader3D.propertyNameToID("u_MaxColorOverLifeGradientColors");
  17603. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT = Shader3D.propertyNameToID("u_SOLSizeGradient");
  17604. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX = Shader3D.propertyNameToID("u_SOLSizeGradientX");
  17605. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY = Shader3D.propertyNameToID("u_SOLSizeGradientY");
  17606. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ = Shader3D.propertyNameToID("u_SOLSizeGradientZ");
  17607. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientMax = Shader3D.propertyNameToID("u_SOLSizeGradientMax");
  17608. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTXMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxX");
  17609. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTYMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxY");
  17610. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxZ");
  17611. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST = Shader3D.propertyNameToID("u_ROLAngularVelocityConst");
  17612. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE = Shader3D.propertyNameToID("u_ROLAngularVelocityConstSeprarate");
  17613. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT = Shader3D.propertyNameToID("u_ROLAngularVelocityGradient");
  17614. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientX");
  17615. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientY");
  17616. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientZ");
  17617. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityConstMax");
  17618. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAXSEPRARATE = Shader3D.propertyNameToID("u_ROLAngularVelocityConstMaxSeprarate");
  17619. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMax");
  17620. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTXMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxX");
  17621. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTYMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxY");
  17622. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxZ");
  17623. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTWMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxW");
  17624. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONCYCLES = Shader3D.propertyNameToID("u_TSACycles");
  17625. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONSUBUVLENGTH = Shader3D.propertyNameToID("u_TSASubUVLength");
  17626. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS = Shader3D.propertyNameToID("u_TSAGradientUVs");
  17627. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTMAXUVS = Shader3D.propertyNameToID("u_TSAMaxGradientUVs");
  17628. class ShurikenParticleMaterial extends Material {
  17629. constructor() {
  17630. super();
  17631. this.setShaderName("PARTICLESHURIKEN");
  17632. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  17633. this.renderMode = ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED;
  17634. }
  17635. static __initDefine__() {
  17636. ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP = Shader3D.getDefineByName("DIFFUSEMAP");
  17637. ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR = Shader3D.getDefineByName("TINTCOLOR");
  17638. ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  17639. ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  17640. }
  17641. get _TintColorR() {
  17642. return this._color.x;
  17643. }
  17644. set _TintColorR(value) {
  17645. this._color.x = value;
  17646. this.color = this._color;
  17647. }
  17648. get _TintColorG() {
  17649. return this._color.y;
  17650. }
  17651. set _TintColorG(value) {
  17652. this._color.y = value;
  17653. this.color = this._color;
  17654. }
  17655. get _TintColorB() {
  17656. return this._color.z;
  17657. }
  17658. set _TintColorB(value) {
  17659. this._color.z = value;
  17660. this.color = this._color;
  17661. }
  17662. get _TintColorA() {
  17663. return this._color.w;
  17664. }
  17665. set _TintColorA(value) {
  17666. this._color.w = value;
  17667. this.color = this._color;
  17668. }
  17669. get _MainTex_STX() {
  17670. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).x;
  17671. }
  17672. set _MainTex_STX(x) {
  17673. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  17674. tilOff.x = x;
  17675. this.tilingOffset = tilOff;
  17676. }
  17677. get _MainTex_STY() {
  17678. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).y;
  17679. }
  17680. set _MainTex_STY(y) {
  17681. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  17682. tilOff.y = y;
  17683. this.tilingOffset = tilOff;
  17684. }
  17685. get _MainTex_STZ() {
  17686. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).z;
  17687. }
  17688. set _MainTex_STZ(z) {
  17689. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  17690. tilOff.z = z;
  17691. this.tilingOffset = tilOff;
  17692. }
  17693. get _MainTex_STW() {
  17694. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).w;
  17695. }
  17696. set _MainTex_STW(w) {
  17697. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  17698. tilOff.w = w;
  17699. this.tilingOffset = tilOff;
  17700. }
  17701. set renderMode(value) {
  17702. switch (value) {
  17703. case ShurikenParticleMaterial.RENDERMODE_ADDTIVE:
  17704. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  17705. this.depthWrite = false;
  17706. this.cull = RenderState.CULL_NONE;
  17707. this.blend = RenderState.BLEND_ENABLE_ALL;
  17708. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  17709. this.blendDst = RenderState.BLENDPARAM_ONE;
  17710. this.alphaTest = false;
  17711. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG);
  17712. break;
  17713. case ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED:
  17714. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  17715. this.depthWrite = false;
  17716. this.cull = RenderState.CULL_NONE;
  17717. this.blend = RenderState.BLEND_ENABLE_ALL;
  17718. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  17719. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  17720. this.alphaTest = false;
  17721. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG);
  17722. break;
  17723. default:
  17724. throw new Error("ShurikenParticleMaterial : renderMode value error.");
  17725. }
  17726. }
  17727. get colorR() {
  17728. return this._TintColorR;
  17729. }
  17730. set colorR(value) {
  17731. this._TintColorR = value;
  17732. }
  17733. get colorG() {
  17734. return this._TintColorG;
  17735. }
  17736. set colorG(value) {
  17737. this._TintColorG = value;
  17738. }
  17739. get colorB() {
  17740. return this._TintColorB;
  17741. }
  17742. set colorB(value) {
  17743. this._TintColorB = value;
  17744. }
  17745. get colorA() {
  17746. return this._TintColorA;
  17747. }
  17748. set colorA(value) {
  17749. this._TintColorA = value;
  17750. }
  17751. get color() {
  17752. return this._shaderValues.getVector(ShurikenParticleMaterial.TINTCOLOR);
  17753. }
  17754. set color(value) {
  17755. if (value)
  17756. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR);
  17757. else
  17758. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR);
  17759. this._shaderValues.setVector(ShurikenParticleMaterial.TINTCOLOR, value);
  17760. }
  17761. get tilingOffsetX() {
  17762. return this._MainTex_STX;
  17763. }
  17764. set tilingOffsetX(x) {
  17765. this._MainTex_STX = x;
  17766. }
  17767. get tilingOffsetY() {
  17768. return this._MainTex_STY;
  17769. }
  17770. set tilingOffsetY(y) {
  17771. this._MainTex_STY = y;
  17772. }
  17773. get tilingOffsetZ() {
  17774. return this._MainTex_STZ;
  17775. }
  17776. set tilingOffsetZ(z) {
  17777. this._MainTex_STZ = z;
  17778. }
  17779. get tilingOffsetW() {
  17780. return this._MainTex_STW;
  17781. }
  17782. set tilingOffsetW(w) {
  17783. this._MainTex_STW = w;
  17784. }
  17785. get tilingOffset() {
  17786. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  17787. }
  17788. set tilingOffset(value) {
  17789. if (value) {
  17790. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  17791. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  17792. else
  17793. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  17794. }
  17795. else {
  17796. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  17797. }
  17798. this._shaderValues.setVector(ShurikenParticleMaterial.TILINGOFFSET, value);
  17799. }
  17800. get texture() {
  17801. return this._shaderValues.getTexture(ShurikenParticleMaterial.DIFFUSETEXTURE);
  17802. }
  17803. set texture(value) {
  17804. if (value)
  17805. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP);
  17806. else
  17807. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP);
  17808. this._shaderValues.setTexture(ShurikenParticleMaterial.DIFFUSETEXTURE, value);
  17809. }
  17810. get depthWrite() {
  17811. return this._shaderValues.getBool(ShurikenParticleMaterial.DEPTH_WRITE);
  17812. }
  17813. set depthWrite(value) {
  17814. this._shaderValues.setBool(ShurikenParticleMaterial.DEPTH_WRITE, value);
  17815. }
  17816. get cull() {
  17817. return this._shaderValues.getInt(ShurikenParticleMaterial.CULL);
  17818. }
  17819. set cull(value) {
  17820. this._shaderValues.setInt(ShurikenParticleMaterial.CULL, value);
  17821. }
  17822. get blend() {
  17823. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND);
  17824. }
  17825. set blend(value) {
  17826. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND, value);
  17827. }
  17828. get blendSrc() {
  17829. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND_SRC);
  17830. }
  17831. set blendSrc(value) {
  17832. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND_SRC, value);
  17833. }
  17834. get blendDst() {
  17835. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND_DST);
  17836. }
  17837. set blendDst(value) {
  17838. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND_DST, value);
  17839. }
  17840. get depthTest() {
  17841. return this._shaderValues.getInt(ShurikenParticleMaterial.DEPTH_TEST);
  17842. }
  17843. set depthTest(value) {
  17844. this._shaderValues.setInt(ShurikenParticleMaterial.DEPTH_TEST, value);
  17845. }
  17846. clone() {
  17847. var dest = new ShurikenParticleMaterial();
  17848. this.cloneTo(dest);
  17849. return dest;
  17850. }
  17851. }
  17852. ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED = 0;
  17853. ShurikenParticleMaterial.RENDERMODE_ADDTIVE = 1;
  17854. ShurikenParticleMaterial.DIFFUSETEXTURE = Shader3D.propertyNameToID("u_texture");
  17855. ShurikenParticleMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_Tintcolor");
  17856. ShurikenParticleMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  17857. ShurikenParticleMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  17858. ShurikenParticleMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  17859. ShurikenParticleMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  17860. ShurikenParticleMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  17861. ShurikenParticleMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  17862. ShurikenParticleMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  17863. class Physics3DUtils {
  17864. constructor() {
  17865. }
  17866. static setColliderCollision(collider1, collider2, collsion) {
  17867. }
  17868. static getIColliderCollision(collider1, collider2) {
  17869. return false;
  17870. }
  17871. }
  17872. Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER = 0x1;
  17873. Physics3DUtils.COLLISIONFILTERGROUP_STATICFILTER = 0x2;
  17874. Physics3DUtils.COLLISIONFILTERGROUP_KINEMATICFILTER = 0x4;
  17875. Physics3DUtils.COLLISIONFILTERGROUP_DEBRISFILTER = 0x8;
  17876. Physics3DUtils.COLLISIONFILTERGROUP_SENSORTRIGGER = 0x10;
  17877. Physics3DUtils.COLLISIONFILTERGROUP_CHARACTERFILTER = 0x20;
  17878. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER1 = 0x40;
  17879. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER2 = 0x80;
  17880. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER3 = 0x100;
  17881. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER4 = 0x200;
  17882. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER5 = 0x400;
  17883. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER6 = 0x800;
  17884. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER7 = 0x1000;
  17885. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER8 = 0x2000;
  17886. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER9 = 0x4000;
  17887. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER10 = 0x8000;
  17888. Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER = -1;
  17889. Physics3DUtils.gravity = new Vector3(0, -9.81, 0);
  17890. class ShurikenParticleRenderer extends BaseRender {
  17891. constructor(owner) {
  17892. super(owner);
  17893. this._finalGravity = new Vector3();
  17894. this._tempRotationMatrix = new Matrix4x4();
  17895. this._mesh = null;
  17896. this.stretchedBillboardCameraSpeedScale = 0;
  17897. this.stretchedBillboardSpeedScale = 0;
  17898. this.stretchedBillboardLengthScale = 2;
  17899. this._defaultBoundBox = new BoundBox(new Vector3(), new Vector3());
  17900. this.renderMode = 0;
  17901. this._supportOctree = false;
  17902. }
  17903. get renderMode() {
  17904. return this._renderMode;
  17905. }
  17906. set renderMode(value) {
  17907. if (this._renderMode !== value) {
  17908. var defineDatas = this._shaderValues;
  17909. switch (this._renderMode) {
  17910. case 0:
  17911. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD);
  17912. break;
  17913. case 1:
  17914. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD);
  17915. break;
  17916. case 2:
  17917. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD);
  17918. break;
  17919. case 3:
  17920. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD);
  17921. break;
  17922. case 4:
  17923. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH);
  17924. break;
  17925. }
  17926. this._renderMode = value;
  17927. switch (value) {
  17928. case 0:
  17929. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD);
  17930. break;
  17931. case 1:
  17932. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD);
  17933. break;
  17934. case 2:
  17935. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD);
  17936. break;
  17937. case 3:
  17938. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD);
  17939. break;
  17940. case 4:
  17941. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH);
  17942. break;
  17943. default:
  17944. throw new Error("ShurikenParticleRender: unknown renderMode Value.");
  17945. }
  17946. var parSys = this._owner.particleSystem;
  17947. (parSys) && (parSys._initBufferDatas());
  17948. }
  17949. }
  17950. get mesh() {
  17951. return this._mesh;
  17952. }
  17953. set mesh(value) {
  17954. if (this._mesh !== value) {
  17955. (this._mesh) && (this._mesh._removeReference());
  17956. this._mesh = value;
  17957. (value) && (value._addReference());
  17958. this._owner.particleSystem._initBufferDatas();
  17959. }
  17960. }
  17961. _calculateBoundingBox() {
  17962. var min = this._bounds.getMin();
  17963. min.x = -Number.MAX_VALUE;
  17964. min.y = -Number.MAX_VALUE;
  17965. min.z = -Number.MAX_VALUE;
  17966. this._bounds.setMin(min);
  17967. var max = this._bounds.getMax();
  17968. max.x = Number.MAX_VALUE;
  17969. max.y = Number.MAX_VALUE;
  17970. max.z = Number.MAX_VALUE;
  17971. this._bounds.setMax(max);
  17972. if (Laya.Render.supportWebGLPlusCulling) {
  17973. var min = this._bounds.getMin();
  17974. var max = this._bounds.getMax();
  17975. var buffer = FrustumCulling._cullingBuffer;
  17976. buffer[this._cullingBufferIndex + 1] = min.x;
  17977. buffer[this._cullingBufferIndex + 2] = min.y;
  17978. buffer[this._cullingBufferIndex + 3] = min.z;
  17979. buffer[this._cullingBufferIndex + 4] = max.x;
  17980. buffer[this._cullingBufferIndex + 5] = max.y;
  17981. buffer[this._cullingBufferIndex + 6] = max.z;
  17982. }
  17983. }
  17984. _needRender(boundFrustum, context) {
  17985. if (boundFrustum) {
  17986. if (boundFrustum.intersects(this.bounds._getBoundBox())) {
  17987. if (this._owner.particleSystem.isAlive)
  17988. return true;
  17989. else
  17990. return false;
  17991. }
  17992. else {
  17993. return false;
  17994. }
  17995. }
  17996. else {
  17997. return true;
  17998. }
  17999. }
  18000. _renderUpdate(context, transfrom) {
  18001. var particleSystem = this._owner.particleSystem;
  18002. var sv = this._shaderValues;
  18003. var transform = this._owner.transform;
  18004. switch (particleSystem.simulationSpace) {
  18005. case 0:
  18006. break;
  18007. case 1:
  18008. sv.setVector3(ShuriKenParticle3DShaderDeclaration.WORLDPOSITION, transform.position);
  18009. sv.setQuaternion(ShuriKenParticle3DShaderDeclaration.WORLDROTATION, transform.rotation);
  18010. break;
  18011. default:
  18012. throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid.");
  18013. }
  18014. switch (particleSystem.scaleMode) {
  18015. case 0:
  18016. var scale = transform.getWorldLossyScale();
  18017. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, scale);
  18018. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, scale);
  18019. break;
  18020. case 1:
  18021. var localScale = transform.localScale;
  18022. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, localScale);
  18023. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, localScale);
  18024. break;
  18025. case 2:
  18026. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, transform.getWorldLossyScale());
  18027. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, Vector3._ONE);
  18028. break;
  18029. }
  18030. Vector3.scale(Physics3DUtils.gravity, particleSystem.gravityModifier, this._finalGravity);
  18031. sv.setVector3(ShuriKenParticle3DShaderDeclaration.GRAVITY, this._finalGravity);
  18032. sv.setInt(ShuriKenParticle3DShaderDeclaration.SIMULATIONSPACE, particleSystem.simulationSpace);
  18033. sv.setBool(ShuriKenParticle3DShaderDeclaration.THREEDSTARTROTATION, particleSystem.threeDStartRotation);
  18034. sv.setInt(ShuriKenParticle3DShaderDeclaration.SCALINGMODE, particleSystem.scaleMode);
  18035. sv.setNumber(ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDLENGTHSCALE, this.stretchedBillboardLengthScale);
  18036. sv.setNumber(ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDSPEEDSCALE, this.stretchedBillboardSpeedScale);
  18037. sv.setNumber(ShuriKenParticle3DShaderDeclaration.CURRENTTIME, particleSystem._currentTime);
  18038. }
  18039. get bounds() {
  18040. if (this._boundsChange) {
  18041. this._calculateBoundingBox();
  18042. this._boundsChange = false;
  18043. }
  18044. return this._bounds;
  18045. }
  18046. _destroy() {
  18047. super._destroy();
  18048. (this._mesh) && (this._mesh._removeReference(), this._mesh = null);
  18049. }
  18050. }
  18051. class VertexShuriKenParticle {
  18052. constructor() {
  18053. }
  18054. }
  18055. VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0 = 0;
  18056. VertexShuriKenParticle.PARTICLE_POSITION0 = 1;
  18057. VertexShuriKenParticle.PARTICLE_COLOR0 = 2;
  18058. VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0 = 3;
  18059. VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME = 4;
  18060. VertexShuriKenParticle.PARTICLE_DIRECTIONTIME = 5;
  18061. VertexShuriKenParticle.PARTICLE_STARTCOLOR0 = 6;
  18062. VertexShuriKenParticle.PARTICLE_ENDCOLOR0 = 7;
  18063. VertexShuriKenParticle.PARTICLE_STARTSIZE = 8;
  18064. VertexShuriKenParticle.PARTICLE_STARTROTATION = 9;
  18065. VertexShuriKenParticle.PARTICLE_STARTSPEED = 10;
  18066. VertexShuriKenParticle.PARTICLE_RANDOM0 = 11;
  18067. VertexShuriKenParticle.PARTICLE_RANDOM1 = 12;
  18068. VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION = 13;
  18069. VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION = 14;
  18070. class VertexShurikenParticleBillboard extends VertexShuriKenParticle {
  18071. static get vertexDeclaration() {
  18072. return VertexShurikenParticleBillboard._vertexDeclaration;
  18073. }
  18074. static __init__() {
  18075. VertexShurikenParticleBillboard._vertexDeclaration = new VertexDeclaration(152, [new VertexElement(0, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0),
  18076. new VertexElement(16, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME),
  18077. new VertexElement(32, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_DIRECTIONTIME),
  18078. new VertexElement(48, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_STARTCOLOR0),
  18079. new VertexElement(64, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTSIZE),
  18080. new VertexElement(76, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTROTATION),
  18081. new VertexElement(88, VertexElementFormat.Single, VertexShuriKenParticle.PARTICLE_STARTSPEED),
  18082. new VertexElement(92, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM0),
  18083. new VertexElement(108, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM1),
  18084. new VertexElement(124, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION),
  18085. new VertexElement(136, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION)]);
  18086. }
  18087. get cornerTextureCoordinate() {
  18088. return this._cornerTextureCoordinate;
  18089. }
  18090. get positionStartLifeTime() {
  18091. return this._positionStartLifeTime;
  18092. }
  18093. get velocity() {
  18094. return this._velocity;
  18095. }
  18096. get startColor() {
  18097. return this._startColor;
  18098. }
  18099. get startSize() {
  18100. return this._startSize;
  18101. }
  18102. get startRotation0() {
  18103. return this._startRotation0;
  18104. }
  18105. get startRotation1() {
  18106. return this._startRotation1;
  18107. }
  18108. get startRotation2() {
  18109. return this._startRotation2;
  18110. }
  18111. get startLifeTime() {
  18112. return this._startLifeTime;
  18113. }
  18114. get time() {
  18115. return this._time;
  18116. }
  18117. get startSpeed() {
  18118. return this._startSpeed;
  18119. }
  18120. get random0() {
  18121. return this._randoms0;
  18122. }
  18123. get random1() {
  18124. return this._randoms1;
  18125. }
  18126. get simulationWorldPostion() {
  18127. return this._simulationWorldPostion;
  18128. }
  18129. constructor(cornerTextureCoordinate, positionStartLifeTime, velocity, startColor, startSize, startRotation0, startRotation1, startRotation2, ageAddScale, time, startSpeed, randoms0, randoms1, simulationWorldPostion) {
  18130. super();
  18131. this._cornerTextureCoordinate = cornerTextureCoordinate;
  18132. this._positionStartLifeTime = positionStartLifeTime;
  18133. this._velocity = velocity;
  18134. this._startColor = startColor;
  18135. this._startSize = startSize;
  18136. this._startRotation0 = startRotation0;
  18137. this._startRotation1 = startRotation1;
  18138. this._startRotation2 = startRotation2;
  18139. this._startLifeTime = ageAddScale;
  18140. this._time = time;
  18141. this._startSpeed = startSpeed;
  18142. this._randoms0 = this.random0;
  18143. this._randoms1 = this.random1;
  18144. this._simulationWorldPostion = simulationWorldPostion;
  18145. }
  18146. }
  18147. class VertexShurikenParticleMesh extends VertexShuriKenParticle {
  18148. static __init__() {
  18149. VertexShurikenParticleMesh._vertexDeclaration = new VertexDeclaration(172, [new VertexElement(0, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_POSITION0),
  18150. new VertexElement(12, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_COLOR0),
  18151. new VertexElement(28, VertexElementFormat.Vector2, VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0),
  18152. new VertexElement(36, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME),
  18153. new VertexElement(52, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_DIRECTIONTIME),
  18154. new VertexElement(68, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_STARTCOLOR0),
  18155. new VertexElement(84, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTSIZE),
  18156. new VertexElement(96, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTROTATION),
  18157. new VertexElement(108, VertexElementFormat.Single, VertexShuriKenParticle.PARTICLE_STARTSPEED),
  18158. new VertexElement(112, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM0),
  18159. new VertexElement(128, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM1),
  18160. new VertexElement(144, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION),
  18161. new VertexElement(156, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION)]);
  18162. }
  18163. static get vertexDeclaration() {
  18164. return VertexShurikenParticleMesh._vertexDeclaration;
  18165. }
  18166. get cornerTextureCoordinate() {
  18167. return this._cornerTextureCoordinate;
  18168. }
  18169. get position() {
  18170. return this._positionStartLifeTime;
  18171. }
  18172. get velocity() {
  18173. return this._velocity;
  18174. }
  18175. get startColor() {
  18176. return this._startColor;
  18177. }
  18178. get startSize() {
  18179. return this._startSize;
  18180. }
  18181. get startRotation0() {
  18182. return this._startRotation0;
  18183. }
  18184. get startRotation1() {
  18185. return this._startRotation1;
  18186. }
  18187. get startRotation2() {
  18188. return this._startRotation2;
  18189. }
  18190. get startLifeTime() {
  18191. return this._startLifeTime;
  18192. }
  18193. get time() {
  18194. return this._time;
  18195. }
  18196. get startSpeed() {
  18197. return this._startSpeed;
  18198. }
  18199. get random0() {
  18200. return this._randoms0;
  18201. }
  18202. get random1() {
  18203. return this._randoms1;
  18204. }
  18205. get simulationWorldPostion() {
  18206. return this._simulationWorldPostion;
  18207. }
  18208. constructor(cornerTextureCoordinate, positionStartLifeTime, velocity, startColor, startSize, startRotation0, startRotation1, startRotation2, ageAddScale, time, startSpeed, randoms0, randoms1, simulationWorldPostion) {
  18209. super();
  18210. this._cornerTextureCoordinate = cornerTextureCoordinate;
  18211. this._positionStartLifeTime = positionStartLifeTime;
  18212. this._velocity = velocity;
  18213. this._startColor = startColor;
  18214. this._startSize = startSize;
  18215. this._startRotation0 = startRotation0;
  18216. this._startRotation1 = startRotation1;
  18217. this._startRotation2 = startRotation2;
  18218. this._startLifeTime = ageAddScale;
  18219. this._time = time;
  18220. this._startSpeed = startSpeed;
  18221. this._randoms0 = this.random0;
  18222. this._randoms1 = this.random1;
  18223. this._simulationWorldPostion = simulationWorldPostion;
  18224. }
  18225. }
  18226. class BoundSphere {
  18227. constructor(center, radius) {
  18228. this.center = center;
  18229. this.radius = radius;
  18230. }
  18231. toDefault() {
  18232. this.center.toDefault();
  18233. this.radius = 0;
  18234. }
  18235. static createFromSubPoints(points, start, count, out) {
  18236. if (points == null) {
  18237. throw new Error("points");
  18238. }
  18239. if (start < 0 || start >= points.length) {
  18240. throw new Error("start" + start + "Must be in the range [0, " + (points.length - 1) + "]");
  18241. }
  18242. if (count < 0 || (start + count) > points.length) {
  18243. throw new Error("count" + count + "Must be in the range <= " + points.length + "}");
  18244. }
  18245. var upperEnd = start + count;
  18246. var center = BoundSphere._tempVector3;
  18247. center.x = 0;
  18248. center.y = 0;
  18249. center.z = 0;
  18250. for (var i = start; i < upperEnd; ++i) {
  18251. Vector3.add(points[i], center, center);
  18252. }
  18253. var outCenter = out.center;
  18254. Vector3.scale(center, 1 / count, outCenter);
  18255. var radius = 0.0;
  18256. for (i = start; i < upperEnd; ++i) {
  18257. var distance = Vector3.distanceSquared(outCenter, points[i]);
  18258. if (distance > radius)
  18259. radius = distance;
  18260. }
  18261. out.radius = Math.sqrt(radius);
  18262. }
  18263. static createfromPoints(points, out) {
  18264. if (points == null) {
  18265. throw new Error("points");
  18266. }
  18267. BoundSphere.createFromSubPoints(points, 0, points.length, out);
  18268. }
  18269. intersectsRayDistance(ray) {
  18270. return CollisionUtils.intersectsRayAndSphereRD(ray, this);
  18271. }
  18272. intersectsRayPoint(ray, outPoint) {
  18273. return CollisionUtils.intersectsRayAndSphereRP(ray, this, outPoint);
  18274. }
  18275. cloneTo(destObject) {
  18276. var dest = destObject;
  18277. this.center.cloneTo(dest.center);
  18278. dest.radius = this.radius;
  18279. }
  18280. clone() {
  18281. var dest = new BoundSphere(new Vector3(), 0);
  18282. this.cloneTo(dest);
  18283. return dest;
  18284. }
  18285. }
  18286. BoundSphere._tempVector3 = new Vector3();
  18287. class Rand {
  18288. constructor(seed) {
  18289. this._temp = new Uint32Array(1);
  18290. this.seeds = new Uint32Array(4);
  18291. this.seeds[0] = seed;
  18292. this.seeds[1] = this.seeds[0] * 0x6C078965 + 1;
  18293. this.seeds[2] = this.seeds[1] * 0x6C078965 + 1;
  18294. this.seeds[3] = this.seeds[2] * 0x6C078965 + 1;
  18295. }
  18296. static getFloatFromInt(v) {
  18297. return (v & 0x007FFFFF) * (1.0 / 8388607.0);
  18298. }
  18299. static getByteFromInt(v) {
  18300. return (v & 0x007FFFFF) >>> 15;
  18301. }
  18302. get seed() {
  18303. return this.seeds[0];
  18304. }
  18305. set seed(seed) {
  18306. this.seeds[0] = seed;
  18307. this.seeds[1] = this.seeds[0] * 0x6C078965 + 1;
  18308. this.seeds[2] = this.seeds[1] * 0x6C078965 + 1;
  18309. this.seeds[3] = this.seeds[2] * 0x6C078965 + 1;
  18310. }
  18311. getUint() {
  18312. this._temp[0] = this.seeds[0] ^ (this.seeds[0] << 11);
  18313. this.seeds[0] = this.seeds[1];
  18314. this.seeds[1] = this.seeds[2];
  18315. this.seeds[2] = this.seeds[3];
  18316. this.seeds[3] = (this.seeds[3] ^ (this.seeds[3] >>> 19)) ^ (this._temp[0] ^ (this._temp[0] >>> 8));
  18317. return this.seeds[3];
  18318. }
  18319. getFloat() {
  18320. this.getUint();
  18321. return (this.seeds[3] & 0x007FFFFF) * (1.0 / 8388607.0);
  18322. }
  18323. getSignedFloat() {
  18324. return this.getFloat() * 2.0 - 1.0;
  18325. }
  18326. }
  18327. class Emission {
  18328. constructor() {
  18329. this._emissionRate = 10;
  18330. this._destroyed = false;
  18331. this._bursts = [];
  18332. }
  18333. set emissionRate(value) {
  18334. if (value < 0)
  18335. throw new Error("ParticleBaseShape:emissionRate value must large or equal than 0.");
  18336. this._emissionRate = value;
  18337. }
  18338. get emissionRate() {
  18339. return this._emissionRate;
  18340. }
  18341. get destroyed() {
  18342. return this._destroyed;
  18343. }
  18344. destroy() {
  18345. this._bursts = null;
  18346. this._destroyed = true;
  18347. }
  18348. getBurstsCount() {
  18349. return this._bursts.length;
  18350. }
  18351. getBurstByIndex(index) {
  18352. return this._bursts[index];
  18353. }
  18354. addBurst(burst) {
  18355. var burstsCount = this._bursts.length;
  18356. if (burstsCount > 0)
  18357. for (var i = 0; i < burstsCount; i++) {
  18358. if (this._bursts[i].time > burst.time)
  18359. this._bursts.splice(i, 0, burst);
  18360. }
  18361. this._bursts.push(burst);
  18362. }
  18363. removeBurst(burst) {
  18364. var index = this._bursts.indexOf(burst);
  18365. if (index !== -1) {
  18366. this._bursts.splice(index, 1);
  18367. }
  18368. }
  18369. removeBurstByIndex(index) {
  18370. this._bursts.splice(index, 1);
  18371. }
  18372. clearBurst() {
  18373. this._bursts.length = 0;
  18374. }
  18375. cloneTo(destObject) {
  18376. var destEmission = destObject;
  18377. var destBursts = destEmission._bursts;
  18378. destBursts.length = this._bursts.length;
  18379. for (var i = 0, n = this._bursts.length; i < n; i++) {
  18380. var destBurst = destBursts[i];
  18381. if (destBurst)
  18382. this._bursts[i].cloneTo(destBurst);
  18383. else
  18384. destBursts[i] = this._bursts[i].clone();
  18385. }
  18386. destEmission._emissionRate = this._emissionRate;
  18387. destEmission.enable = this.enable;
  18388. }
  18389. clone() {
  18390. var destEmission = new Emission();
  18391. this.cloneTo(destEmission);
  18392. return destEmission;
  18393. }
  18394. }
  18395. class ShurikenParticleData {
  18396. constructor() {
  18397. }
  18398. static _getStartLifetimeFromGradient(startLifeTimeGradient, emissionTime) {
  18399. for (var i = 1, n = startLifeTimeGradient.gradientCount; i < n; i++) {
  18400. var key = startLifeTimeGradient.getKeyByIndex(i);
  18401. if (key >= emissionTime) {
  18402. var lastKey = startLifeTimeGradient.getKeyByIndex(i - 1);
  18403. var age = (emissionTime - lastKey) / (key - lastKey);
  18404. return Laya.MathUtil.lerp(startLifeTimeGradient.getValueByIndex(i - 1), startLifeTimeGradient.getValueByIndex(i), age);
  18405. }
  18406. }
  18407. throw new Error("ShurikenParticleData: can't get value foam startLifeTimeGradient.");
  18408. }
  18409. static _randomInvertRoationArray(rotatonE, outE, randomizeRotationDirection, rand, randomSeeds) {
  18410. var randDic;
  18411. if (rand) {
  18412. rand.seed = randomSeeds[6];
  18413. randDic = rand.getFloat();
  18414. randomSeeds[6] = rand.seed;
  18415. }
  18416. else {
  18417. randDic = Math.random();
  18418. }
  18419. if (randDic < randomizeRotationDirection) {
  18420. outE.x = -rotatonE.x;
  18421. outE.y = -rotatonE.y;
  18422. outE.z = -rotatonE.z;
  18423. }
  18424. else {
  18425. outE.x = rotatonE.x;
  18426. outE.y = rotatonE.y;
  18427. outE.z = rotatonE.z;
  18428. }
  18429. }
  18430. static _randomInvertRoation(rotaton, randomizeRotationDirection, rand, randomSeeds) {
  18431. var randDic;
  18432. if (rand) {
  18433. rand.seed = randomSeeds[6];
  18434. randDic = rand.getFloat();
  18435. randomSeeds[6] = rand.seed;
  18436. }
  18437. else {
  18438. randDic = Math.random();
  18439. }
  18440. if (randDic < randomizeRotationDirection)
  18441. rotaton = -rotaton;
  18442. return rotaton;
  18443. }
  18444. static create(particleSystem, particleRender, transform) {
  18445. var autoRandomSeed = particleSystem.autoRandomSeed;
  18446. var rand = particleSystem._rand;
  18447. var randomSeeds = particleSystem._randomSeeds;
  18448. switch (particleSystem.startColorType) {
  18449. case 0:
  18450. var constantStartColor = particleSystem.startColorConstant;
  18451. ShurikenParticleData.startColor.x = constantStartColor.x;
  18452. ShurikenParticleData.startColor.y = constantStartColor.y;
  18453. ShurikenParticleData.startColor.z = constantStartColor.z;
  18454. ShurikenParticleData.startColor.w = constantStartColor.w;
  18455. break;
  18456. case 2:
  18457. if (autoRandomSeed) {
  18458. Vector4.lerp(particleSystem.startColorConstantMin, particleSystem.startColorConstantMax, Math.random(), ShurikenParticleData.startColor);
  18459. }
  18460. else {
  18461. rand.seed = randomSeeds[3];
  18462. Vector4.lerp(particleSystem.startColorConstantMin, particleSystem.startColorConstantMax, rand.getFloat(), ShurikenParticleData.startColor);
  18463. randomSeeds[3] = rand.seed;
  18464. }
  18465. break;
  18466. }
  18467. var colorOverLifetime = particleSystem.colorOverLifetime;
  18468. if (colorOverLifetime && colorOverLifetime.enable) {
  18469. var color = colorOverLifetime.color;
  18470. switch (color.type) {
  18471. case 0:
  18472. ShurikenParticleData.startColor.x = ShurikenParticleData.startColor.x * color.constant.x;
  18473. ShurikenParticleData.startColor.y = ShurikenParticleData.startColor.y * color.constant.y;
  18474. ShurikenParticleData.startColor.z = ShurikenParticleData.startColor.z * color.constant.z;
  18475. ShurikenParticleData.startColor.w = ShurikenParticleData.startColor.w * color.constant.w;
  18476. break;
  18477. case 2:
  18478. var colorRandom;
  18479. if (autoRandomSeed) {
  18480. colorRandom = Math.random();
  18481. }
  18482. else {
  18483. rand.seed = randomSeeds[10];
  18484. colorRandom = rand.getFloat();
  18485. randomSeeds[10] = rand.seed;
  18486. }
  18487. var minConstantColor = color.constantMin;
  18488. var maxConstantColor = color.constantMax;
  18489. ShurikenParticleData.startColor.x = ShurikenParticleData.startColor.x * Laya.MathUtil.lerp(minConstantColor.x, maxConstantColor.x, colorRandom);
  18490. ShurikenParticleData.startColor.y = ShurikenParticleData.startColor.y * Laya.MathUtil.lerp(minConstantColor.y, maxConstantColor.y, colorRandom);
  18491. ShurikenParticleData.startColor.z = ShurikenParticleData.startColor.z * Laya.MathUtil.lerp(minConstantColor.z, maxConstantColor.z, colorRandom);
  18492. ShurikenParticleData.startColor.w = ShurikenParticleData.startColor.w * Laya.MathUtil.lerp(minConstantColor.w, maxConstantColor.w, colorRandom);
  18493. break;
  18494. }
  18495. }
  18496. var particleSize = ShurikenParticleData.startSize;
  18497. switch (particleSystem.startSizeType) {
  18498. case 0:
  18499. if (particleSystem.threeDStartSize) {
  18500. var startSizeConstantSeparate = particleSystem.startSizeConstantSeparate;
  18501. particleSize[0] = startSizeConstantSeparate.x;
  18502. particleSize[1] = startSizeConstantSeparate.y;
  18503. particleSize[2] = startSizeConstantSeparate.z;
  18504. }
  18505. else {
  18506. particleSize[0] = particleSize[1] = particleSize[2] = particleSystem.startSizeConstant;
  18507. }
  18508. break;
  18509. case 2:
  18510. if (particleSystem.threeDStartSize) {
  18511. var startSizeConstantMinSeparate = particleSystem.startSizeConstantMinSeparate;
  18512. var startSizeConstantMaxSeparate = particleSystem.startSizeConstantMaxSeparate;
  18513. if (autoRandomSeed) {
  18514. particleSize[0] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.x, startSizeConstantMaxSeparate.x, Math.random());
  18515. particleSize[1] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.y, startSizeConstantMaxSeparate.y, Math.random());
  18516. particleSize[2] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.z, startSizeConstantMaxSeparate.z, Math.random());
  18517. }
  18518. else {
  18519. rand.seed = randomSeeds[4];
  18520. particleSize[0] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.x, startSizeConstantMaxSeparate.x, rand.getFloat());
  18521. particleSize[1] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.y, startSizeConstantMaxSeparate.y, rand.getFloat());
  18522. particleSize[2] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.z, startSizeConstantMaxSeparate.z, rand.getFloat());
  18523. randomSeeds[4] = rand.seed;
  18524. }
  18525. }
  18526. else {
  18527. if (autoRandomSeed) {
  18528. particleSize[0] = particleSize[1] = particleSize[2] = Laya.MathUtil.lerp(particleSystem.startSizeConstantMin, particleSystem.startSizeConstantMax, Math.random());
  18529. }
  18530. else {
  18531. rand.seed = randomSeeds[4];
  18532. particleSize[0] = particleSize[1] = particleSize[2] = Laya.MathUtil.lerp(particleSystem.startSizeConstantMin, particleSystem.startSizeConstantMax, rand.getFloat());
  18533. randomSeeds[4] = rand.seed;
  18534. }
  18535. }
  18536. break;
  18537. }
  18538. var sizeOverLifetime = particleSystem.sizeOverLifetime;
  18539. if (sizeOverLifetime && sizeOverLifetime.enable && sizeOverLifetime.size.type === 1) {
  18540. var size = sizeOverLifetime.size;
  18541. if (size.separateAxes) {
  18542. if (autoRandomSeed) {
  18543. particleSize[0] = particleSize[0] * Laya.MathUtil.lerp(size.constantMinSeparate.x, size.constantMaxSeparate.x, Math.random());
  18544. particleSize[1] = particleSize[1] * Laya.MathUtil.lerp(size.constantMinSeparate.y, size.constantMaxSeparate.y, Math.random());
  18545. particleSize[2] = particleSize[2] * Laya.MathUtil.lerp(size.constantMinSeparate.z, size.constantMaxSeparate.z, Math.random());
  18546. }
  18547. else {
  18548. rand.seed = randomSeeds[11];
  18549. particleSize[0] = particleSize[0] * Laya.MathUtil.lerp(size.constantMinSeparate.x, size.constantMaxSeparate.x, rand.getFloat());
  18550. particleSize[1] = particleSize[1] * Laya.MathUtil.lerp(size.constantMinSeparate.y, size.constantMaxSeparate.y, rand.getFloat());
  18551. particleSize[2] = particleSize[2] * Laya.MathUtil.lerp(size.constantMinSeparate.z, size.constantMaxSeparate.z, rand.getFloat());
  18552. randomSeeds[11] = rand.seed;
  18553. }
  18554. }
  18555. else {
  18556. var randomSize;
  18557. if (autoRandomSeed) {
  18558. randomSize = Laya.MathUtil.lerp(size.constantMin, size.constantMax, Math.random());
  18559. }
  18560. else {
  18561. rand.seed = randomSeeds[11];
  18562. randomSize = Laya.MathUtil.lerp(size.constantMin, size.constantMax, rand.getFloat());
  18563. randomSeeds[11] = rand.seed;
  18564. }
  18565. particleSize[0] = particleSize[0] * randomSize;
  18566. particleSize[1] = particleSize[1] * randomSize;
  18567. particleSize[2] = particleSize[2] * randomSize;
  18568. }
  18569. }
  18570. var renderMode = particleRender.renderMode;
  18571. if (renderMode !== 1) {
  18572. switch (particleSystem.startRotationType) {
  18573. case 0:
  18574. if (particleSystem.threeDStartRotation) {
  18575. var startRotationConstantSeparate = particleSystem.startRotationConstantSeparate;
  18576. var randomRotationE = ShurikenParticleData._tempVector30;
  18577. ShurikenParticleData._randomInvertRoationArray(startRotationConstantSeparate, randomRotationE, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  18578. ShurikenParticleData.startRotation[0] = randomRotationE.x;
  18579. ShurikenParticleData.startRotation[1] = randomRotationE.y;
  18580. if (renderMode !== 4)
  18581. ShurikenParticleData.startRotation[2] = -randomRotationE.z;
  18582. else
  18583. ShurikenParticleData.startRotation[2] = randomRotationE.z;
  18584. }
  18585. else {
  18586. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(particleSystem.startRotationConstant, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  18587. ShurikenParticleData.startRotation[1] = 0;
  18588. ShurikenParticleData.startRotation[2] = 0;
  18589. }
  18590. break;
  18591. case 2:
  18592. if (particleSystem.threeDStartRotation) {
  18593. var startRotationConstantMinSeparate = particleSystem.startRotationConstantMinSeparate;
  18594. var startRotationConstantMaxSeparate = particleSystem.startRotationConstantMaxSeparate;
  18595. var lerpRoationE = ShurikenParticleData._tempVector30;
  18596. if (autoRandomSeed) {
  18597. lerpRoationE.x = Laya.MathUtil.lerp(startRotationConstantMinSeparate.x, startRotationConstantMaxSeparate.x, Math.random());
  18598. lerpRoationE.y = Laya.MathUtil.lerp(startRotationConstantMinSeparate.y, startRotationConstantMaxSeparate.y, Math.random());
  18599. lerpRoationE.z = Laya.MathUtil.lerp(startRotationConstantMinSeparate.z, startRotationConstantMaxSeparate.z, Math.random());
  18600. }
  18601. else {
  18602. rand.seed = randomSeeds[5];
  18603. lerpRoationE.x = Laya.MathUtil.lerp(startRotationConstantMinSeparate.x, startRotationConstantMaxSeparate.x, rand.getFloat());
  18604. lerpRoationE.y = Laya.MathUtil.lerp(startRotationConstantMinSeparate.y, startRotationConstantMaxSeparate.y, rand.getFloat());
  18605. lerpRoationE.z = Laya.MathUtil.lerp(startRotationConstantMinSeparate.z, startRotationConstantMaxSeparate.z, rand.getFloat());
  18606. randomSeeds[5] = rand.seed;
  18607. }
  18608. ShurikenParticleData._randomInvertRoationArray(lerpRoationE, lerpRoationE, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  18609. ShurikenParticleData.startRotation[0] = lerpRoationE.x;
  18610. ShurikenParticleData.startRotation[1] = lerpRoationE.y;
  18611. if (renderMode !== 4)
  18612. ShurikenParticleData.startRotation[2] = -lerpRoationE.z;
  18613. else
  18614. ShurikenParticleData.startRotation[2] = lerpRoationE.z;
  18615. }
  18616. else {
  18617. if (autoRandomSeed) {
  18618. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(Laya.MathUtil.lerp(particleSystem.startRotationConstantMin, particleSystem.startRotationConstantMax, Math.random()), particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  18619. }
  18620. else {
  18621. rand.seed = randomSeeds[5];
  18622. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(Laya.MathUtil.lerp(particleSystem.startRotationConstantMin, particleSystem.startRotationConstantMax, rand.getFloat()), particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  18623. randomSeeds[5] = rand.seed;
  18624. }
  18625. }
  18626. break;
  18627. }
  18628. }
  18629. switch (particleSystem.startLifetimeType) {
  18630. case 0:
  18631. ShurikenParticleData.startLifeTime = particleSystem.startLifetimeConstant;
  18632. break;
  18633. case 1:
  18634. ShurikenParticleData.startLifeTime = ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradient, particleSystem.emissionTime);
  18635. break;
  18636. case 2:
  18637. if (autoRandomSeed) {
  18638. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(particleSystem.startLifetimeConstantMin, particleSystem.startLifetimeConstantMax, Math.random());
  18639. }
  18640. else {
  18641. rand.seed = randomSeeds[7];
  18642. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(particleSystem.startLifetimeConstantMin, particleSystem.startLifetimeConstantMax, rand.getFloat());
  18643. randomSeeds[7] = rand.seed;
  18644. }
  18645. break;
  18646. case 3:
  18647. var emissionTime = particleSystem.emissionTime;
  18648. if (autoRandomSeed) {
  18649. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin, emissionTime), ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax, emissionTime), Math.random());
  18650. }
  18651. else {
  18652. rand.seed = randomSeeds[7];
  18653. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin, emissionTime), ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax, emissionTime), rand.getFloat());
  18654. randomSeeds[7] = rand.seed;
  18655. }
  18656. break;
  18657. }
  18658. var textureSheetAnimation = particleSystem.textureSheetAnimation;
  18659. var enableSheetAnimation = textureSheetAnimation && textureSheetAnimation.enable;
  18660. if (enableSheetAnimation) {
  18661. var title = textureSheetAnimation.tiles;
  18662. var titleX = title.x, titleY = title.y;
  18663. var subU = 1.0 / titleX, subV = 1.0 / titleY;
  18664. var startFrameCount;
  18665. var startFrame = textureSheetAnimation.startFrame;
  18666. switch (startFrame.type) {
  18667. case 0:
  18668. startFrameCount = startFrame.constant;
  18669. break;
  18670. case 1:
  18671. if (autoRandomSeed) {
  18672. startFrameCount = Laya.MathUtil.lerp(startFrame.constantMin, startFrame.constantMax, Math.random());
  18673. }
  18674. else {
  18675. rand.seed = randomSeeds[14];
  18676. startFrameCount = Laya.MathUtil.lerp(startFrame.constantMin, startFrame.constantMax, rand.getFloat());
  18677. randomSeeds[14] = rand.seed;
  18678. }
  18679. break;
  18680. }
  18681. var frame = textureSheetAnimation.frame;
  18682. var cycles = textureSheetAnimation.cycles;
  18683. switch (frame.type) {
  18684. case 0:
  18685. startFrameCount += frame.constant * cycles;
  18686. break;
  18687. case 2:
  18688. if (autoRandomSeed) {
  18689. startFrameCount += Laya.MathUtil.lerp(frame.constantMin, frame.constantMax, Math.random()) * cycles;
  18690. }
  18691. else {
  18692. rand.seed = randomSeeds[15];
  18693. startFrameCount += Laya.MathUtil.lerp(frame.constantMin, frame.constantMax, rand.getFloat()) * cycles;
  18694. randomSeeds[15] = rand.seed;
  18695. }
  18696. break;
  18697. }
  18698. var startRow = 0;
  18699. switch (textureSheetAnimation.type) {
  18700. case 0:
  18701. startRow = Math.floor(startFrameCount / titleX);
  18702. break;
  18703. case 1:
  18704. if (textureSheetAnimation.randomRow) {
  18705. if (autoRandomSeed) {
  18706. startRow = Math.floor(Math.random() * titleY);
  18707. }
  18708. else {
  18709. rand.seed = randomSeeds[13];
  18710. startRow = Math.floor(rand.getFloat() * titleY);
  18711. randomSeeds[13] = rand.seed;
  18712. }
  18713. }
  18714. else {
  18715. startRow = textureSheetAnimation.rowIndex;
  18716. }
  18717. break;
  18718. }
  18719. var startCol = Math.floor(startFrameCount % titleX);
  18720. ShurikenParticleData.startUVInfo = ShurikenParticleData.startUVInfo;
  18721. ShurikenParticleData.startUVInfo[0] = subU;
  18722. ShurikenParticleData.startUVInfo[1] = subV;
  18723. ShurikenParticleData.startUVInfo[2] = startCol * subU;
  18724. ShurikenParticleData.startUVInfo[3] = startRow * subV;
  18725. }
  18726. else {
  18727. ShurikenParticleData.startUVInfo = ShurikenParticleData.startUVInfo;
  18728. ShurikenParticleData.startUVInfo[0] = 1.0;
  18729. ShurikenParticleData.startUVInfo[1] = 1.0;
  18730. ShurikenParticleData.startUVInfo[2] = 0.0;
  18731. ShurikenParticleData.startUVInfo[3] = 0.0;
  18732. }
  18733. }
  18734. }
  18735. ShurikenParticleData._tempVector30 = new Vector3();
  18736. ShurikenParticleData.startColor = new Vector4();
  18737. ShurikenParticleData.startSize = new Float32Array(3);
  18738. ShurikenParticleData.startRotation = new Float32Array(3);
  18739. ShurikenParticleData.startUVInfo = new Float32Array(4);
  18740. class ShurikenParticleSystem extends GeometryElement {
  18741. constructor(owner) {
  18742. super();
  18743. this._boundingSphere = null;
  18744. this._boundingBox = null;
  18745. this._boundingBoxCorners = null;
  18746. this._owner = null;
  18747. this._ownerRender = null;
  18748. this._vertices = null;
  18749. this._floatCountPerVertex = 0;
  18750. this._startLifeTimeIndex = 0;
  18751. this._timeIndex = 0;
  18752. this._simulateUpdate = false;
  18753. this._firstActiveElement = 0;
  18754. this._firstNewElement = 0;
  18755. this._firstFreeElement = 0;
  18756. this._firstRetiredElement = 0;
  18757. this._drawCounter = 0;
  18758. this._bufferMaxParticles = 0;
  18759. this._emission = null;
  18760. this._shape = null;
  18761. this._isEmitting = false;
  18762. this._isPlaying = false;
  18763. this._isPaused = false;
  18764. this._playStartDelay = 0;
  18765. this._frameRateTime = 0;
  18766. this._emissionTime = 0;
  18767. this._totalDelayTime = 0;
  18768. this._burstsIndex = 0;
  18769. this._velocityOverLifetime = null;
  18770. this._colorOverLifetime = null;
  18771. this._sizeOverLifetime = null;
  18772. this._rotationOverLifetime = null;
  18773. this._textureSheetAnimation = null;
  18774. this._startLifetimeType = 0;
  18775. this._startLifetimeConstant = 0;
  18776. this._startLifeTimeGradient = null;
  18777. this._startLifetimeConstantMin = 0;
  18778. this._startLifetimeConstantMax = 0;
  18779. this._startLifeTimeGradientMin = null;
  18780. this._startLifeTimeGradientMax = null;
  18781. this._maxStartLifetime = 0;
  18782. this._uvLength = new Vector2();
  18783. this._vertexStride = 0;
  18784. this._indexStride = 0;
  18785. this._vertexBuffer = null;
  18786. this._indexBuffer = null;
  18787. this._bufferState = new BufferState();
  18788. this._currentTime = 0;
  18789. this._startUpdateLoopCount = 0;
  18790. this._rand = null;
  18791. this._randomSeeds = null;
  18792. this.duration = 0;
  18793. this.looping = false;
  18794. this.prewarm = false;
  18795. this.startDelayType = 0;
  18796. this.startDelay = 0;
  18797. this.startDelayMin = 0;
  18798. this.startDelayMax = 0;
  18799. this.startSpeedType = 0;
  18800. this.startSpeedConstant = 0;
  18801. this.startSpeedConstantMin = 0;
  18802. this.startSpeedConstantMax = 0;
  18803. this.threeDStartSize = false;
  18804. this.startSizeType = 0;
  18805. this.startSizeConstant = 0;
  18806. this.startSizeConstantSeparate = null;
  18807. this.startSizeConstantMin = 0;
  18808. this.startSizeConstantMax = 0;
  18809. this.startSizeConstantMinSeparate = null;
  18810. this.startSizeConstantMaxSeparate = null;
  18811. this.threeDStartRotation = false;
  18812. this.startRotationType = 0;
  18813. this.startRotationConstant = 0;
  18814. this.startRotationConstantSeparate = null;
  18815. this.startRotationConstantMin = 0;
  18816. this.startRotationConstantMax = 0;
  18817. this.startRotationConstantMinSeparate = null;
  18818. this.startRotationConstantMaxSeparate = null;
  18819. this.randomizeRotationDirection = 0;
  18820. this.startColorType = 0;
  18821. this.startColorConstant = new Vector4(1, 1, 1, 1);
  18822. this.startColorConstantMin = new Vector4(0, 0, 0, 0);
  18823. this.startColorConstantMax = new Vector4(1, 1, 1, 1);
  18824. this.gravityModifier = 0;
  18825. this.simulationSpace = 0;
  18826. this.simulationSpeed = 1.0;
  18827. this.scaleMode = 0;
  18828. this.playOnAwake = false;
  18829. this.randomSeed = null;
  18830. this.autoRandomSeed = false;
  18831. this.isPerformanceMode = false;
  18832. this._firstActiveElement = 0;
  18833. this._firstNewElement = 0;
  18834. this._firstFreeElement = 0;
  18835. this._firstRetiredElement = 0;
  18836. this._owner = owner;
  18837. this._ownerRender = owner.particleRenderer;
  18838. this._boundingBoxCorners = [];
  18839. this._boundingSphere = new BoundSphere(new Vector3(), Number.MAX_VALUE);
  18840. this._boundingBox = new BoundBox(new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE), new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE));
  18841. this._currentTime = 0;
  18842. this._isEmitting = false;
  18843. this._isPlaying = false;
  18844. this._isPaused = false;
  18845. this._burstsIndex = 0;
  18846. this._frameRateTime = 0;
  18847. this._emissionTime = 0;
  18848. this._totalDelayTime = 0;
  18849. this._simulateUpdate = false;
  18850. this._bufferMaxParticles = 1;
  18851. this.duration = 5.0;
  18852. this.looping = true;
  18853. this.prewarm = false;
  18854. this.startDelayType = 0;
  18855. this.startDelay = 0.0;
  18856. this.startDelayMin = 0.0;
  18857. this.startDelayMax = 0.0;
  18858. this._startLifetimeType = 0;
  18859. this._startLifetimeConstant = 5.0;
  18860. this._startLifeTimeGradient = new GradientDataNumber();
  18861. this._startLifetimeConstantMin = 0.0;
  18862. this._startLifetimeConstantMax = 5.0;
  18863. this._startLifeTimeGradientMin = new GradientDataNumber();
  18864. this._startLifeTimeGradientMax = new GradientDataNumber();
  18865. this._maxStartLifetime = 5.0;
  18866. this.startSpeedType = 0;
  18867. this.startSpeedConstant = 5.0;
  18868. this.startSpeedConstantMin = 0.0;
  18869. this.startSpeedConstantMax = 5.0;
  18870. this.threeDStartSize = false;
  18871. this.startSizeType = 0;
  18872. this.startSizeConstant = 1;
  18873. this.startSizeConstantSeparate = new Vector3(1, 1, 1);
  18874. this.startSizeConstantMin = 0;
  18875. this.startSizeConstantMax = 1;
  18876. this.startSizeConstantMinSeparate = new Vector3(0, 0, 0);
  18877. this.startSizeConstantMaxSeparate = new Vector3(1, 1, 1);
  18878. this.threeDStartRotation = false;
  18879. this.startRotationType = 0;
  18880. this.startRotationConstant = 0;
  18881. this.startRotationConstantSeparate = new Vector3(0, 0, 0);
  18882. this.startRotationConstantMin = 0.0;
  18883. this.startRotationConstantMax = 0.0;
  18884. this.startRotationConstantMinSeparate = new Vector3(0, 0, 0);
  18885. this.startRotationConstantMaxSeparate = new Vector3(0, 0, 0);
  18886. this.gravityModifier = 0.0;
  18887. this.simulationSpace = 1;
  18888. this.scaleMode = 0;
  18889. this.playOnAwake = true;
  18890. this._rand = new Rand(0);
  18891. this.autoRandomSeed = true;
  18892. this.randomSeed = new Uint32Array(1);
  18893. this._randomSeeds = new Uint32Array(ShurikenParticleSystem._RANDOMOFFSET.length);
  18894. this.isPerformanceMode = true;
  18895. this._emission = new Emission();
  18896. this._emission.enable = true;
  18897. }
  18898. ;
  18899. get maxParticles() {
  18900. return this._bufferMaxParticles - 1;
  18901. }
  18902. set maxParticles(value) {
  18903. var newMaxParticles = value + 1;
  18904. if (newMaxParticles !== this._bufferMaxParticles) {
  18905. this._bufferMaxParticles = newMaxParticles;
  18906. this._initBufferDatas();
  18907. }
  18908. }
  18909. get emission() {
  18910. return this._emission;
  18911. }
  18912. get aliveParticleCount() {
  18913. if (this._firstNewElement >= this._firstRetiredElement)
  18914. return this._firstNewElement - this._firstRetiredElement;
  18915. else
  18916. return this._bufferMaxParticles - this._firstRetiredElement + this._firstNewElement;
  18917. }
  18918. get emissionTime() {
  18919. return this._emissionTime > this.duration ? this.duration : this._emissionTime;
  18920. }
  18921. get shape() {
  18922. return this._shape;
  18923. }
  18924. set shape(value) {
  18925. if (this._shape !== value) {
  18926. if (value && value.enable)
  18927. this._owner._render._shaderValues.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE);
  18928. else
  18929. this._owner._render._shaderValues.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE);
  18930. this._shape = value;
  18931. }
  18932. }
  18933. get isAlive() {
  18934. if (this._isPlaying || this.aliveParticleCount > 0)
  18935. return true;
  18936. return false;
  18937. }
  18938. get isEmitting() {
  18939. return this._isEmitting;
  18940. }
  18941. get isPlaying() {
  18942. return this._isPlaying;
  18943. }
  18944. get isPaused() {
  18945. return this._isPaused;
  18946. }
  18947. get startLifetimeType() {
  18948. return this._startLifetimeType;
  18949. }
  18950. set startLifetimeType(value) {
  18951. var i, n;
  18952. switch (this.startLifetimeType) {
  18953. case 0:
  18954. this._maxStartLifetime = this.startLifetimeConstant;
  18955. break;
  18956. case 1:
  18957. this._maxStartLifetime = -Number.MAX_VALUE;
  18958. var startLifeTimeGradient = startLifeTimeGradient;
  18959. for (i = 0, n = startLifeTimeGradient.gradientCount; i < n; i++)
  18960. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradient.getValueByIndex(i));
  18961. break;
  18962. case 2:
  18963. this._maxStartLifetime = Math.max(this.startLifetimeConstantMin, this.startLifetimeConstantMax);
  18964. break;
  18965. case 3:
  18966. this._maxStartLifetime = -Number.MAX_VALUE;
  18967. var startLifeTimeGradientMin = startLifeTimeGradientMin;
  18968. for (i = 0, n = startLifeTimeGradientMin.gradientCount; i < n; i++)
  18969. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradientMin.getValueByIndex(i));
  18970. var startLifeTimeGradientMax = startLifeTimeGradientMax;
  18971. for (i = 0, n = startLifeTimeGradientMax.gradientCount; i < n; i++)
  18972. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradientMax.getValueByIndex(i));
  18973. break;
  18974. }
  18975. this._startLifetimeType = value;
  18976. }
  18977. get startLifetimeConstant() {
  18978. return this._startLifetimeConstant;
  18979. }
  18980. set startLifetimeConstant(value) {
  18981. if (this._startLifetimeType === 0)
  18982. this._maxStartLifetime = value;
  18983. this._startLifetimeConstant = value;
  18984. }
  18985. get startLifeTimeGradient() {
  18986. return this._startLifeTimeGradient;
  18987. }
  18988. set startLifeTimeGradient(value) {
  18989. if (this._startLifetimeType === 1) {
  18990. this._maxStartLifetime = -Number.MAX_VALUE;
  18991. for (var i = 0, n = value.gradientCount; i < n; i++)
  18992. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  18993. }
  18994. this._startLifeTimeGradient = value;
  18995. }
  18996. get startLifetimeConstantMin() {
  18997. return this._startLifetimeConstantMin;
  18998. }
  18999. set startLifetimeConstantMin(value) {
  19000. if (this._startLifetimeType === 2)
  19001. this._maxStartLifetime = Math.max(value, this._startLifetimeConstantMax);
  19002. this._startLifetimeConstantMin = value;
  19003. }
  19004. get startLifetimeConstantMax() {
  19005. return this._startLifetimeConstantMax;
  19006. }
  19007. set startLifetimeConstantMax(value) {
  19008. if (this._startLifetimeType === 2)
  19009. this._maxStartLifetime = Math.max(this._startLifetimeConstantMin, value);
  19010. this._startLifetimeConstantMax = value;
  19011. }
  19012. get startLifeTimeGradientMin() {
  19013. return this._startLifeTimeGradientMin;
  19014. }
  19015. set startLifeTimeGradientMin(value) {
  19016. if (this._startLifetimeType === 3) {
  19017. var i, n;
  19018. this._maxStartLifetime = -Number.MAX_VALUE;
  19019. for (i = 0, n = value.gradientCount; i < n; i++)
  19020. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  19021. for (i = 0, n = this._startLifeTimeGradientMax.gradientCount; i < n; i++)
  19022. this._maxStartLifetime = Math.max(this._maxStartLifetime, this._startLifeTimeGradientMax.getValueByIndex(i));
  19023. }
  19024. this._startLifeTimeGradientMin = value;
  19025. }
  19026. get startLifeTimeGradientMax() {
  19027. return this._startLifeTimeGradientMax;
  19028. }
  19029. set startLifeTimeGradientMax(value) {
  19030. if (this._startLifetimeType === 3) {
  19031. var i, n;
  19032. this._maxStartLifetime = -Number.MAX_VALUE;
  19033. for (i = 0, n = this._startLifeTimeGradientMin.gradientCount; i < n; i++)
  19034. this._maxStartLifetime = Math.max(this._maxStartLifetime, this._startLifeTimeGradientMin.getValueByIndex(i));
  19035. for (i = 0, n = value.gradientCount; i < n; i++)
  19036. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  19037. }
  19038. this._startLifeTimeGradientMax = value;
  19039. }
  19040. get velocityOverLifetime() {
  19041. return this._velocityOverLifetime;
  19042. }
  19043. set velocityOverLifetime(value) {
  19044. var shaDat = this._owner._render._shaderValues;
  19045. if (value) {
  19046. var velocity = value.velocity;
  19047. var velocityType = velocity.type;
  19048. if (value.enable) {
  19049. switch (velocityType) {
  19050. case 0:
  19051. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  19052. break;
  19053. case 1:
  19054. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  19055. break;
  19056. case 2:
  19057. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  19058. break;
  19059. case 3:
  19060. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  19061. break;
  19062. }
  19063. }
  19064. else {
  19065. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  19066. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  19067. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  19068. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  19069. }
  19070. switch (velocityType) {
  19071. case 0:
  19072. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST, velocity.constant);
  19073. break;
  19074. case 1:
  19075. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX, velocity.gradientX._elements);
  19076. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY, velocity.gradientY._elements);
  19077. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ, velocity.gradientZ._elements);
  19078. break;
  19079. case 2:
  19080. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST, velocity.constantMin);
  19081. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONSTMAX, velocity.constantMax);
  19082. break;
  19083. case 3:
  19084. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX, velocity.gradientXMin._elements);
  19085. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTXMAX, velocity.gradientXMax._elements);
  19086. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY, velocity.gradientYMin._elements);
  19087. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTYMAX, velocity.gradientYMax._elements);
  19088. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ, velocity.gradientZMin._elements);
  19089. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZMAX, velocity.gradientZMax._elements);
  19090. break;
  19091. }
  19092. shaDat.setInt(ShuriKenParticle3DShaderDeclaration.VOLSPACETYPE, value.space);
  19093. }
  19094. else {
  19095. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  19096. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  19097. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  19098. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  19099. }
  19100. this._velocityOverLifetime = value;
  19101. }
  19102. get colorOverLifetime() {
  19103. return this._colorOverLifetime;
  19104. }
  19105. set colorOverLifetime(value) {
  19106. var shaDat = this._owner._render._shaderValues;
  19107. if (value) {
  19108. var color = value.color;
  19109. if (value.enable) {
  19110. switch (color.type) {
  19111. case 1:
  19112. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  19113. break;
  19114. case 3:
  19115. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  19116. break;
  19117. }
  19118. }
  19119. else {
  19120. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  19121. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  19122. }
  19123. switch (color.type) {
  19124. case 1:
  19125. var gradientColor = color.gradient;
  19126. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, gradientColor._alphaElements);
  19127. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, gradientColor._rgbElements);
  19128. break;
  19129. case 3:
  19130. var minGradientColor = color.gradientMin;
  19131. var maxGradientColor = color.gradientMax;
  19132. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, minGradientColor._alphaElements);
  19133. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, minGradientColor._rgbElements);
  19134. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS, maxGradientColor._alphaElements);
  19135. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS, maxGradientColor._rgbElements);
  19136. break;
  19137. }
  19138. }
  19139. else {
  19140. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  19141. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  19142. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, gradientColor._alphaElements);
  19143. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, gradientColor._rgbElements);
  19144. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, minGradientColor._alphaElements);
  19145. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, minGradientColor._rgbElements);
  19146. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS, maxGradientColor._alphaElements);
  19147. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS, maxGradientColor._rgbElements);
  19148. }
  19149. this._colorOverLifetime = value;
  19150. }
  19151. get sizeOverLifetime() {
  19152. return this._sizeOverLifetime;
  19153. }
  19154. set sizeOverLifetime(value) {
  19155. var shaDat = this._owner._render._shaderValues;
  19156. if (value) {
  19157. var size = value.size;
  19158. var sizeSeparate = size.separateAxes;
  19159. var sizeType = size.type;
  19160. if (value.enable) {
  19161. switch (sizeType) {
  19162. case 0:
  19163. if (sizeSeparate)
  19164. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  19165. else
  19166. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  19167. break;
  19168. case 2:
  19169. if (sizeSeparate)
  19170. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  19171. else
  19172. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  19173. break;
  19174. }
  19175. }
  19176. else {
  19177. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  19178. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  19179. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  19180. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  19181. }
  19182. switch (sizeType) {
  19183. case 0:
  19184. if (sizeSeparate) {
  19185. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX, size.gradientX._elements);
  19186. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY, size.gradientY._elements);
  19187. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ, size.gradientZ._elements);
  19188. }
  19189. else {
  19190. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT, size.gradient._elements);
  19191. }
  19192. break;
  19193. case 2:
  19194. if (sizeSeparate) {
  19195. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX, size.gradientXMin._elements);
  19196. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTXMAX, size.gradientXMax._elements);
  19197. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY, size.gradientYMin._elements);
  19198. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTYMAX, size.gradientYMax._elements);
  19199. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ, size.gradientZMin._elements);
  19200. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZMAX, size.gradientZMax._elements);
  19201. }
  19202. else {
  19203. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT, size.gradientMin._elements);
  19204. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientMax, size.gradientMax._elements);
  19205. }
  19206. break;
  19207. }
  19208. }
  19209. else {
  19210. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  19211. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  19212. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  19213. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  19214. }
  19215. this._sizeOverLifetime = value;
  19216. }
  19217. get rotationOverLifetime() {
  19218. return this._rotationOverLifetime;
  19219. }
  19220. set rotationOverLifetime(value) {
  19221. var shaDat = this._owner._render._shaderValues;
  19222. if (value) {
  19223. var rotation = value.angularVelocity;
  19224. if (!rotation)
  19225. return;
  19226. var rotationSeparate = rotation.separateAxes;
  19227. var rotationType = rotation.type;
  19228. if (value.enable) {
  19229. if (rotationSeparate)
  19230. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  19231. else
  19232. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  19233. switch (rotationType) {
  19234. case 0:
  19235. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  19236. break;
  19237. case 1:
  19238. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  19239. break;
  19240. case 2:
  19241. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  19242. break;
  19243. case 3:
  19244. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  19245. break;
  19246. }
  19247. }
  19248. else {
  19249. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  19250. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  19251. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  19252. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  19253. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  19254. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  19255. }
  19256. switch (rotationType) {
  19257. case 0:
  19258. if (rotationSeparate) {
  19259. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE, rotation.constantSeparate);
  19260. }
  19261. else {
  19262. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST, rotation.constant);
  19263. }
  19264. break;
  19265. case 1:
  19266. if (rotationSeparate) {
  19267. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX, rotation.gradientX._elements);
  19268. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY, rotation.gradientY._elements);
  19269. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ, rotation.gradientZ._elements);
  19270. }
  19271. else {
  19272. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT, rotation.gradient._elements);
  19273. }
  19274. break;
  19275. case 2:
  19276. if (rotationSeparate) {
  19277. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE, rotation.constantMinSeparate);
  19278. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAXSEPRARATE, rotation.constantMaxSeparate);
  19279. }
  19280. else {
  19281. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST, rotation.constantMin);
  19282. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAX, rotation.constantMax);
  19283. }
  19284. break;
  19285. case 3:
  19286. if (rotationSeparate) {
  19287. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX, rotation.gradientXMin._elements);
  19288. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTXMAX, rotation.gradientXMax._elements);
  19289. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY, rotation.gradientYMin._elements);
  19290. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTYMAX, rotation.gradientYMax._elements);
  19291. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ, rotation.gradientZMin._elements);
  19292. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZMAX, rotation.gradientZMax._elements);
  19293. }
  19294. else {
  19295. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT, rotation.gradientMin._elements);
  19296. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTMAX, rotation.gradientMax._elements);
  19297. }
  19298. break;
  19299. }
  19300. }
  19301. else {
  19302. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  19303. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  19304. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  19305. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  19306. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  19307. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  19308. }
  19309. this._rotationOverLifetime = value;
  19310. }
  19311. get textureSheetAnimation() {
  19312. return this._textureSheetAnimation;
  19313. }
  19314. set textureSheetAnimation(value) {
  19315. var shaDat = this._owner._render._shaderValues;
  19316. if (value) {
  19317. var frameOverTime = value.frame;
  19318. var textureAniType = frameOverTime.type;
  19319. if (value.enable) {
  19320. switch (textureAniType) {
  19321. case 1:
  19322. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  19323. break;
  19324. case 3:
  19325. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  19326. break;
  19327. }
  19328. }
  19329. else {
  19330. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  19331. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  19332. }
  19333. if (textureAniType === 1 || textureAniType === 3) {
  19334. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONCYCLES, value.cycles);
  19335. var title = value.tiles;
  19336. var _uvLengthE = this._uvLength;
  19337. _uvLengthE.x = 1.0 / title.x;
  19338. _uvLengthE.y = 1.0 / title.y;
  19339. shaDat.setVector2(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONSUBUVLENGTH, this._uvLength);
  19340. }
  19341. switch (textureAniType) {
  19342. case 1:
  19343. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS, frameOverTime.frameOverTimeData._elements);
  19344. break;
  19345. case 3:
  19346. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS, frameOverTime.frameOverTimeDataMin._elements);
  19347. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTMAXUVS, frameOverTime.frameOverTimeDataMax._elements);
  19348. break;
  19349. }
  19350. }
  19351. else {
  19352. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  19353. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  19354. }
  19355. this._textureSheetAnimation = value;
  19356. }
  19357. _getVertexBuffer(index = 0) {
  19358. if (index === 0)
  19359. return this._vertexBuffer;
  19360. else
  19361. return null;
  19362. }
  19363. _getIndexBuffer() {
  19364. return this._indexBuffer;
  19365. }
  19366. _generateBoundingSphere() {
  19367. var centerE = this._boundingSphere.center;
  19368. centerE.x = 0;
  19369. centerE.y = 0;
  19370. centerE.z = 0;
  19371. this._boundingSphere.radius = Number.MAX_VALUE;
  19372. }
  19373. _generateBoundingBox() {
  19374. var particle = this._owner;
  19375. var particleRender = particle.particleRenderer;
  19376. var boundMin = this._boundingBox.min;
  19377. var boundMax = this._boundingBox.max;
  19378. var i, n;
  19379. var maxStartLifeTime;
  19380. switch (this.startLifetimeType) {
  19381. case 0:
  19382. maxStartLifeTime = this.startLifetimeConstant;
  19383. break;
  19384. case 1:
  19385. maxStartLifeTime = -Number.MAX_VALUE;
  19386. var startLifeTimeGradient = startLifeTimeGradient;
  19387. for (i = 0, n = startLifeTimeGradient.gradientCount; i < n; i++)
  19388. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradient.getValueByIndex(i));
  19389. break;
  19390. case 2:
  19391. maxStartLifeTime = Math.max(this.startLifetimeConstantMin, this.startLifetimeConstantMax);
  19392. break;
  19393. case 3:
  19394. maxStartLifeTime = -Number.MAX_VALUE;
  19395. var startLifeTimeGradientMin = startLifeTimeGradientMin;
  19396. for (i = 0, n = startLifeTimeGradientMin.gradientCount; i < n; i++)
  19397. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradientMin.getValueByIndex(i));
  19398. var startLifeTimeGradientMax = startLifeTimeGradientMax;
  19399. for (i = 0, n = startLifeTimeGradientMax.gradientCount; i < n; i++)
  19400. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradientMax.getValueByIndex(i));
  19401. break;
  19402. }
  19403. var minStartSpeed, maxStartSpeed;
  19404. switch (this.startSpeedType) {
  19405. case 0:
  19406. minStartSpeed = maxStartSpeed = this.startSpeedConstant;
  19407. break;
  19408. case 1:
  19409. break;
  19410. case 2:
  19411. minStartSpeed = this.startLifetimeConstantMin;
  19412. maxStartSpeed = this.startLifetimeConstantMax;
  19413. break;
  19414. case 3:
  19415. break;
  19416. }
  19417. var minPosition, maxPosition, minDirection, maxDirection;
  19418. if (this._shape && this._shape.enable) ;
  19419. else {
  19420. minPosition = maxPosition = Vector3._ZERO;
  19421. minDirection = Vector3._ZERO;
  19422. maxDirection = Vector3._UnitZ;
  19423. }
  19424. var startMinVelocity = new Vector3(minDirection.x * minStartSpeed, minDirection.y * minStartSpeed, minDirection.z * minStartSpeed);
  19425. var startMaxVelocity = new Vector3(maxDirection.x * maxStartSpeed, maxDirection.y * maxStartSpeed, maxDirection.z * maxStartSpeed);
  19426. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) {
  19427. var lifeMinVelocity;
  19428. var lifeMaxVelocity;
  19429. var velocity = this._velocityOverLifetime.velocity;
  19430. switch (velocity.type) {
  19431. case 0:
  19432. lifeMinVelocity = lifeMaxVelocity = velocity.constant;
  19433. break;
  19434. case 1:
  19435. lifeMinVelocity = lifeMaxVelocity = new Vector3(velocity.gradientX.getAverageValue(), velocity.gradientY.getAverageValue(), velocity.gradientZ.getAverageValue());
  19436. break;
  19437. case 2:
  19438. lifeMinVelocity = velocity.constantMin;
  19439. lifeMaxVelocity = velocity.constantMax;
  19440. break;
  19441. case 3:
  19442. lifeMinVelocity = new Vector3(velocity.gradientXMin.getAverageValue(), velocity.gradientYMin.getAverageValue(), velocity.gradientZMin.getAverageValue());
  19443. lifeMaxVelocity = new Vector3(velocity.gradientXMax.getAverageValue(), velocity.gradientYMax.getAverageValue(), velocity.gradientZMax.getAverageValue());
  19444. break;
  19445. }
  19446. }
  19447. var positionScale, velocityScale;
  19448. var transform = this._owner.transform;
  19449. var worldPosition = transform.position;
  19450. var sizeScale = ShurikenParticleSystem._tempVector39;
  19451. var renderMode = particleRender.renderMode;
  19452. switch (this.scaleMode) {
  19453. case 0:
  19454. var scale = transform.getWorldLossyScale();
  19455. positionScale = scale;
  19456. sizeScale.x = scale.x;
  19457. sizeScale.y = scale.z;
  19458. sizeScale.z = scale.y;
  19459. (renderMode === 1) && (velocityScale = scale);
  19460. break;
  19461. case 1:
  19462. var localScale = transform.localScale;
  19463. positionScale = localScale;
  19464. sizeScale.x = localScale.x;
  19465. sizeScale.y = localScale.z;
  19466. sizeScale.z = localScale.y;
  19467. (renderMode === 1) && (velocityScale = localScale);
  19468. break;
  19469. case 2:
  19470. positionScale = transform.getWorldLossyScale();
  19471. sizeScale.x = sizeScale.y = sizeScale.z = 1;
  19472. (renderMode === 1) && (velocityScale = Vector3._ONE);
  19473. break;
  19474. }
  19475. var minStratPosition, maxStratPosition;
  19476. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) ;
  19477. else {
  19478. minStratPosition = new Vector3(startMinVelocity.x * maxStartLifeTime, startMinVelocity.y * maxStartLifeTime, startMinVelocity.z * maxStartLifeTime);
  19479. maxStratPosition = new Vector3(startMaxVelocity.x * maxStartLifeTime, startMaxVelocity.y * maxStartLifeTime, startMaxVelocity.z * maxStartLifeTime);
  19480. if (this.scaleMode != 2) {
  19481. Vector3.add(minPosition, minStratPosition, boundMin);
  19482. Vector3.multiply(positionScale, boundMin, boundMin);
  19483. Vector3.add(maxPosition, maxStratPosition, boundMax);
  19484. Vector3.multiply(positionScale, boundMax, boundMax);
  19485. }
  19486. else {
  19487. Vector3.multiply(positionScale, minPosition, boundMin);
  19488. Vector3.add(boundMin, minStratPosition, boundMin);
  19489. Vector3.multiply(positionScale, maxPosition, boundMax);
  19490. Vector3.add(boundMax, maxStratPosition, boundMax);
  19491. }
  19492. }
  19493. switch (this.simulationSpace) {
  19494. case 0:
  19495. break;
  19496. case 1:
  19497. Vector3.add(boundMin, worldPosition, boundMin);
  19498. Vector3.add(boundMax, worldPosition, boundMax);
  19499. break;
  19500. }
  19501. var maxSize, maxSizeY;
  19502. switch (this.startSizeType) {
  19503. case 0:
  19504. if (this.threeDStartSize) {
  19505. var startSizeConstantSeparate = startSizeConstantSeparate;
  19506. maxSize = Math.max(startSizeConstantSeparate.x, startSizeConstantSeparate.y);
  19507. if (renderMode === 1)
  19508. maxSizeY = startSizeConstantSeparate.y;
  19509. }
  19510. else {
  19511. maxSize = this.startSizeConstant;
  19512. if (renderMode === 1)
  19513. maxSizeY = this.startSizeConstant;
  19514. }
  19515. break;
  19516. case 1:
  19517. break;
  19518. case 2:
  19519. if (this.threeDStartSize) {
  19520. var startSizeConstantMaxSeparate = startSizeConstantMaxSeparate;
  19521. maxSize = Math.max(startSizeConstantMaxSeparate.x, startSizeConstantMaxSeparate.y);
  19522. if (renderMode === 1)
  19523. maxSizeY = startSizeConstantMaxSeparate.y;
  19524. }
  19525. else {
  19526. maxSize = this.startSizeConstantMax;
  19527. if (renderMode === 1)
  19528. maxSizeY = this.startSizeConstantMax;
  19529. }
  19530. break;
  19531. case 3:
  19532. break;
  19533. }
  19534. if (this._sizeOverLifetime && this._sizeOverLifetime.enable) {
  19535. var size = this._sizeOverLifetime.size;
  19536. maxSize *= this._sizeOverLifetime.size.getMaxSizeInGradient();
  19537. }
  19538. var threeDMaxSize = ShurikenParticleSystem._tempVector30;
  19539. var rotSize, nonRotSize;
  19540. switch (renderMode) {
  19541. case 0:
  19542. rotSize = maxSize * ShurikenParticleSystem.halfKSqrtOf2;
  19543. Vector3.scale(sizeScale, maxSize, threeDMaxSize);
  19544. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  19545. Vector3.add(boundMax, threeDMaxSize, boundMax);
  19546. break;
  19547. case 1:
  19548. var maxStretchPosition = ShurikenParticleSystem._tempVector31;
  19549. var maxStretchVelocity = ShurikenParticleSystem._tempVector32;
  19550. var minStretchVelocity = ShurikenParticleSystem._tempVector33;
  19551. var minStretchPosition = ShurikenParticleSystem._tempVector34;
  19552. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) ;
  19553. else {
  19554. Vector3.multiply(velocityScale, startMaxVelocity, maxStretchVelocity);
  19555. Vector3.multiply(velocityScale, startMinVelocity, minStretchVelocity);
  19556. }
  19557. var sizeStretch = maxSizeY * particleRender.stretchedBillboardLengthScale;
  19558. var maxStretchLength = Vector3.scalarLength(maxStretchVelocity) * particleRender.stretchedBillboardSpeedScale + sizeStretch;
  19559. var minStretchLength = Vector3.scalarLength(minStretchVelocity) * particleRender.stretchedBillboardSpeedScale + sizeStretch;
  19560. var norMaxStretchVelocity = ShurikenParticleSystem._tempVector35;
  19561. var norMinStretchVelocity = ShurikenParticleSystem._tempVector36;
  19562. Vector3.normalize(maxStretchVelocity, norMaxStretchVelocity);
  19563. Vector3.scale(norMaxStretchVelocity, maxStretchLength, minStretchPosition);
  19564. Vector3.subtract(maxStratPosition, minStretchPosition, minStretchPosition);
  19565. Vector3.normalize(minStretchVelocity, norMinStretchVelocity);
  19566. Vector3.scale(norMinStretchVelocity, minStretchLength, maxStretchPosition);
  19567. Vector3.add(minStratPosition, maxStretchPosition, maxStretchPosition);
  19568. rotSize = maxSize * ShurikenParticleSystem.halfKSqrtOf2;
  19569. Vector3.scale(sizeScale, rotSize, threeDMaxSize);
  19570. var halfNorMaxStretchVelocity = ShurikenParticleSystem._tempVector37;
  19571. var halfNorMinStretchVelocity = ShurikenParticleSystem._tempVector38;
  19572. Vector3.scale(norMaxStretchVelocity, 0.5, halfNorMaxStretchVelocity);
  19573. Vector3.scale(norMinStretchVelocity, 0.5, halfNorMinStretchVelocity);
  19574. Vector3.multiply(halfNorMaxStretchVelocity, sizeScale, halfNorMaxStretchVelocity);
  19575. Vector3.multiply(halfNorMinStretchVelocity, sizeScale, halfNorMinStretchVelocity);
  19576. Vector3.add(boundMin, halfNorMinStretchVelocity, boundMin);
  19577. Vector3.min(boundMin, minStretchPosition, boundMin);
  19578. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  19579. Vector3.subtract(boundMax, halfNorMaxStretchVelocity, boundMax);
  19580. Vector3.max(boundMax, maxStretchPosition, boundMax);
  19581. Vector3.add(boundMax, threeDMaxSize, boundMax);
  19582. break;
  19583. case 2:
  19584. maxSize *= Math.cos(0.78539816339744830961566084581988);
  19585. nonRotSize = maxSize * 0.5;
  19586. threeDMaxSize.x = sizeScale.x * nonRotSize;
  19587. threeDMaxSize.y = sizeScale.z * nonRotSize;
  19588. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  19589. Vector3.add(boundMax, threeDMaxSize, boundMax);
  19590. break;
  19591. case 3:
  19592. maxSize *= Math.cos(0.78539816339744830961566084581988);
  19593. nonRotSize = maxSize * 0.5;
  19594. Vector3.scale(sizeScale, nonRotSize, threeDMaxSize);
  19595. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  19596. Vector3.add(boundMax, threeDMaxSize, boundMax);
  19597. break;
  19598. }
  19599. this._boundingBox.getCorners(this._boundingBoxCorners);
  19600. }
  19601. _updateEmission() {
  19602. if (!this.isAlive)
  19603. return;
  19604. if (this._simulateUpdate) {
  19605. this._simulateUpdate = false;
  19606. }
  19607. else {
  19608. var elapsedTime = (this._startUpdateLoopCount !== Laya.Stat.loopCount && !this._isPaused) ? this._owner._scene.timer._delta / 1000.0 : 0;
  19609. elapsedTime = Math.min(ShurikenParticleSystem._maxElapsedTime, elapsedTime * this.simulationSpeed);
  19610. this._updateParticles(elapsedTime);
  19611. }
  19612. }
  19613. _updateParticles(elapsedTime) {
  19614. if (this._ownerRender.renderMode === 4 && !this._ownerRender.mesh)
  19615. return;
  19616. this._currentTime += elapsedTime;
  19617. this._retireActiveParticles();
  19618. this._freeRetiredParticles();
  19619. this._totalDelayTime += elapsedTime;
  19620. if (this._totalDelayTime < this._playStartDelay) {
  19621. return;
  19622. }
  19623. if (this._emission.enable && this._isEmitting && !this._isPaused)
  19624. this._advanceTime(elapsedTime, this._currentTime);
  19625. }
  19626. _updateParticlesSimulationRestart(time) {
  19627. this._firstActiveElement = 0;
  19628. this._firstNewElement = 0;
  19629. this._firstFreeElement = 0;
  19630. this._firstRetiredElement = 0;
  19631. this._burstsIndex = 0;
  19632. this._frameRateTime = time;
  19633. this._emissionTime = 0;
  19634. this._totalDelayTime = 0;
  19635. this._currentTime = time;
  19636. var delayTime = time;
  19637. if (delayTime < this._playStartDelay) {
  19638. this._totalDelayTime = delayTime;
  19639. return;
  19640. }
  19641. if (this._emission.enable)
  19642. this._advanceTime(time, time);
  19643. }
  19644. _retireActiveParticles() {
  19645. const epsilon = 0.0001;
  19646. while (this._firstActiveElement != this._firstNewElement) {
  19647. var index = this._firstActiveElement * this._floatCountPerVertex * this._vertexStride;
  19648. var timeIndex = index + this._timeIndex;
  19649. var particleAge = this._currentTime - this._vertices[timeIndex];
  19650. if (particleAge + epsilon < this._vertices[index + this._startLifeTimeIndex])
  19651. break;
  19652. this._vertices[timeIndex] = this._drawCounter;
  19653. this._firstActiveElement++;
  19654. if (this._firstActiveElement >= this._bufferMaxParticles)
  19655. this._firstActiveElement = 0;
  19656. }
  19657. }
  19658. _freeRetiredParticles() {
  19659. while (this._firstRetiredElement != this._firstActiveElement) {
  19660. var age = this._drawCounter - this._vertices[this._firstRetiredElement * this._floatCountPerVertex * this._vertexStride + this._timeIndex];
  19661. if (this.isPerformanceMode)
  19662. if (age < 3)
  19663. break;
  19664. this._firstRetiredElement++;
  19665. if (this._firstRetiredElement >= this._bufferMaxParticles)
  19666. this._firstRetiredElement = 0;
  19667. }
  19668. }
  19669. _burst(fromTime, toTime) {
  19670. var totalEmitCount = 0;
  19671. var bursts = this._emission._bursts;
  19672. for (var n = bursts.length; this._burstsIndex < n; this._burstsIndex++) {
  19673. var burst = bursts[this._burstsIndex];
  19674. var burstTime = burst.time;
  19675. if (fromTime <= burstTime && burstTime < toTime) {
  19676. var emitCount;
  19677. if (this.autoRandomSeed) {
  19678. emitCount = Laya.MathUtil.lerp(burst.minCount, burst.maxCount, Math.random());
  19679. }
  19680. else {
  19681. this._rand.seed = this._randomSeeds[0];
  19682. emitCount = Laya.MathUtil.lerp(burst.minCount, burst.maxCount, this._rand.getFloat());
  19683. this._randomSeeds[0] = this._rand.seed;
  19684. }
  19685. totalEmitCount += emitCount;
  19686. }
  19687. else {
  19688. break;
  19689. }
  19690. }
  19691. return totalEmitCount;
  19692. }
  19693. _advanceTime(elapsedTime, emitTime) {
  19694. var i;
  19695. var lastEmissionTime = this._emissionTime;
  19696. this._emissionTime += elapsedTime;
  19697. var totalEmitCount = 0;
  19698. if (this._emissionTime > this.duration) {
  19699. if (this.looping) {
  19700. totalEmitCount += this._burst(lastEmissionTime, this._emissionTime);
  19701. this._emissionTime -= this.duration;
  19702. this._burstsIndex = 0;
  19703. totalEmitCount += this._burst(0, this._emissionTime);
  19704. }
  19705. else {
  19706. totalEmitCount = Math.min(this.maxParticles - this.aliveParticleCount, totalEmitCount);
  19707. for (i = 0; i < totalEmitCount; i++)
  19708. this.emit(emitTime);
  19709. this._isPlaying = false;
  19710. this.stop();
  19711. return;
  19712. }
  19713. }
  19714. else {
  19715. totalEmitCount += this._burst(lastEmissionTime, this._emissionTime);
  19716. }
  19717. totalEmitCount = Math.min(this.maxParticles - this.aliveParticleCount, totalEmitCount);
  19718. for (i = 0; i < totalEmitCount; i++)
  19719. this.emit(emitTime);
  19720. var emissionRate = this.emission.emissionRate;
  19721. if (emissionRate > 0) {
  19722. var minEmissionTime = 1 / emissionRate;
  19723. this._frameRateTime += minEmissionTime;
  19724. this._frameRateTime = this._currentTime - (this._currentTime - this._frameRateTime) % this._maxStartLifetime;
  19725. while (this._frameRateTime <= emitTime) {
  19726. if (this.emit(this._frameRateTime))
  19727. this._frameRateTime += minEmissionTime;
  19728. else
  19729. break;
  19730. }
  19731. this._frameRateTime = Math.floor(emitTime / minEmissionTime) * minEmissionTime;
  19732. }
  19733. }
  19734. _initBufferDatas() {
  19735. if (this._vertexBuffer) {
  19736. this._vertexBuffer.destroy();
  19737. this._indexBuffer.destroy();
  19738. }
  19739. var gl = Laya.LayaGL.instance;
  19740. var render = this._ownerRender;
  19741. var renderMode = render.renderMode;
  19742. if (renderMode !== -1 && this.maxParticles > 0) {
  19743. var indices, i, j, m, indexOffset, perPartOffset, vertexDeclaration;
  19744. var vbMemorySize = 0, memorySize = 0;
  19745. var mesh = render.mesh;
  19746. if (renderMode === 4) {
  19747. if (mesh) {
  19748. vertexDeclaration = VertexShurikenParticleMesh.vertexDeclaration;
  19749. this._floatCountPerVertex = vertexDeclaration.vertexStride / 4;
  19750. this._startLifeTimeIndex = 12;
  19751. this._timeIndex = 16;
  19752. this._vertexStride = mesh._vertexCount;
  19753. var totalVertexCount = this._bufferMaxParticles * this._vertexStride;
  19754. var vbCount = Math.floor(totalVertexCount / 65535) + 1;
  19755. var lastVBVertexCount = totalVertexCount % 65535;
  19756. if (vbCount > 1) {
  19757. throw new Error("ShurikenParticleSystem:the maxParticleCount multiply mesh vertexCount is large than 65535.");
  19758. }
  19759. vbMemorySize = vertexDeclaration.vertexStride * lastVBVertexCount;
  19760. this._vertexBuffer = new VertexBuffer3D(vbMemorySize, gl.DYNAMIC_DRAW);
  19761. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  19762. this._vertices = new Float32Array(this._floatCountPerVertex * lastVBVertexCount);
  19763. this._indexStride = mesh._indexBuffer.indexCount;
  19764. var indexDatas = mesh._indexBuffer.getData();
  19765. var indexCount = this._bufferMaxParticles * this._indexStride;
  19766. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indexCount, gl.STATIC_DRAW);
  19767. indices = new Uint16Array(indexCount);
  19768. memorySize = vbMemorySize + indexCount * 2;
  19769. indexOffset = 0;
  19770. for (i = 0; i < this._bufferMaxParticles; i++) {
  19771. var indexValueOffset = i * this._vertexStride;
  19772. for (j = 0, m = indexDatas.length; j < m; j++)
  19773. indices[indexOffset++] = indexValueOffset + indexDatas[j];
  19774. }
  19775. this._indexBuffer.setData(indices);
  19776. this._bufferState.bind();
  19777. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  19778. this._bufferState.applyIndexBuffer(this._indexBuffer);
  19779. this._bufferState.unBind();
  19780. }
  19781. }
  19782. else {
  19783. vertexDeclaration = VertexShurikenParticleBillboard.vertexDeclaration;
  19784. this._floatCountPerVertex = vertexDeclaration.vertexStride / 4;
  19785. this._startLifeTimeIndex = 7;
  19786. this._timeIndex = 11;
  19787. this._vertexStride = 4;
  19788. vbMemorySize = vertexDeclaration.vertexStride * this._bufferMaxParticles * this._vertexStride;
  19789. this._vertexBuffer = new VertexBuffer3D(vbMemorySize, gl.DYNAMIC_DRAW);
  19790. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  19791. this._vertices = new Float32Array(this._floatCountPerVertex * this._bufferMaxParticles * this._vertexStride);
  19792. for (i = 0; i < this._bufferMaxParticles; i++) {
  19793. perPartOffset = i * this._floatCountPerVertex * this._vertexStride;
  19794. this._vertices[perPartOffset] = -0.5;
  19795. this._vertices[perPartOffset + 1] = -0.5;
  19796. this._vertices[perPartOffset + 2] = 0;
  19797. this._vertices[perPartOffset + 3] = 1;
  19798. perPartOffset += this._floatCountPerVertex;
  19799. this._vertices[perPartOffset] = 0.5;
  19800. this._vertices[perPartOffset + 1] = -0.5;
  19801. this._vertices[perPartOffset + 2] = 1;
  19802. this._vertices[perPartOffset + 3] = 1;
  19803. perPartOffset += this._floatCountPerVertex;
  19804. this._vertices[perPartOffset] = 0.5;
  19805. this._vertices[perPartOffset + 1] = 0.5;
  19806. this._vertices[perPartOffset + 2] = 1;
  19807. this._vertices[perPartOffset + 3] = 0;
  19808. perPartOffset += this._floatCountPerVertex;
  19809. this._vertices[perPartOffset] = -0.5;
  19810. this._vertices[perPartOffset + 1] = 0.5;
  19811. this._vertices[perPartOffset + 2] = 0;
  19812. this._vertices[perPartOffset + 3] = 0;
  19813. }
  19814. this._indexStride = 6;
  19815. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._bufferMaxParticles * 6, gl.STATIC_DRAW);
  19816. indices = new Uint16Array(this._bufferMaxParticles * 6);
  19817. for (i = 0; i < this._bufferMaxParticles; i++) {
  19818. indexOffset = i * 6;
  19819. var firstVertex = i * this._vertexStride, secondVertex = firstVertex + 2;
  19820. indices[indexOffset++] = firstVertex;
  19821. indices[indexOffset++] = secondVertex;
  19822. indices[indexOffset++] = firstVertex + 1;
  19823. indices[indexOffset++] = firstVertex;
  19824. indices[indexOffset++] = firstVertex + 3;
  19825. indices[indexOffset++] = secondVertex;
  19826. }
  19827. this._indexBuffer.setData(indices);
  19828. memorySize = vbMemorySize + this._bufferMaxParticles * 6 * 2;
  19829. this._bufferState.bind();
  19830. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  19831. this._bufferState.applyIndexBuffer(this._indexBuffer);
  19832. this._bufferState.unBind();
  19833. }
  19834. Laya.Resource._addMemory(memorySize, memorySize);
  19835. }
  19836. }
  19837. destroy() {
  19838. super.destroy();
  19839. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer.indexCount * 2;
  19840. Laya.Resource._addMemory(-memorySize, -memorySize);
  19841. this._bufferState.destroy();
  19842. this._vertexBuffer.destroy();
  19843. this._indexBuffer.destroy();
  19844. this._emission.destroy();
  19845. this._bufferState = null;
  19846. this._vertexBuffer = null;
  19847. this._indexBuffer = null;
  19848. this._owner = null;
  19849. this._vertices = null;
  19850. this._indexBuffer = null;
  19851. this._emission = null;
  19852. this._shape = null;
  19853. this.startLifeTimeGradient = null;
  19854. this.startLifeTimeGradientMin = null;
  19855. this.startLifeTimeGradientMax = null;
  19856. this.startSizeConstantSeparate = null;
  19857. this.startSizeConstantMinSeparate = null;
  19858. this.startSizeConstantMaxSeparate = null;
  19859. this.startRotationConstantSeparate = null;
  19860. this.startRotationConstantMinSeparate = null;
  19861. this.startRotationConstantMaxSeparate = null;
  19862. this.startColorConstant = null;
  19863. this.startColorConstantMin = null;
  19864. this.startColorConstantMax = null;
  19865. this._velocityOverLifetime = null;
  19866. this._colorOverLifetime = null;
  19867. this._sizeOverLifetime = null;
  19868. this._rotationOverLifetime = null;
  19869. this._textureSheetAnimation = null;
  19870. }
  19871. emit(time) {
  19872. var position = ShurikenParticleSystem._tempPosition;
  19873. var direction = ShurikenParticleSystem._tempDirection;
  19874. if (this._shape && this._shape.enable) {
  19875. if (this.autoRandomSeed)
  19876. this._shape.generatePositionAndDirection(position, direction);
  19877. else
  19878. this._shape.generatePositionAndDirection(position, direction, this._rand, this._randomSeeds);
  19879. }
  19880. else {
  19881. position.x = position.y = position.z = 0;
  19882. direction.x = direction.y = 0;
  19883. direction.z = 1;
  19884. }
  19885. return this.addParticle(position, direction, time);
  19886. }
  19887. addParticle(position, direction, time) {
  19888. Vector3.normalize(direction, direction);
  19889. var nextFreeParticle = this._firstFreeElement + 1;
  19890. if (nextFreeParticle >= this._bufferMaxParticles)
  19891. nextFreeParticle = 0;
  19892. if (nextFreeParticle === this._firstRetiredElement)
  19893. return false;
  19894. var transform = this._owner.transform;
  19895. ShurikenParticleData.create(this, this._ownerRender, transform);
  19896. var particleAge = this._currentTime - time;
  19897. if (particleAge >= ShurikenParticleData.startLifeTime)
  19898. return true;
  19899. var pos, rot;
  19900. if (this.simulationSpace == 0) {
  19901. pos = transform.position;
  19902. rot = transform.rotation;
  19903. }
  19904. var startSpeed;
  19905. switch (this.startSpeedType) {
  19906. case 0:
  19907. startSpeed = this.startSpeedConstant;
  19908. break;
  19909. case 2:
  19910. if (this.autoRandomSeed) {
  19911. startSpeed = Laya.MathUtil.lerp(this.startSpeedConstantMin, this.startSpeedConstantMax, Math.random());
  19912. }
  19913. else {
  19914. this._rand.seed = this._randomSeeds[8];
  19915. startSpeed = Laya.MathUtil.lerp(this.startSpeedConstantMin, this.startSpeedConstantMax, this._rand.getFloat());
  19916. this._randomSeeds[8] = this._rand.seed;
  19917. }
  19918. break;
  19919. }
  19920. var randomVelocityX, randomVelocityY, randomVelocityZ, randomColor, randomSize, randomRotation, randomTextureAnimation;
  19921. var needRandomVelocity = this._velocityOverLifetime && this._velocityOverLifetime.enable;
  19922. if (needRandomVelocity) {
  19923. var velocityType = this._velocityOverLifetime.velocity.type;
  19924. if (velocityType === 2 || velocityType === 3) {
  19925. if (this.autoRandomSeed) {
  19926. randomVelocityX = Math.random();
  19927. randomVelocityY = Math.random();
  19928. randomVelocityZ = Math.random();
  19929. }
  19930. else {
  19931. this._rand.seed = this._randomSeeds[9];
  19932. randomVelocityX = this._rand.getFloat();
  19933. randomVelocityY = this._rand.getFloat();
  19934. randomVelocityZ = this._rand.getFloat();
  19935. this._randomSeeds[9] = this._rand.seed;
  19936. }
  19937. }
  19938. else {
  19939. needRandomVelocity = false;
  19940. }
  19941. }
  19942. else {
  19943. needRandomVelocity = false;
  19944. }
  19945. var needRandomColor = this._colorOverLifetime && this._colorOverLifetime.enable;
  19946. if (needRandomColor) {
  19947. var colorType = this._colorOverLifetime.color.type;
  19948. if (colorType === 3) {
  19949. if (this.autoRandomSeed) {
  19950. randomColor = Math.random();
  19951. }
  19952. else {
  19953. this._rand.seed = this._randomSeeds[10];
  19954. randomColor = this._rand.getFloat();
  19955. this._randomSeeds[10] = this._rand.seed;
  19956. }
  19957. }
  19958. else {
  19959. needRandomColor = false;
  19960. }
  19961. }
  19962. else {
  19963. needRandomColor = false;
  19964. }
  19965. var needRandomSize = this._sizeOverLifetime && this._sizeOverLifetime.enable;
  19966. if (needRandomSize) {
  19967. var sizeType = this._sizeOverLifetime.size.type;
  19968. if (sizeType === 3) {
  19969. if (this.autoRandomSeed) {
  19970. randomSize = Math.random();
  19971. }
  19972. else {
  19973. this._rand.seed = this._randomSeeds[11];
  19974. randomSize = this._rand.getFloat();
  19975. this._randomSeeds[11] = this._rand.seed;
  19976. }
  19977. }
  19978. else {
  19979. needRandomSize = false;
  19980. }
  19981. }
  19982. else {
  19983. needRandomSize = false;
  19984. }
  19985. var needRandomRotation = this._rotationOverLifetime && this._rotationOverLifetime.enable;
  19986. if (needRandomRotation) {
  19987. var rotationType = this._rotationOverLifetime.angularVelocity.type;
  19988. if (rotationType === 2 || rotationType === 3) {
  19989. if (this.autoRandomSeed) {
  19990. randomRotation = Math.random();
  19991. }
  19992. else {
  19993. this._rand.seed = this._randomSeeds[12];
  19994. randomRotation = this._rand.getFloat();
  19995. this._randomSeeds[12] = this._rand.seed;
  19996. }
  19997. }
  19998. else {
  19999. needRandomRotation = false;
  20000. }
  20001. }
  20002. else {
  20003. needRandomRotation = false;
  20004. }
  20005. var needRandomTextureAnimation = this._textureSheetAnimation && this._textureSheetAnimation.enable;
  20006. if (needRandomTextureAnimation) {
  20007. var textureAnimationType = this._textureSheetAnimation.frame.type;
  20008. if (textureAnimationType === 3) {
  20009. if (this.autoRandomSeed) {
  20010. randomTextureAnimation = Math.random();
  20011. }
  20012. else {
  20013. this._rand.seed = this._randomSeeds[15];
  20014. randomTextureAnimation = this._rand.getFloat();
  20015. this._randomSeeds[15] = this._rand.seed;
  20016. }
  20017. }
  20018. else {
  20019. needRandomTextureAnimation = false;
  20020. }
  20021. }
  20022. else {
  20023. needRandomTextureAnimation = false;
  20024. }
  20025. var startIndex = this._firstFreeElement * this._floatCountPerVertex * this._vertexStride;
  20026. var subU = ShurikenParticleData.startUVInfo[0];
  20027. var subV = ShurikenParticleData.startUVInfo[1];
  20028. var startU = ShurikenParticleData.startUVInfo[2];
  20029. var startV = ShurikenParticleData.startUVInfo[3];
  20030. var meshVertices, meshVertexStride, meshPosOffset, meshCorOffset, meshUVOffset, meshVertexIndex;
  20031. var render = this._ownerRender;
  20032. if (render.renderMode === 4) {
  20033. var meshVB = render.mesh._vertexBuffer;
  20034. meshVertices = meshVB.getFloat32Data();
  20035. var meshVertexDeclaration = meshVB.vertexDeclaration;
  20036. meshPosOffset = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  20037. var colorElement = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  20038. meshCorOffset = colorElement ? colorElement._offset / 4 : -1;
  20039. var uvElement = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  20040. meshUVOffset = uvElement ? uvElement._offset / 4 : -1;
  20041. meshVertexStride = meshVertexDeclaration.vertexStride / 4;
  20042. meshVertexIndex = 0;
  20043. }
  20044. else {
  20045. this._vertices[startIndex + 2] = startU;
  20046. this._vertices[startIndex + 3] = startV + subV;
  20047. var secondOffset = startIndex + this._floatCountPerVertex;
  20048. this._vertices[secondOffset + 2] = startU + subU;
  20049. this._vertices[secondOffset + 3] = startV + subV;
  20050. var thirdOffset = secondOffset + this._floatCountPerVertex;
  20051. this._vertices[thirdOffset + 2] = startU + subU;
  20052. this._vertices[thirdOffset + 3] = startV;
  20053. var fourthOffset = thirdOffset + this._floatCountPerVertex;
  20054. this._vertices[fourthOffset + 2] = startU;
  20055. this._vertices[fourthOffset + 3] = startV;
  20056. }
  20057. for (var i = startIndex, n = startIndex + this._floatCountPerVertex * this._vertexStride; i < n; i += this._floatCountPerVertex) {
  20058. var offset;
  20059. if (render.renderMode === 4) {
  20060. offset = i;
  20061. var vertexOffset = meshVertexStride * (meshVertexIndex++);
  20062. var meshOffset = vertexOffset + meshPosOffset;
  20063. this._vertices[offset++] = meshVertices[meshOffset++];
  20064. this._vertices[offset++] = meshVertices[meshOffset++];
  20065. this._vertices[offset++] = meshVertices[meshOffset];
  20066. if (meshCorOffset === -1) {
  20067. this._vertices[offset++] = 1.0;
  20068. this._vertices[offset++] = 1.0;
  20069. this._vertices[offset++] = 1.0;
  20070. this._vertices[offset++] = 1.0;
  20071. }
  20072. else {
  20073. meshOffset = vertexOffset + meshCorOffset;
  20074. this._vertices[offset++] = meshVertices[meshOffset++];
  20075. this._vertices[offset++] = meshVertices[meshOffset++];
  20076. this._vertices[offset++] = meshVertices[meshOffset++];
  20077. this._vertices[offset++] = meshVertices[meshOffset];
  20078. }
  20079. if (meshUVOffset === -1) {
  20080. this._vertices[offset++] = 0.0;
  20081. this._vertices[offset++] = 0.0;
  20082. }
  20083. else {
  20084. meshOffset = vertexOffset + meshUVOffset;
  20085. this._vertices[offset++] = startU + meshVertices[meshOffset++] * subU;
  20086. this._vertices[offset++] = startV + meshVertices[meshOffset] * subV;
  20087. }
  20088. }
  20089. else {
  20090. offset = i + 4;
  20091. }
  20092. this._vertices[offset++] = position.x;
  20093. this._vertices[offset++] = position.y;
  20094. this._vertices[offset++] = position.z;
  20095. this._vertices[offset++] = ShurikenParticleData.startLifeTime;
  20096. this._vertices[offset++] = direction.x;
  20097. this._vertices[offset++] = direction.y;
  20098. this._vertices[offset++] = direction.z;
  20099. this._vertices[offset++] = time;
  20100. this._vertices[offset++] = ShurikenParticleData.startColor.x;
  20101. this._vertices[offset++] = ShurikenParticleData.startColor.y;
  20102. this._vertices[offset++] = ShurikenParticleData.startColor.z;
  20103. this._vertices[offset++] = ShurikenParticleData.startColor.w;
  20104. this._vertices[offset++] = ShurikenParticleData.startSize[0];
  20105. this._vertices[offset++] = ShurikenParticleData.startSize[1];
  20106. this._vertices[offset++] = ShurikenParticleData.startSize[2];
  20107. this._vertices[offset++] = ShurikenParticleData.startRotation[0];
  20108. this._vertices[offset++] = ShurikenParticleData.startRotation[1];
  20109. this._vertices[offset++] = ShurikenParticleData.startRotation[2];
  20110. this._vertices[offset++] = startSpeed;
  20111. needRandomColor && (this._vertices[offset + 1] = randomColor);
  20112. needRandomSize && (this._vertices[offset + 2] = randomSize);
  20113. needRandomRotation && (this._vertices[offset + 3] = randomRotation);
  20114. needRandomTextureAnimation && (this._vertices[offset + 4] = randomTextureAnimation);
  20115. if (needRandomVelocity) {
  20116. this._vertices[offset + 5] = randomVelocityX;
  20117. this._vertices[offset + 6] = randomVelocityY;
  20118. this._vertices[offset + 7] = randomVelocityZ;
  20119. }
  20120. switch (this.simulationSpace) {
  20121. case 0:
  20122. offset += 8;
  20123. this._vertices[offset++] = pos.x;
  20124. this._vertices[offset++] = pos.y;
  20125. this._vertices[offset++] = pos.z;
  20126. this._vertices[offset++] = rot.x;
  20127. this._vertices[offset++] = rot.y;
  20128. this._vertices[offset++] = rot.z;
  20129. this._vertices[offset++] = rot.w;
  20130. break;
  20131. case 1:
  20132. break;
  20133. default:
  20134. throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid.");
  20135. }
  20136. }
  20137. this._firstFreeElement = nextFreeParticle;
  20138. return true;
  20139. }
  20140. addNewParticlesToVertexBuffer() {
  20141. var start;
  20142. var byteStride = this._vertexStride * this._floatCountPerVertex * 4;
  20143. if (this._firstNewElement < this._firstFreeElement) {
  20144. start = this._firstNewElement * byteStride;
  20145. this._vertexBuffer.setData(this._vertices.buffer, start, start, (this._firstFreeElement - this._firstNewElement) * byteStride);
  20146. }
  20147. else {
  20148. start = this._firstNewElement * byteStride;
  20149. this._vertexBuffer.setData(this._vertices.buffer, start, start, (this._bufferMaxParticles - this._firstNewElement) * byteStride);
  20150. if (this._firstFreeElement > 0) {
  20151. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, this._firstFreeElement * byteStride);
  20152. }
  20153. }
  20154. this._firstNewElement = this._firstFreeElement;
  20155. }
  20156. _getType() {
  20157. return ShurikenParticleSystem._type;
  20158. }
  20159. _prepareRender(state) {
  20160. this._updateEmission();
  20161. if (this._firstNewElement != this._firstFreeElement)
  20162. this.addNewParticlesToVertexBuffer();
  20163. this._drawCounter++;
  20164. if (this._firstActiveElement != this._firstFreeElement)
  20165. return true;
  20166. else
  20167. return false;
  20168. }
  20169. _render(state) {
  20170. this._bufferState.bind();
  20171. var indexCount;
  20172. var gl = Laya.LayaGL.instance;
  20173. if (this._firstActiveElement < this._firstFreeElement) {
  20174. indexCount = (this._firstFreeElement - this._firstActiveElement) * this._indexStride;
  20175. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 2 * this._firstActiveElement * this._indexStride);
  20176. Laya.Stat.trianglesFaces += indexCount / 3;
  20177. Laya.Stat.renderBatches++;
  20178. }
  20179. else {
  20180. indexCount = (this._bufferMaxParticles - this._firstActiveElement) * this._indexStride;
  20181. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 2 * this._firstActiveElement * this._indexStride);
  20182. Laya.Stat.trianglesFaces += indexCount / 3;
  20183. Laya.Stat.renderBatches++;
  20184. if (this._firstFreeElement > 0) {
  20185. indexCount = this._firstFreeElement * this._indexStride;
  20186. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  20187. Laya.Stat.trianglesFaces += indexCount / 3;
  20188. Laya.Stat.renderBatches++;
  20189. }
  20190. }
  20191. }
  20192. play() {
  20193. this._burstsIndex = 0;
  20194. this._isEmitting = true;
  20195. this._isPlaying = true;
  20196. this._isPaused = false;
  20197. this._emissionTime = 0;
  20198. this._totalDelayTime = 0;
  20199. if (!this.autoRandomSeed) {
  20200. for (var i = 0, n = this._randomSeeds.length; i < n; i++)
  20201. this._randomSeeds[i] = this.randomSeed[0] + ShurikenParticleSystem._RANDOMOFFSET[i];
  20202. }
  20203. switch (this.startDelayType) {
  20204. case 0:
  20205. this._playStartDelay = this.startDelay;
  20206. break;
  20207. case 1:
  20208. if (this.autoRandomSeed) {
  20209. this._playStartDelay = Laya.MathUtil.lerp(this.startDelayMin, this.startDelayMax, Math.random());
  20210. }
  20211. else {
  20212. this._rand.seed = this._randomSeeds[2];
  20213. this._playStartDelay = Laya.MathUtil.lerp(this.startDelayMin, this.startDelayMax, this._rand.getFloat());
  20214. this._randomSeeds[2] = this._rand.seed;
  20215. }
  20216. break;
  20217. default:
  20218. throw new Error("Utils3D: startDelayType is invalid.");
  20219. }
  20220. this._frameRateTime = this._currentTime + this._playStartDelay;
  20221. this._startUpdateLoopCount = Laya.Stat.loopCount;
  20222. }
  20223. pause() {
  20224. this._isPaused = true;
  20225. }
  20226. simulate(time, restart = true) {
  20227. this._simulateUpdate = true;
  20228. if (restart) {
  20229. this._updateParticlesSimulationRestart(time);
  20230. }
  20231. else {
  20232. this._isPaused = false;
  20233. this._updateParticles(time);
  20234. }
  20235. this.pause();
  20236. }
  20237. stop() {
  20238. this._burstsIndex = 0;
  20239. this._isEmitting = false;
  20240. this._emissionTime = 0;
  20241. }
  20242. cloneTo(destObject) {
  20243. var dest = destObject;
  20244. dest.duration = this.duration;
  20245. dest.looping = this.looping;
  20246. dest.prewarm = this.prewarm;
  20247. dest.startDelayType = this.startDelayType;
  20248. dest.startDelay = this.startDelay;
  20249. dest.startDelayMin = this.startDelayMin;
  20250. dest.startDelayMax = this.startDelayMax;
  20251. dest._maxStartLifetime = this._maxStartLifetime;
  20252. dest.startLifetimeType = this.startLifetimeType;
  20253. dest.startLifetimeConstant = this.startLifetimeConstant;
  20254. this.startLifeTimeGradient.cloneTo(dest.startLifeTimeGradient);
  20255. dest.startLifetimeConstantMin = this.startLifetimeConstantMin;
  20256. dest.startLifetimeConstantMax = this.startLifetimeConstantMax;
  20257. this.startLifeTimeGradientMin.cloneTo(dest.startLifeTimeGradientMin);
  20258. this.startLifeTimeGradientMax.cloneTo(dest.startLifeTimeGradientMax);
  20259. dest.startSpeedType = this.startSpeedType;
  20260. dest.startSpeedConstant = this.startSpeedConstant;
  20261. dest.startSpeedConstantMin = this.startSpeedConstantMin;
  20262. dest.startSpeedConstantMax = this.startSpeedConstantMax;
  20263. dest.threeDStartSize = this.threeDStartSize;
  20264. dest.startSizeType = this.startSizeType;
  20265. dest.startSizeConstant = this.startSizeConstant;
  20266. this.startSizeConstantSeparate.cloneTo(dest.startSizeConstantSeparate);
  20267. dest.startSizeConstantMin = this.startSizeConstantMin;
  20268. dest.startSizeConstantMax = this.startSizeConstantMax;
  20269. this.startSizeConstantMinSeparate.cloneTo(dest.startSizeConstantMinSeparate);
  20270. this.startSizeConstantMaxSeparate.cloneTo(dest.startSizeConstantMaxSeparate);
  20271. dest.threeDStartRotation = this.threeDStartRotation;
  20272. dest.startRotationType = this.startRotationType;
  20273. dest.startRotationConstant = this.startRotationConstant;
  20274. this.startRotationConstantSeparate.cloneTo(dest.startRotationConstantSeparate);
  20275. dest.startRotationConstantMin = this.startRotationConstantMin;
  20276. dest.startRotationConstantMax = this.startRotationConstantMax;
  20277. this.startRotationConstantMinSeparate.cloneTo(dest.startRotationConstantMinSeparate);
  20278. this.startRotationConstantMaxSeparate.cloneTo(dest.startRotationConstantMaxSeparate);
  20279. dest.randomizeRotationDirection = this.randomizeRotationDirection;
  20280. dest.startColorType = this.startColorType;
  20281. this.startColorConstant.cloneTo(dest.startColorConstant);
  20282. this.startColorConstantMin.cloneTo(dest.startColorConstantMin);
  20283. this.startColorConstantMax.cloneTo(dest.startColorConstantMax);
  20284. dest.gravityModifier = this.gravityModifier;
  20285. dest.simulationSpace = this.simulationSpace;
  20286. dest.scaleMode = this.scaleMode;
  20287. dest.playOnAwake = this.playOnAwake;
  20288. dest.autoRandomSeed = this.autoRandomSeed;
  20289. dest.randomSeed[0] = this.randomSeed[0];
  20290. dest.maxParticles = this.maxParticles;
  20291. (this._emission) && (dest._emission = this._emission.clone());
  20292. (this.shape) && (dest.shape = this.shape.clone());
  20293. (this.velocityOverLifetime) && (dest.velocityOverLifetime = this.velocityOverLifetime.clone());
  20294. (this.colorOverLifetime) && (dest.colorOverLifetime = this.colorOverLifetime.clone());
  20295. (this.sizeOverLifetime) && (dest.sizeOverLifetime = this.sizeOverLifetime.clone());
  20296. (this.rotationOverLifetime) && (dest.rotationOverLifetime = this.rotationOverLifetime.clone());
  20297. (this.textureSheetAnimation) && (dest.textureSheetAnimation = this.textureSheetAnimation.clone());
  20298. dest.isPerformanceMode = this.isPerformanceMode;
  20299. dest._isEmitting = this._isEmitting;
  20300. dest._isPlaying = this._isPlaying;
  20301. dest._isPaused = this._isPaused;
  20302. dest._playStartDelay = this._playStartDelay;
  20303. dest._frameRateTime = this._frameRateTime;
  20304. dest._emissionTime = this._emissionTime;
  20305. dest._totalDelayTime = this._totalDelayTime;
  20306. dest._burstsIndex = this._burstsIndex;
  20307. }
  20308. clone() {
  20309. var dest = new ShurikenParticleSystem(null);
  20310. this.cloneTo(dest);
  20311. return dest;
  20312. }
  20313. }
  20314. ShurikenParticleSystem._RANDOMOFFSET = new Uint32Array([0x23571a3e, 0xc34f56fe, 0x13371337, 0x12460f3b, 0x6aed452e, 0xdec4aea1, 0x96aa4de3, 0x8d2c8431, 0xf3857f6f, 0xe0fbd834, 0x13740583, 0x591bc05c, 0x40eb95e4, 0xbc524e5f, 0xaf502044, 0xa614b381, 0x1034e524, 0xfc524e5f]);
  20315. ShurikenParticleSystem.halfKSqrtOf2 = 1.42 * 0.5;
  20316. ShurikenParticleSystem._maxElapsedTime = 1.0 / 3.0;
  20317. ShurikenParticleSystem._tempVector30 = new Vector3();
  20318. ShurikenParticleSystem._tempVector31 = new Vector3();
  20319. ShurikenParticleSystem._tempVector32 = new Vector3();
  20320. ShurikenParticleSystem._tempVector33 = new Vector3();
  20321. ShurikenParticleSystem._tempVector34 = new Vector3();
  20322. ShurikenParticleSystem._tempVector35 = new Vector3();
  20323. ShurikenParticleSystem._tempVector36 = new Vector3();
  20324. ShurikenParticleSystem._tempVector37 = new Vector3();
  20325. ShurikenParticleSystem._tempVector38 = new Vector3();
  20326. ShurikenParticleSystem._tempVector39 = new Vector3();
  20327. ShurikenParticleSystem._tempPosition = new Vector3();
  20328. ShurikenParticleSystem._tempDirection = new Vector3();
  20329. ShurikenParticleSystem._type = GeometryElement._typeCounter++;
  20330. class ShuriKenParticle3D extends RenderableSprite3D {
  20331. static __init__() {
  20332. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD = Shader3D.getDefineByName("SPHERHBILLBOARD");
  20333. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD = Shader3D.getDefineByName("STRETCHEDBILLBOARD");
  20334. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD = Shader3D.getDefineByName("HORIZONTALBILLBOARD");
  20335. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD = Shader3D.getDefineByName("VERTICALBILLBOARD");
  20336. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME = Shader3D.getDefineByName("COLOROVERLIFETIME");
  20337. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME = Shader3D.getDefineByName("RANDOMCOLOROVERLIFETIME");
  20338. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT = Shader3D.getDefineByName("VELOCITYOVERLIFETIMECONSTANT");
  20339. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE = Shader3D.getDefineByName("VELOCITYOVERLIFETIMECURVE");
  20340. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT = Shader3D.getDefineByName("VELOCITYOVERLIFETIMERANDOMCONSTANT");
  20341. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE = Shader3D.getDefineByName("VELOCITYOVERLIFETIMERANDOMCURVE");
  20342. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE = Shader3D.getDefineByName("TEXTURESHEETANIMATIONCURVE");
  20343. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE = Shader3D.getDefineByName("TEXTURESHEETANIMATIONRANDOMCURVE");
  20344. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME = Shader3D.getDefineByName("ROTATIONOVERLIFETIME");
  20345. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE = Shader3D.getDefineByName("ROTATIONOVERLIFETIMESEPERATE");
  20346. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT = Shader3D.getDefineByName("ROTATIONOVERLIFETIMECONSTANT");
  20347. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE = Shader3D.getDefineByName("ROTATIONOVERLIFETIMECURVE");
  20348. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS = Shader3D.getDefineByName("ROTATIONOVERLIFETIMERANDOMCONSTANTS");
  20349. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES = Shader3D.getDefineByName("ROTATIONOVERLIFETIMERANDOMCURVES");
  20350. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE = Shader3D.getDefineByName("SIZEOVERLIFETIMECURVE");
  20351. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE = Shader3D.getDefineByName("SIZEOVERLIFETIMECURVESEPERATE");
  20352. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES = Shader3D.getDefineByName("SIZEOVERLIFETIMERANDOMCURVES");
  20353. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE = Shader3D.getDefineByName("SIZEOVERLIFETIMERANDOMCURVESSEPERATE");
  20354. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH = Shader3D.getDefineByName("RENDERMODE_MESH");
  20355. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE = Shader3D.getDefineByName("SHAPE");
  20356. }
  20357. get particleSystem() {
  20358. return this._particleSystem;
  20359. }
  20360. get particleRenderer() {
  20361. return this._render;
  20362. }
  20363. constructor() {
  20364. super(null);
  20365. this._render = new ShurikenParticleRenderer(this);
  20366. this._particleSystem = new ShurikenParticleSystem(this);
  20367. var elements = this._render._renderElements;
  20368. var element = elements[0] = new RenderElement();
  20369. element.setTransform(this._transform);
  20370. element.render = this._render;
  20371. element.setGeometry(this._particleSystem);
  20372. element.material = ShurikenParticleMaterial.defaultMaterial;
  20373. }
  20374. _parseModule(module, moduleData) {
  20375. for (var t in moduleData) {
  20376. switch (t) {
  20377. case "bases":
  20378. var bases = moduleData.bases;
  20379. for (var k in bases)
  20380. module[k] = bases[k];
  20381. break;
  20382. case "vector2s":
  20383. var vector2s = moduleData.vector2s;
  20384. for (var k in vector2s) {
  20385. var vec2 = module[k];
  20386. var vec2Data = vector2s[k];
  20387. vec2.setValue(vec2Data[0], vec2Data[1]);
  20388. module[k] = vec2;
  20389. }
  20390. break;
  20391. case "vector3s":
  20392. var vector3s = moduleData.vector3s;
  20393. for (var k in vector3s) {
  20394. var vec3 = module[k];
  20395. var vec3Data = vector3s[k];
  20396. vec3.setValue(vec3Data[0], vec3Data[1], vec3Data[2]);
  20397. module[k] = vec3;
  20398. }
  20399. break;
  20400. case "vector4s":
  20401. var vector4s = moduleData.vector4s;
  20402. for (var k in vector4s) {
  20403. var vec4 = module[k];
  20404. var vec4Data = vector4s[k];
  20405. vec4.setValue(vec4Data[0], vec4Data[1], vec4Data[2], vec4Data[3]);
  20406. module[k] = vec4;
  20407. }
  20408. break;
  20409. case "gradientDataNumbers":
  20410. var gradientDataNumbers = moduleData.gradientDataNumbers;
  20411. for (var k in gradientDataNumbers) {
  20412. var gradientNumber = module[k];
  20413. var gradientNumberData = moduleData[k];
  20414. for (var i = 0, n = gradientNumberData.length; i < n; i++) {
  20415. var valueData = gradientNumberData[i];
  20416. gradientNumber.add(valueData.key, valueData.value);
  20417. }
  20418. module[k] = gradientNumber;
  20419. }
  20420. break;
  20421. case "resources":
  20422. var resources = moduleData.resources;
  20423. for (var k in resources)
  20424. module[k] = Laya.Loader.getRes(resources[k]);
  20425. break;
  20426. case "bursts":
  20427. var burstsData = moduleData.bursts;
  20428. for (var i = 0, n = burstsData.length; i < n; i++) {
  20429. var brust = burstsData[i];
  20430. module.addBurst(new Burst(brust.time, brust.min, brust.max));
  20431. }
  20432. break;
  20433. case "randomSeed":
  20434. module.randomSeed[0] = moduleData.randomSeed;
  20435. break;
  20436. case "shapeType":
  20437. case "type":
  20438. case "color":
  20439. case "size":
  20440. case "frame":
  20441. case "startFrame":
  20442. case "angularVelocity":
  20443. case "velocity":
  20444. break;
  20445. default:
  20446. throw "ShurikenParticle3D:unknown type.";
  20447. }
  20448. }
  20449. }
  20450. _parse(data, spriteMap) {
  20451. super._parse(data, spriteMap);
  20452. if (data.main) {
  20453. var particleSystem = this.particleSystem;
  20454. var particleRender = this.particleRenderer;
  20455. this._parseModule(particleRender, data.renderer);
  20456. this._parseModule(particleSystem, data.main);
  20457. this._parseModule(particleSystem.emission, data.emission);
  20458. var shapeData = data.shape;
  20459. if (shapeData) {
  20460. var shape;
  20461. switch (shapeData.shapeType) {
  20462. case 0:
  20463. shape = new SphereShape();
  20464. break;
  20465. case 1:
  20466. shape = new HemisphereShape();
  20467. break;
  20468. case 2:
  20469. shape = new ConeShape();
  20470. break;
  20471. case 3:
  20472. shape = new BoxShape();
  20473. break;
  20474. case 7:
  20475. shape = new CircleShape();
  20476. break;
  20477. default:
  20478. throw "ShuriKenParticle3D:unknown shape type.";
  20479. }
  20480. this._parseModule(shape, shapeData);
  20481. particleSystem.shape = shape;
  20482. }
  20483. var velocityOverLifetimeData = data.velocityOverLifetime;
  20484. if (velocityOverLifetimeData) {
  20485. var velocityData = velocityOverLifetimeData.velocity;
  20486. var velocity;
  20487. switch (velocityData.type) {
  20488. case 0:
  20489. var constantData = velocityData.constant;
  20490. velocity = GradientVelocity.createByConstant(constantData ? new Vector3(constantData[0], constantData[1], constantData[2]) : new Vector3(0, 0, 0));
  20491. break;
  20492. case 1:
  20493. velocity = GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX), this._initParticleVelocity(velocityData.gradientY), this._initParticleVelocity(velocityData.gradientZ));
  20494. break;
  20495. case 2:
  20496. var constantMinData = velocityData.constantMin;
  20497. var constantMaxData = velocityData.constantMax;
  20498. velocity = GradientVelocity.createByRandomTwoConstant(constantMinData ? new Vector3(constantMinData[0], constantMinData[1], constantMinData[2]) : new Vector3(0, 0, 0), constantMaxData ? new Vector3(constantMaxData[0], constantMaxData[1], constantMaxData[2]) : new Vector3(0, 0, 0));
  20499. break;
  20500. case 3:
  20501. velocity = GradientVelocity.createByRandomTwoGradient(this._initParticleVelocity(velocityData.gradientXMin), this._initParticleVelocity(velocityData.gradientXMax), this._initParticleVelocity(velocityData.gradientYMin), this._initParticleVelocity(velocityData.gradientYMax), this._initParticleVelocity(velocityData.gradientZMin), this._initParticleVelocity(velocityData.gradientZMax));
  20502. break;
  20503. }
  20504. var velocityOverLifetime = new VelocityOverLifetime(velocity);
  20505. this._parseModule(velocityOverLifetime, velocityOverLifetimeData);
  20506. particleSystem.velocityOverLifetime = velocityOverLifetime;
  20507. }
  20508. var colorOverLifetimeData = data.colorOverLifetime;
  20509. if (colorOverLifetimeData) {
  20510. var colorData = colorOverLifetimeData.color;
  20511. var color;
  20512. switch (colorData.type) {
  20513. case 0:
  20514. var constColorData = colorData.constant;
  20515. color = GradientColor.createByConstant(constColorData ? new Vector4(constColorData[0], constColorData[1], constColorData[2], constColorData[3]) : new Vector4(0, 0, 0, 0));
  20516. break;
  20517. case 1:
  20518. color = GradientColor.createByGradient(this._initParticleColor(colorData.gradient));
  20519. break;
  20520. case 2:
  20521. var minConstColorData = colorData.constantMin;
  20522. var maxConstColorData = colorData.constantMax;
  20523. color = GradientColor.createByRandomTwoConstant(minConstColorData ? new Vector4(minConstColorData[0], minConstColorData[1], minConstColorData[2], minConstColorData[3]) : new Vector4(0, 0, 0, 0), minConstColorData ? new Vector4(maxConstColorData[0], maxConstColorData[1], maxConstColorData[2], maxConstColorData[3]) : new Vector4(0, 0, 0, 0));
  20524. break;
  20525. case 3:
  20526. color = GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin), this._initParticleColor(colorData.gradientMax));
  20527. break;
  20528. }
  20529. var colorOverLifetime = new ColorOverLifetime(color);
  20530. this._parseModule(colorOverLifetime, colorOverLifetimeData);
  20531. particleSystem.colorOverLifetime = colorOverLifetime;
  20532. }
  20533. var sizeOverLifetimeData = data.sizeOverLifetime;
  20534. if (sizeOverLifetimeData) {
  20535. var sizeData = sizeOverLifetimeData.size;
  20536. var size;
  20537. switch (sizeData.type) {
  20538. case 0:
  20539. if (sizeData.separateAxes) {
  20540. size = GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX), this._initParticleSize(sizeData.gradientY), this._initParticleSize(sizeData.gradientZ));
  20541. }
  20542. else {
  20543. size = GradientSize.createByGradient(this._initParticleSize(sizeData.gradient));
  20544. }
  20545. break;
  20546. case 1:
  20547. if (sizeData.separateAxes) {
  20548. var constantMinSeparateData = sizeData.constantMinSeparate;
  20549. var constantMaxSeparateData = sizeData.constantMaxSeparate;
  20550. size = GradientSize.createByRandomTwoConstantSeparate(constantMinSeparateData ? new Vector3(constantMinSeparateData[0], constantMinSeparateData[1], constantMinSeparateData[2]) : new Vector3(0, 0, 0), constantMaxSeparateData ? new Vector3(constantMaxSeparateData[0], constantMaxSeparateData[1], constantMaxSeparateData[2]) : new Vector3(0, 0, 0));
  20551. }
  20552. else {
  20553. size = GradientSize.createByRandomTwoConstant(sizeData.constantMin || 0, sizeData.constantMax || 0);
  20554. }
  20555. break;
  20556. case 2:
  20557. if (sizeData.separateAxes) {
  20558. size = GradientSize.createByRandomTwoGradientSeparate(this._initParticleSize(sizeData.gradientXMin), this._initParticleSize(sizeData.gradientYMin), this._initParticleSize(sizeData.gradientZMin), this._initParticleSize(sizeData.gradientXMax), this._initParticleSize(sizeData.gradientYMax), this._initParticleSize(sizeData.gradientZMax));
  20559. }
  20560. else {
  20561. size = GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin), this._initParticleSize(sizeData.gradientMax));
  20562. }
  20563. break;
  20564. }
  20565. var sizeOverLifetime = new SizeOverLifetime(size);
  20566. this._parseModule(sizeOverLifetime, sizeOverLifetimeData);
  20567. particleSystem.sizeOverLifetime = sizeOverLifetime;
  20568. }
  20569. var rotationOverLifetimeData = data.rotationOverLifetime;
  20570. if (rotationOverLifetimeData) {
  20571. var angularVelocityData = rotationOverLifetimeData.angularVelocity;
  20572. var angularVelocity;
  20573. switch (angularVelocityData.type) {
  20574. case 0:
  20575. if (angularVelocityData.separateAxes) {
  20576. var conSep = angularVelocityData.constantSeparate;
  20577. angularVelocity = GradientAngularVelocity.createByConstantSeparate(conSep ? new Vector3(conSep[0], conSep[1], conSep[2]) : new Vector3(0, 0, Math.PI / 4));
  20578. }
  20579. else {
  20580. angularVelocity = GradientAngularVelocity.createByConstant(angularVelocityData.constant || Math.PI / 4);
  20581. }
  20582. break;
  20583. case 1:
  20584. if (angularVelocityData.separateAxes) {
  20585. angularVelocity = GradientAngularVelocity.createByGradientSeparate(this._initParticleRotation(angularVelocityData.gradientX), this._initParticleRotation(angularVelocityData.gradientY), this._initParticleRotation(angularVelocityData.gradientZ));
  20586. }
  20587. else {
  20588. angularVelocity = GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient));
  20589. }
  20590. break;
  20591. case 2:
  20592. if (angularVelocityData.separateAxes) {
  20593. var minSep = angularVelocityData.constantMinSeparate;
  20594. var maxSep = angularVelocityData.constantMaxSeparate;
  20595. angularVelocity = GradientAngularVelocity.createByRandomTwoConstantSeparate(minSep ? new Vector3(minSep[0], minSep[1], minSep[2]) : new Vector3(0, 0, 0), maxSep ? new Vector3(maxSep[0], maxSep[1], maxSep[2]) : new Vector3(0, 0, Math.PI / 4));
  20596. }
  20597. else {
  20598. angularVelocity = GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin || 0, angularVelocityData.constantMax || Math.PI / 4);
  20599. }
  20600. break;
  20601. case 3:
  20602. if (angularVelocityData.separateAxes) ;
  20603. else {
  20604. angularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin), this._initParticleRotation(angularVelocityData.gradientMax));
  20605. }
  20606. break;
  20607. }
  20608. var rotationOverLifetime = new RotationOverLifetime(angularVelocity);
  20609. this._parseModule(rotationOverLifetime, rotationOverLifetimeData);
  20610. particleSystem.rotationOverLifetime = rotationOverLifetime;
  20611. }
  20612. var textureSheetAnimationData = data.textureSheetAnimation;
  20613. if (textureSheetAnimationData) {
  20614. var frameData = textureSheetAnimationData.frame;
  20615. var frameOverTime;
  20616. switch (frameData.type) {
  20617. case 0:
  20618. frameOverTime = FrameOverTime.createByConstant(frameData.constant);
  20619. break;
  20620. case 1:
  20621. frameOverTime = FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime));
  20622. break;
  20623. case 2:
  20624. frameOverTime = FrameOverTime.createByRandomTwoConstant(frameData.constantMin, frameData.constantMax);
  20625. break;
  20626. case 3:
  20627. frameOverTime = FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin), this._initParticleFrame(frameData.overTimeMax));
  20628. break;
  20629. }
  20630. var startFrameData = textureSheetAnimationData.startFrame;
  20631. var startFrame;
  20632. switch (startFrameData.type) {
  20633. case 0:
  20634. startFrame = StartFrame.createByConstant(startFrameData.constant);
  20635. break;
  20636. case 1:
  20637. startFrame = StartFrame.createByRandomTwoConstant(startFrameData.constantMin, startFrameData.constantMax);
  20638. break;
  20639. }
  20640. var textureSheetAnimation = new TextureSheetAnimation(frameOverTime, startFrame);
  20641. this._parseModule(textureSheetAnimation, textureSheetAnimationData);
  20642. particleSystem.textureSheetAnimation = textureSheetAnimation;
  20643. }
  20644. }
  20645. else {
  20646. this._parseOld(data);
  20647. }
  20648. }
  20649. _activeHierarchy(activeChangeComponents) {
  20650. super._activeHierarchy(activeChangeComponents);
  20651. (this.particleSystem.playOnAwake) && (this.particleSystem.play());
  20652. }
  20653. _inActiveHierarchy(activeChangeComponents) {
  20654. super._inActiveHierarchy(activeChangeComponents);
  20655. (this.particleSystem.isAlive) && (this.particleSystem.simulate(0, true));
  20656. }
  20657. _cloneTo(destObject, srcSprite, dstSprite) {
  20658. var destShuriKenParticle3D = destObject;
  20659. var destParticleSystem = destShuriKenParticle3D._particleSystem;
  20660. this._particleSystem.cloneTo(destParticleSystem);
  20661. var destParticleRender = destShuriKenParticle3D._render;
  20662. var particleRender = this._render;
  20663. destParticleRender.sharedMaterials = particleRender.sharedMaterials;
  20664. destParticleRender.enable = particleRender.enable;
  20665. destParticleRender.renderMode = particleRender.renderMode;
  20666. destParticleRender.mesh = particleRender.mesh;
  20667. destParticleRender.stretchedBillboardCameraSpeedScale = particleRender.stretchedBillboardCameraSpeedScale;
  20668. destParticleRender.stretchedBillboardSpeedScale = particleRender.stretchedBillboardSpeedScale;
  20669. destParticleRender.stretchedBillboardLengthScale = particleRender.stretchedBillboardLengthScale;
  20670. destParticleRender.sortingFudge = particleRender.sortingFudge;
  20671. super._cloneTo(destObject, srcSprite, dstSprite);
  20672. }
  20673. destroy(destroyChild = true) {
  20674. if (this.destroyed)
  20675. return;
  20676. super.destroy(destroyChild);
  20677. this._particleSystem.destroy();
  20678. this._particleSystem = null;
  20679. }
  20680. _create() {
  20681. return new ShuriKenParticle3D();
  20682. }
  20683. _parseOld(data) {
  20684. const anglelToRad = Math.PI / 180.0;
  20685. var i, n;
  20686. var particleRender = this.particleRenderer;
  20687. var material;
  20688. var materialData = data.material;
  20689. (materialData) && (material = Laya.Loader.getRes(materialData.path));
  20690. particleRender.sharedMaterial = material;
  20691. var meshPath = data.meshPath;
  20692. (meshPath) && (particleRender.mesh = Laya.Loader.getRes(meshPath));
  20693. particleRender.renderMode = data.renderMode;
  20694. particleRender.stretchedBillboardCameraSpeedScale = data.stretchedBillboardCameraSpeedScale;
  20695. particleRender.stretchedBillboardSpeedScale = data.stretchedBillboardSpeedScale;
  20696. particleRender.stretchedBillboardLengthScale = data.stretchedBillboardLengthScale;
  20697. particleRender.sortingFudge = data.sortingFudge ? data.sortingFudge : 0.0;
  20698. var particleSystem = this.particleSystem;
  20699. particleSystem.isPerformanceMode = data.isPerformanceMode;
  20700. particleSystem.duration = data.duration;
  20701. particleSystem.looping = data.looping;
  20702. particleSystem.prewarm = data.prewarm;
  20703. particleSystem.startDelayType = data.startDelayType;
  20704. particleSystem.startDelay = data.startDelay;
  20705. particleSystem.startDelayMin = data.startDelayMin;
  20706. particleSystem.startDelayMax = data.startDelayMax;
  20707. particleSystem.startLifetimeType = data.startLifetimeType;
  20708. particleSystem.startLifetimeConstant = data.startLifetimeConstant;
  20709. particleSystem.startLifeTimeGradient = ShuriKenParticle3D._initStartLife(data.startLifetimeGradient);
  20710. particleSystem.startLifetimeConstantMin = data.startLifetimeConstantMin;
  20711. particleSystem.startLifetimeConstantMax = data.startLifetimeConstantMax;
  20712. particleSystem.startLifeTimeGradientMin = ShuriKenParticle3D._initStartLife(data.startLifetimeGradientMin);
  20713. particleSystem.startLifeTimeGradientMax = ShuriKenParticle3D._initStartLife(data.startLifetimeGradientMax);
  20714. particleSystem.startSpeedType = data.startSpeedType;
  20715. particleSystem.startSpeedConstant = data.startSpeedConstant;
  20716. particleSystem.startSpeedConstantMin = data.startSpeedConstantMin;
  20717. particleSystem.startSpeedConstantMax = data.startSpeedConstantMax;
  20718. particleSystem.threeDStartSize = data.threeDStartSize;
  20719. particleSystem.startSizeType = data.startSizeType;
  20720. particleSystem.startSizeConstant = data.startSizeConstant;
  20721. var startSizeConstantSeparateArray = data.startSizeConstantSeparate;
  20722. var startSizeConstantSeparateElement = particleSystem.startSizeConstantSeparate;
  20723. startSizeConstantSeparateElement.x = startSizeConstantSeparateArray[0];
  20724. startSizeConstantSeparateElement.y = startSizeConstantSeparateArray[1];
  20725. startSizeConstantSeparateElement.z = startSizeConstantSeparateArray[2];
  20726. particleSystem.startSizeConstantMin = data.startSizeConstantMin;
  20727. particleSystem.startSizeConstantMax = data.startSizeConstantMax;
  20728. var startSizeConstantMinSeparateArray = data.startSizeConstantMinSeparate;
  20729. var startSizeConstantMinSeparateElement = particleSystem.startSizeConstantMinSeparate;
  20730. startSizeConstantMinSeparateElement.x = startSizeConstantMinSeparateArray[0];
  20731. startSizeConstantMinSeparateElement.y = startSizeConstantMinSeparateArray[1];
  20732. startSizeConstantMinSeparateElement.z = startSizeConstantMinSeparateArray[2];
  20733. var startSizeConstantMaxSeparateArray = data.startSizeConstantMaxSeparate;
  20734. var startSizeConstantMaxSeparateElement = particleSystem.startSizeConstantMaxSeparate;
  20735. startSizeConstantMaxSeparateElement.x = startSizeConstantMaxSeparateArray[0];
  20736. startSizeConstantMaxSeparateElement.y = startSizeConstantMaxSeparateArray[1];
  20737. startSizeConstantMaxSeparateElement.z = startSizeConstantMaxSeparateArray[2];
  20738. particleSystem.threeDStartRotation = data.threeDStartRotation;
  20739. particleSystem.startRotationType = data.startRotationType;
  20740. particleSystem.startRotationConstant = data.startRotationConstant * anglelToRad;
  20741. var startRotationConstantSeparateArray = data.startRotationConstantSeparate;
  20742. var startRotationConstantSeparateElement = particleSystem.startRotationConstantSeparate;
  20743. startRotationConstantSeparateElement.x = startRotationConstantSeparateArray[0] * anglelToRad;
  20744. startRotationConstantSeparateElement.y = startRotationConstantSeparateArray[1] * anglelToRad;
  20745. startRotationConstantSeparateElement.z = startRotationConstantSeparateArray[2] * anglelToRad;
  20746. particleSystem.startRotationConstantMin = data.startRotationConstantMin * anglelToRad;
  20747. particleSystem.startRotationConstantMax = data.startRotationConstantMax * anglelToRad;
  20748. var startRotationConstantMinSeparateArray = data.startRotationConstantMinSeparate;
  20749. var startRotationConstantMinSeparateElement = particleSystem.startRotationConstantMinSeparate;
  20750. startRotationConstantMinSeparateElement.x = startRotationConstantMinSeparateArray[0] * anglelToRad;
  20751. startRotationConstantMinSeparateElement.y = startRotationConstantMinSeparateArray[1] * anglelToRad;
  20752. startRotationConstantMinSeparateElement.z = startRotationConstantMinSeparateArray[2] * anglelToRad;
  20753. var startRotationConstantMaxSeparateArray = data.startRotationConstantMaxSeparate;
  20754. var startRotationConstantMaxSeparateElement = particleSystem.startRotationConstantMaxSeparate;
  20755. startRotationConstantMaxSeparateElement.x = startRotationConstantMaxSeparateArray[0] * anglelToRad;
  20756. startRotationConstantMaxSeparateElement.y = startRotationConstantMaxSeparateArray[1] * anglelToRad;
  20757. startRotationConstantMaxSeparateElement.z = startRotationConstantMaxSeparateArray[2] * anglelToRad;
  20758. particleSystem.randomizeRotationDirection = data.randomizeRotationDirection;
  20759. particleSystem.startColorType = data.startColorType;
  20760. var startColorConstantArray = data.startColorConstant;
  20761. var startColorConstantElement = particleSystem.startColorConstant;
  20762. startColorConstantElement.x = startColorConstantArray[0];
  20763. startColorConstantElement.y = startColorConstantArray[1];
  20764. startColorConstantElement.z = startColorConstantArray[2];
  20765. startColorConstantElement.w = startColorConstantArray[3];
  20766. var startColorConstantMinArray = data.startColorConstantMin;
  20767. var startColorConstantMinElement = particleSystem.startColorConstantMin;
  20768. startColorConstantMinElement.x = startColorConstantMinArray[0];
  20769. startColorConstantMinElement.y = startColorConstantMinArray[1];
  20770. startColorConstantMinElement.z = startColorConstantMinArray[2];
  20771. startColorConstantMinElement.w = startColorConstantMinArray[3];
  20772. var startColorConstantMaxArray = data.startColorConstantMax;
  20773. var startColorConstantMaxElement = particleSystem.startColorConstantMax;
  20774. startColorConstantMaxElement.x = startColorConstantMaxArray[0];
  20775. startColorConstantMaxElement.y = startColorConstantMaxArray[1];
  20776. startColorConstantMaxElement.z = startColorConstantMaxArray[2];
  20777. startColorConstantMaxElement.w = startColorConstantMaxArray[3];
  20778. particleSystem.gravityModifier = data.gravityModifier;
  20779. particleSystem.simulationSpace = data.simulationSpace;
  20780. (data.simulationSpeed !== undefined) && (particleSystem.simulationSpeed = data.simulationSpeed);
  20781. particleSystem.scaleMode = data.scaleMode;
  20782. particleSystem.playOnAwake = data.playOnAwake;
  20783. particleSystem.maxParticles = data.maxParticles;
  20784. var autoRandomSeed = data.autoRandomSeed;
  20785. (autoRandomSeed != null) && (particleSystem.autoRandomSeed = autoRandomSeed);
  20786. var randomSeed = data.randomSeed;
  20787. (randomSeed != null) && (particleSystem.randomSeed[0] = randomSeed);
  20788. var emissionData = data.emission;
  20789. var emission = particleSystem.emission;
  20790. if (emissionData) {
  20791. emission.emissionRate = emissionData.emissionRate;
  20792. var burstsData = emissionData.bursts;
  20793. if (burstsData)
  20794. for (i = 0, n = burstsData.length; i < n; i++) {
  20795. var brust = burstsData[i];
  20796. emission.addBurst(new Burst(brust.time, brust.min, brust.max));
  20797. }
  20798. emission.enable = emissionData.enable;
  20799. }
  20800. else {
  20801. emission.enable = false;
  20802. }
  20803. var shapeData = data.shape;
  20804. if (shapeData) {
  20805. var shape;
  20806. switch (shapeData.shapeType) {
  20807. case 0:
  20808. var sphereShape;
  20809. shape = sphereShape = new SphereShape();
  20810. sphereShape.radius = shapeData.sphereRadius;
  20811. sphereShape.emitFromShell = shapeData.sphereEmitFromShell;
  20812. sphereShape.randomDirection = shapeData.sphereRandomDirection;
  20813. break;
  20814. case 1:
  20815. var hemiSphereShape;
  20816. shape = hemiSphereShape = new HemisphereShape();
  20817. hemiSphereShape.radius = shapeData.hemiSphereRadius;
  20818. hemiSphereShape.emitFromShell = shapeData.hemiSphereEmitFromShell;
  20819. hemiSphereShape.randomDirection = shapeData.hemiSphereRandomDirection;
  20820. break;
  20821. case 2:
  20822. var coneShape;
  20823. shape = coneShape = new ConeShape();
  20824. coneShape.angle = shapeData.coneAngle * anglelToRad;
  20825. coneShape.radius = shapeData.coneRadius;
  20826. coneShape.length = shapeData.coneLength;
  20827. coneShape.emitType = shapeData.coneEmitType;
  20828. coneShape.randomDirection = shapeData.coneRandomDirection;
  20829. break;
  20830. case 3:
  20831. var boxShape;
  20832. shape = boxShape = new BoxShape();
  20833. boxShape.x = shapeData.boxX;
  20834. boxShape.y = shapeData.boxY;
  20835. boxShape.z = shapeData.boxZ;
  20836. boxShape.randomDirection = shapeData.boxRandomDirection;
  20837. break;
  20838. case 7:
  20839. var circleShape;
  20840. shape = circleShape = new CircleShape();
  20841. circleShape.radius = shapeData.circleRadius;
  20842. circleShape.arc = shapeData.circleArc * anglelToRad;
  20843. circleShape.emitFromEdge = shapeData.circleEmitFromEdge;
  20844. circleShape.randomDirection = shapeData.circleRandomDirection;
  20845. break;
  20846. default:
  20847. var tempShape;
  20848. shape = tempShape = new CircleShape();
  20849. tempShape.radius = shapeData.circleRadius;
  20850. tempShape.arc = shapeData.circleArc * anglelToRad;
  20851. tempShape.emitFromEdge = shapeData.circleEmitFromEdge;
  20852. tempShape.randomDirection = shapeData.circleRandomDirection;
  20853. break;
  20854. }
  20855. shape.enable = shapeData.enable;
  20856. particleSystem.shape = shape;
  20857. }
  20858. var velocityOverLifetimeData = data.velocityOverLifetime;
  20859. if (velocityOverLifetimeData) {
  20860. var velocityData = velocityOverLifetimeData.velocity;
  20861. var velocity;
  20862. switch (velocityData.type) {
  20863. case 0:
  20864. var constantData = velocityData.constant;
  20865. velocity = GradientVelocity.createByConstant(new Vector3(constantData[0], constantData[1], constantData[2]));
  20866. break;
  20867. case 1:
  20868. velocity = GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX), this._initParticleVelocity(velocityData.gradientY), this._initParticleVelocity(velocityData.gradientZ));
  20869. break;
  20870. case 2:
  20871. var constantMinData = velocityData.constantMin;
  20872. var constantMaxData = velocityData.constantMax;
  20873. velocity = GradientVelocity.createByRandomTwoConstant(new Vector3(constantMinData[0], constantMinData[1], constantMinData[2]), new Vector3(constantMaxData[0], constantMaxData[1], constantMaxData[2]));
  20874. break;
  20875. case 3:
  20876. velocity = GradientVelocity.createByRandomTwoGradient(this._initParticleVelocity(velocityData.gradientXMin), this._initParticleVelocity(velocityData.gradientXMax), this._initParticleVelocity(velocityData.gradientYMin), this._initParticleVelocity(velocityData.gradientYMax), this._initParticleVelocity(velocityData.gradientZMin), this._initParticleVelocity(velocityData.gradientZMax));
  20877. break;
  20878. }
  20879. var velocityOverLifetime = new VelocityOverLifetime(velocity);
  20880. velocityOverLifetime.space = velocityOverLifetimeData.space;
  20881. velocityOverLifetime.enable = velocityOverLifetimeData.enable;
  20882. particleSystem.velocityOverLifetime = velocityOverLifetime;
  20883. }
  20884. var colorOverLifetimeData = data.colorOverLifetime;
  20885. if (colorOverLifetimeData) {
  20886. var colorData = colorOverLifetimeData.color;
  20887. var color;
  20888. switch (colorData.type) {
  20889. case 0:
  20890. var constColorData = colorData.constant;
  20891. color = GradientColor.createByConstant(new Vector4(constColorData[0], constColorData[1], constColorData[2], constColorData[3]));
  20892. break;
  20893. case 1:
  20894. color = GradientColor.createByGradient(this._initParticleColor(colorData.gradient));
  20895. break;
  20896. case 2:
  20897. var minConstColorData = colorData.constantMin;
  20898. var maxConstColorData = colorData.constantMax;
  20899. color = GradientColor.createByRandomTwoConstant(new Vector4(minConstColorData[0], minConstColorData[1], minConstColorData[2], minConstColorData[3]), new Vector4(maxConstColorData[0], maxConstColorData[1], maxConstColorData[2], maxConstColorData[3]));
  20900. break;
  20901. case 3:
  20902. color = GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin), this._initParticleColor(colorData.gradientMax));
  20903. break;
  20904. }
  20905. var colorOverLifetime = new ColorOverLifetime(color);
  20906. colorOverLifetime.enable = colorOverLifetimeData.enable;
  20907. particleSystem.colorOverLifetime = colorOverLifetime;
  20908. }
  20909. var sizeOverLifetimeData = data.sizeOverLifetime;
  20910. if (sizeOverLifetimeData) {
  20911. var sizeData = sizeOverLifetimeData.size;
  20912. var size;
  20913. switch (sizeData.type) {
  20914. case 0:
  20915. if (sizeData.separateAxes) {
  20916. size = GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX), this._initParticleSize(sizeData.gradientY), this._initParticleSize(sizeData.gradientZ));
  20917. }
  20918. else {
  20919. size = GradientSize.createByGradient(this._initParticleSize(sizeData.gradient));
  20920. }
  20921. break;
  20922. case 1:
  20923. if (sizeData.separateAxes) {
  20924. var constantMinSeparateData = sizeData.constantMinSeparate;
  20925. var constantMaxSeparateData = sizeData.constantMaxSeparate;
  20926. size = GradientSize.createByRandomTwoConstantSeparate(new Vector3(constantMinSeparateData[0], constantMinSeparateData[1], constantMinSeparateData[2]), new Vector3(constantMaxSeparateData[0], constantMaxSeparateData[1], constantMaxSeparateData[2]));
  20927. }
  20928. else {
  20929. size = GradientSize.createByRandomTwoConstant(sizeData.constantMin, sizeData.constantMax);
  20930. }
  20931. break;
  20932. case 2:
  20933. if (sizeData.separateAxes) {
  20934. size = GradientSize.createByRandomTwoGradientSeparate(this._initParticleSize(sizeData.gradientXMin), this._initParticleSize(sizeData.gradientYMin), this._initParticleSize(sizeData.gradientZMin), this._initParticleSize(sizeData.gradientXMax), this._initParticleSize(sizeData.gradientYMax), this._initParticleSize(sizeData.gradientZMax));
  20935. }
  20936. else {
  20937. size = GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin), this._initParticleSize(sizeData.gradientMax));
  20938. }
  20939. break;
  20940. }
  20941. var sizeOverLifetime = new SizeOverLifetime(size);
  20942. sizeOverLifetime.enable = sizeOverLifetimeData.enable;
  20943. particleSystem.sizeOverLifetime = sizeOverLifetime;
  20944. }
  20945. var rotationOverLifetimeData = data.rotationOverLifetime;
  20946. if (rotationOverLifetimeData) {
  20947. var angularVelocityData = rotationOverLifetimeData.angularVelocity;
  20948. var angularVelocity;
  20949. switch (angularVelocityData.type) {
  20950. case 0:
  20951. if (angularVelocityData.separateAxes) {
  20952. var conSep = angularVelocityData.constantSeparate;
  20953. angularVelocity = GradientAngularVelocity.createByConstantSeparate(new Vector3(conSep[0] * anglelToRad, conSep[1] * anglelToRad, conSep[2] * anglelToRad));
  20954. }
  20955. else {
  20956. angularVelocity = GradientAngularVelocity.createByConstant(angularVelocityData.constant * anglelToRad);
  20957. }
  20958. break;
  20959. case 1:
  20960. if (angularVelocityData.separateAxes) {
  20961. angularVelocity = GradientAngularVelocity.createByGradientSeparate(this._initParticleRotation(angularVelocityData.gradientX), this._initParticleRotation(angularVelocityData.gradientY), this._initParticleRotation(angularVelocityData.gradientZ));
  20962. }
  20963. else {
  20964. angularVelocity = GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient));
  20965. }
  20966. break;
  20967. case 2:
  20968. if (angularVelocityData.separateAxes) {
  20969. var minSep = angularVelocityData.constantMinSeparate;
  20970. var maxSep = angularVelocityData.constantMaxSeparate;
  20971. angularVelocity = GradientAngularVelocity.createByRandomTwoConstantSeparate(new Vector3(minSep[0] * anglelToRad, minSep[1] * anglelToRad, minSep[2] * anglelToRad), new Vector3(maxSep[0] * anglelToRad, maxSep[1] * anglelToRad, maxSep[2] * anglelToRad));
  20972. }
  20973. else {
  20974. angularVelocity = GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin * anglelToRad, angularVelocityData.constantMax * anglelToRad);
  20975. }
  20976. break;
  20977. case 3:
  20978. if (angularVelocityData.separateAxes) ;
  20979. else {
  20980. angularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin), this._initParticleRotation(angularVelocityData.gradientMax));
  20981. }
  20982. break;
  20983. }
  20984. var rotationOverLifetime = new RotationOverLifetime(angularVelocity);
  20985. rotationOverLifetime.enable = rotationOverLifetimeData.enable;
  20986. particleSystem.rotationOverLifetime = rotationOverLifetime;
  20987. }
  20988. var textureSheetAnimationData = data.textureSheetAnimation;
  20989. if (textureSheetAnimationData) {
  20990. var frameData = textureSheetAnimationData.frame;
  20991. var frameOverTime;
  20992. switch (frameData.type) {
  20993. case 0:
  20994. frameOverTime = FrameOverTime.createByConstant(frameData.constant);
  20995. break;
  20996. case 1:
  20997. frameOverTime = FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime));
  20998. break;
  20999. case 2:
  21000. frameOverTime = FrameOverTime.createByRandomTwoConstant(frameData.constantMin, frameData.constantMax);
  21001. break;
  21002. case 3:
  21003. frameOverTime = FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin), this._initParticleFrame(frameData.overTimeMax));
  21004. break;
  21005. }
  21006. var startFrameData = textureSheetAnimationData.startFrame;
  21007. var startFrame;
  21008. switch (startFrameData.type) {
  21009. case 0:
  21010. startFrame = StartFrame.createByConstant(startFrameData.constant);
  21011. break;
  21012. case 1:
  21013. startFrame = StartFrame.createByRandomTwoConstant(startFrameData.constantMin, startFrameData.constantMax);
  21014. break;
  21015. }
  21016. var textureSheetAnimation = new TextureSheetAnimation(frameOverTime, startFrame);
  21017. textureSheetAnimation.enable = textureSheetAnimationData.enable;
  21018. var tilesData = textureSheetAnimationData.tiles;
  21019. textureSheetAnimation.tiles = new Vector2(tilesData[0], tilesData[1]);
  21020. textureSheetAnimation.type = textureSheetAnimationData.type;
  21021. textureSheetAnimation.randomRow = textureSheetAnimationData.randomRow;
  21022. var rowIndex = textureSheetAnimationData.rowIndex;
  21023. (rowIndex !== undefined) && (textureSheetAnimation.rowIndex = rowIndex);
  21024. textureSheetAnimation.cycles = textureSheetAnimationData.cycles;
  21025. particleSystem.textureSheetAnimation = textureSheetAnimation;
  21026. }
  21027. }
  21028. _initParticleColor(gradientColorData) {
  21029. var gradientColor = new Gradient(4, 4);
  21030. if (!gradientColorData) {
  21031. gradientColor.addColorAlpha(0, 1);
  21032. gradientColor.addColorAlpha(1, 1);
  21033. gradientColor.addColorRGB(0, new Color(1.0, 1.0, 1.0, 1.0));
  21034. gradientColor.addColorRGB(1, new Color(1.0, 1.0, 1.0, 1.0));
  21035. }
  21036. else {
  21037. var alphasData = gradientColorData.alphas;
  21038. var i, n;
  21039. if (!alphasData) {
  21040. gradientColor.addColorAlpha(0, 1);
  21041. gradientColor.addColorAlpha(1, 1);
  21042. }
  21043. else {
  21044. for (i = 0, n = alphasData.length; i < n; i++) {
  21045. if (i == 3 && n > 4) {
  21046. i = n - 1;
  21047. console.warn("GradientDataColor warning:alpha data length is large than 4, will ignore the middle data.");
  21048. }
  21049. var alphaData = alphasData[i];
  21050. gradientColor.addColorAlpha(alphaData.key, alphaData.value);
  21051. }
  21052. }
  21053. var rgbsData = gradientColorData.rgbs;
  21054. if (!rgbsData) {
  21055. gradientColor.addColorRGB(0, new Color(1.0, 1.0, 1.0, 1.0));
  21056. gradientColor.addColorRGB(1, new Color(1.0, 1.0, 1.0, 1.0));
  21057. }
  21058. else {
  21059. for (i = 0, n = rgbsData.length; i < n; i++) {
  21060. if (i == 3 && n > 4) {
  21061. i = n - 1;
  21062. console.warn("GradientDataColor warning:rgb data length is large than 4, will ignore the middle data.");
  21063. }
  21064. var rgbData = rgbsData[i];
  21065. var rgbValue = rgbData.value;
  21066. gradientColor.addColorRGB(rgbData.key, new Color(rgbValue[0], rgbValue[1], rgbValue[2], 1.0));
  21067. }
  21068. }
  21069. }
  21070. return gradientColor;
  21071. }
  21072. _initParticleFrame(overTimeFramesData) {
  21073. var overTimeFrame = new GradientDataInt();
  21074. if (overTimeFramesData) {
  21075. var framesData = overTimeFramesData.frames;
  21076. for (var i = 0, n = framesData.length; i < n; i++) {
  21077. var frameData = framesData[i];
  21078. overTimeFrame.add(frameData.key, frameData.value);
  21079. }
  21080. }
  21081. else {
  21082. overTimeFrame.add(0, 0);
  21083. overTimeFrame.add(1, 1);
  21084. }
  21085. return overTimeFrame;
  21086. }
  21087. static _initStartLife(gradientData) {
  21088. var gradient = new GradientDataNumber();
  21089. var startLifetimesData = gradientData.startLifetimes;
  21090. for (var i = 0, n = startLifetimesData.length; i < n; i++) {
  21091. var valueData = startLifetimesData[i];
  21092. gradient.add(valueData.key, valueData.value);
  21093. }
  21094. return gradient;
  21095. }
  21096. _initParticleVelocity(gradientData) {
  21097. var gradient = new GradientDataNumber();
  21098. var velocitysData = gradientData.velocitys;
  21099. for (var i = 0, n = velocitysData.length; i < n; i++) {
  21100. var valueData = velocitysData[i];
  21101. gradient.add(valueData.key, valueData.value);
  21102. }
  21103. return gradient;
  21104. }
  21105. _initParticleSize(gradientSizeData) {
  21106. var gradientSize = new GradientDataNumber();
  21107. if (gradientSizeData) {
  21108. var sizesData = gradientSizeData.sizes;
  21109. for (var i = 0, n = sizesData.length; i < n; i++) {
  21110. var valueData = sizesData[i];
  21111. gradientSize.add(valueData.key, valueData.value);
  21112. }
  21113. }
  21114. else {
  21115. gradientSize.add(0, 0);
  21116. gradientSize.add(1, 1);
  21117. }
  21118. return gradientSize;
  21119. }
  21120. _initParticleRotation(gradientData) {
  21121. var gradient = new GradientDataNumber();
  21122. var angularVelocitysData = gradientData.angularVelocitys;
  21123. for (var i = 0, n = angularVelocitysData.length; i < n; i++) {
  21124. var valueData = angularVelocitysData[i];
  21125. gradient.add(valueData.key, valueData.value / 180.0 * Math.PI);
  21126. }
  21127. return gradient;
  21128. }
  21129. }
  21130. class PixelLineMaterial extends Material {
  21131. constructor() {
  21132. super();
  21133. this.setShaderName("LineShader");
  21134. this._shaderValues.setVector(PixelLineMaterial.COLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  21135. }
  21136. static __initDefine__() {
  21137. }
  21138. get color() {
  21139. return this._shaderValues.getVector(PixelLineMaterial.COLOR);
  21140. }
  21141. set color(value) {
  21142. this._shaderValues.setVector(PixelLineMaterial.COLOR, value);
  21143. }
  21144. set depthWrite(value) {
  21145. this._shaderValues.setBool(PixelLineMaterial.DEPTH_WRITE, value);
  21146. }
  21147. get depthWrite() {
  21148. return this._shaderValues.getBool(PixelLineMaterial.DEPTH_WRITE);
  21149. }
  21150. set cull(value) {
  21151. this._shaderValues.setInt(PixelLineMaterial.CULL, value);
  21152. }
  21153. get cull() {
  21154. return this._shaderValues.getInt(PixelLineMaterial.CULL);
  21155. }
  21156. set blend(value) {
  21157. this._shaderValues.setInt(PixelLineMaterial.BLEND, value);
  21158. }
  21159. get blend() {
  21160. return this._shaderValues.getInt(PixelLineMaterial.BLEND);
  21161. }
  21162. set blendSrc(value) {
  21163. this._shaderValues.setInt(PixelLineMaterial.BLEND_SRC, value);
  21164. }
  21165. get blendSrc() {
  21166. return this._shaderValues.getInt(PixelLineMaterial.BLEND_SRC);
  21167. }
  21168. set blendDst(value) {
  21169. this._shaderValues.setInt(PixelLineMaterial.BLEND_DST, value);
  21170. }
  21171. get blendDst() {
  21172. return this._shaderValues.getInt(PixelLineMaterial.BLEND_DST);
  21173. }
  21174. set depthTest(value) {
  21175. this._shaderValues.setInt(PixelLineMaterial.DEPTH_TEST, value);
  21176. }
  21177. get depthTest() {
  21178. return this._shaderValues.getInt(PixelLineMaterial.DEPTH_TEST);
  21179. }
  21180. clone() {
  21181. var dest = new PixelLineMaterial();
  21182. this.cloneTo(dest);
  21183. return dest;
  21184. }
  21185. }
  21186. PixelLineMaterial.COLOR = Shader3D.propertyNameToID("u_Color");
  21187. PixelLineMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  21188. PixelLineMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  21189. PixelLineMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  21190. PixelLineMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  21191. PixelLineMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  21192. PixelLineMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  21193. class PixelLineVertex {
  21194. static get vertexDeclaration() {
  21195. return PixelLineVertex._vertexDeclaration;
  21196. }
  21197. static __init__() {
  21198. PixelLineVertex._vertexDeclaration = new VertexDeclaration(28, [new VertexElement(0, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0),
  21199. new VertexElement(12, VertexElementFormat.Vector4, VertexMesh.MESH_COLOR0)]);
  21200. }
  21201. get vertexDeclaration() {
  21202. return PixelLineVertex._vertexDeclaration;
  21203. }
  21204. constructor() {
  21205. }
  21206. }
  21207. class SimpleSingletonList extends SingletonList {
  21208. constructor() {
  21209. super();
  21210. }
  21211. add(element) {
  21212. var index = element._getIndexInList();
  21213. if (index !== -1)
  21214. throw "SimpleSingletonList:" + element + " has in SingletonList.";
  21215. this._add(element);
  21216. element._setIndexInList(this.length++);
  21217. }
  21218. remove(element) {
  21219. var index = element._getIndexInList();
  21220. this.length--;
  21221. if (index !== this.length) {
  21222. var end = this.elements[this.length];
  21223. this.elements[index] = end;
  21224. end._setIndexInList(index);
  21225. }
  21226. element._setIndexInList(-1);
  21227. }
  21228. clear() {
  21229. var elements = this.elements;
  21230. for (var i, n = this.length; i < n; i++)
  21231. elements[i]._setIndexInList(-1);
  21232. this.length = 0;
  21233. }
  21234. }
  21235. class MouseTouch {
  21236. constructor() {
  21237. this._pressedSprite = null;
  21238. this._pressedLoopCount = -1;
  21239. this.sprite = null;
  21240. this.mousePositionX = 0;
  21241. this.mousePositionY = 0;
  21242. }
  21243. }
  21244. class Touch {
  21245. constructor() {
  21246. this._indexInList = -1;
  21247. this._identifier = -1;
  21248. this._position = new Vector2();
  21249. }
  21250. get identifier() {
  21251. return this._identifier;
  21252. }
  21253. get position() {
  21254. return this._position;
  21255. }
  21256. _getIndexInList() {
  21257. return this._indexInList;
  21258. }
  21259. _setIndexInList(index) {
  21260. this._indexInList = index;
  21261. }
  21262. }
  21263. class HitResult {
  21264. constructor() {
  21265. this.succeeded = false;
  21266. this.collider = null;
  21267. this.point = new Vector3();
  21268. this.normal = new Vector3();
  21269. this.hitFraction = 0;
  21270. }
  21271. }
  21272. class PhysicsUpdateList extends SingletonList {
  21273. constructor() {
  21274. super();
  21275. }
  21276. add(element) {
  21277. var index = element._inPhysicUpdateListIndex;
  21278. if (index !== -1)
  21279. throw "PhysicsUpdateList:element has in PhysicsUpdateList.";
  21280. this._add(element);
  21281. element._inPhysicUpdateListIndex = this.length++;
  21282. }
  21283. remove(element) {
  21284. var index = element._inPhysicUpdateListIndex;
  21285. this.length--;
  21286. if (index !== this.length) {
  21287. var end = this.elements[this.length];
  21288. this.elements[index] = end;
  21289. end._inPhysicUpdateListIndex = index;
  21290. }
  21291. element._inPhysicUpdateListIndex = -1;
  21292. }
  21293. }
  21294. class ContactPoint {
  21295. constructor() {
  21296. this._idCounter = 0;
  21297. this.colliderA = null;
  21298. this.colliderB = null;
  21299. this.distance = 0;
  21300. this.normal = new Vector3();
  21301. this.positionOnA = new Vector3();
  21302. this.positionOnB = new Vector3();
  21303. this._id = ++this._idCounter;
  21304. }
  21305. }
  21306. class Collision {
  21307. constructor() {
  21308. this._lastUpdateFrame = -2147483648;
  21309. this._updateFrame = -2147483648;
  21310. this._isTrigger = false;
  21311. this.contacts = [];
  21312. }
  21313. _setUpdateFrame(farme) {
  21314. this._lastUpdateFrame = this._updateFrame;
  21315. this._updateFrame = farme;
  21316. }
  21317. }
  21318. class CollisionTool {
  21319. constructor() {
  21320. this._hitResultsPoolIndex = 0;
  21321. this._hitResultsPool = [];
  21322. this._contactPonintsPoolIndex = 0;
  21323. this._contactPointsPool = [];
  21324. this._collisionsPool = [];
  21325. this._collisions = {};
  21326. }
  21327. getHitResult() {
  21328. var hitResult = this._hitResultsPool[this._hitResultsPoolIndex++];
  21329. if (!hitResult) {
  21330. hitResult = new HitResult();
  21331. this._hitResultsPool.push(hitResult);
  21332. }
  21333. return hitResult;
  21334. }
  21335. recoverAllHitResultsPool() {
  21336. this._hitResultsPoolIndex = 0;
  21337. }
  21338. getContactPoints() {
  21339. var contactPoint = this._contactPointsPool[this._contactPonintsPoolIndex++];
  21340. if (!contactPoint) {
  21341. contactPoint = new ContactPoint();
  21342. this._contactPointsPool.push(contactPoint);
  21343. }
  21344. return contactPoint;
  21345. }
  21346. recoverAllContactPointsPool() {
  21347. this._contactPonintsPoolIndex = 0;
  21348. }
  21349. getCollision(physicComponentA, physicComponentB) {
  21350. var collision;
  21351. var idA = physicComponentA.id;
  21352. var idB = physicComponentB.id;
  21353. var subCollisionFirst = this._collisions[idA];
  21354. if (subCollisionFirst)
  21355. collision = subCollisionFirst[idB];
  21356. if (!collision) {
  21357. if (!subCollisionFirst) {
  21358. subCollisionFirst = {};
  21359. this._collisions[idA] = subCollisionFirst;
  21360. }
  21361. collision = this._collisionsPool.length === 0 ? new Collision() : this._collisionsPool.pop();
  21362. collision._colliderA = physicComponentA;
  21363. collision._colliderB = physicComponentB;
  21364. subCollisionFirst[idB] = collision;
  21365. }
  21366. return collision;
  21367. }
  21368. recoverCollision(collision) {
  21369. var idA = collision._colliderA.id;
  21370. var idB = collision._colliderB.id;
  21371. this._collisions[idA][idB] = null;
  21372. this._collisionsPool.push(collision);
  21373. }
  21374. garbageCollection() {
  21375. this._hitResultsPoolIndex = 0;
  21376. this._hitResultsPool.length = 0;
  21377. this._contactPonintsPoolIndex = 0;
  21378. this._contactPointsPool.length = 0;
  21379. this._collisionsPool.length = 0;
  21380. for (var subCollisionsKey in this._collisionsPool) {
  21381. var subCollisions = this._collisionsPool[subCollisionsKey];
  21382. var wholeDelete = true;
  21383. for (var collisionKey in subCollisions) {
  21384. if (subCollisions[collisionKey])
  21385. wholeDelete = false;
  21386. else
  21387. delete subCollisions[collisionKey];
  21388. }
  21389. if (wholeDelete)
  21390. delete this._collisionsPool[subCollisionsKey];
  21391. }
  21392. }
  21393. }
  21394. class ColliderShape {
  21395. constructor() {
  21396. this._scale = new Vector3(1, 1, 1);
  21397. this._centerMatrix = new Matrix4x4();
  21398. this._attatched = false;
  21399. this._indexInCompound = -1;
  21400. this._compoundParent = null;
  21401. this._attatchedCollisionObject = null;
  21402. this._referenceCount = 0;
  21403. this._localOffset = new Vector3(0, 0, 0);
  21404. this._localRotation = new Quaternion(0, 0, 0, 1);
  21405. this.needsCustomCollisionCallback = false;
  21406. }
  21407. static __init__() {
  21408. var bt = Physics3D._bullet;
  21409. ColliderShape._btScale = bt.btVector3_create(1, 1, 1);
  21410. ColliderShape._btVector30 = bt.btVector3_create(0, 0, 0);
  21411. ColliderShape._btQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  21412. ColliderShape._btTransform0 = bt.btTransform_create();
  21413. }
  21414. static _createAffineTransformation(trans, rot, outE) {
  21415. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  21416. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  21417. var wx = w * x2, wy = w * y2, wz = w * z2;
  21418. outE[0] = (1 - (yy + zz));
  21419. outE[1] = (xy + wz);
  21420. outE[2] = (xz - wy);
  21421. outE[3] = 0;
  21422. outE[4] = (xy - wz);
  21423. outE[5] = (1 - (xx + zz));
  21424. outE[6] = (yz + wx);
  21425. outE[7] = 0;
  21426. outE[8] = (xz + wy);
  21427. outE[9] = (yz - wx);
  21428. outE[10] = (1 - (xx + yy));
  21429. outE[11] = 0;
  21430. outE[12] = trans.x;
  21431. outE[13] = trans.y;
  21432. outE[14] = trans.z;
  21433. outE[15] = 1;
  21434. }
  21435. get type() {
  21436. return this._type;
  21437. }
  21438. get localOffset() {
  21439. return this._localOffset;
  21440. }
  21441. set localOffset(value) {
  21442. this._localOffset = value;
  21443. if (this._compoundParent)
  21444. this._compoundParent._updateChildTransform(this);
  21445. }
  21446. get localRotation() {
  21447. return this._localRotation;
  21448. }
  21449. set localRotation(value) {
  21450. this._localRotation = value;
  21451. if (this._compoundParent)
  21452. this._compoundParent._updateChildTransform(this);
  21453. }
  21454. _setScale(value) {
  21455. if (this._compoundParent) {
  21456. this.updateLocalTransformations();
  21457. }
  21458. else {
  21459. var bt = Physics3D._bullet;
  21460. bt.btVector3_setValue(ColliderShape._btScale, value.x, value.y, value.z);
  21461. bt.btCollisionShape_setLocalScaling(this._btShape, ColliderShape._btScale);
  21462. }
  21463. }
  21464. _addReference() {
  21465. this._referenceCount++;
  21466. }
  21467. _removeReference() {
  21468. this._referenceCount--;
  21469. }
  21470. updateLocalTransformations() {
  21471. if (this._compoundParent) {
  21472. var offset = ColliderShape._tempVector30;
  21473. Vector3.multiply(this.localOffset, this._scale, offset);
  21474. ColliderShape._createAffineTransformation(offset, this.localRotation, this._centerMatrix.elements);
  21475. }
  21476. else {
  21477. ColliderShape._createAffineTransformation(this.localOffset, this.localRotation, this._centerMatrix.elements);
  21478. }
  21479. }
  21480. cloneTo(destObject) {
  21481. var destColliderShape = destObject;
  21482. this._localOffset.cloneTo(destColliderShape.localOffset);
  21483. this._localRotation.cloneTo(destColliderShape.localRotation);
  21484. destColliderShape.localOffset = destColliderShape.localOffset;
  21485. destColliderShape.localRotation = destColliderShape.localRotation;
  21486. }
  21487. clone() {
  21488. return null;
  21489. }
  21490. destroy() {
  21491. if (this._btShape) {
  21492. Physics3D._bullet.btCollisionShape_destroy(this._btShape);
  21493. this._btShape = null;
  21494. }
  21495. }
  21496. }
  21497. ColliderShape.SHAPEORIENTATION_UPX = 0;
  21498. ColliderShape.SHAPEORIENTATION_UPY = 1;
  21499. ColliderShape.SHAPEORIENTATION_UPZ = 2;
  21500. ColliderShape.SHAPETYPES_BOX = 0;
  21501. ColliderShape.SHAPETYPES_SPHERE = 1;
  21502. ColliderShape.SHAPETYPES_CYLINDER = 2;
  21503. ColliderShape.SHAPETYPES_CAPSULE = 3;
  21504. ColliderShape.SHAPETYPES_CONVEXHULL = 4;
  21505. ColliderShape.SHAPETYPES_COMPOUND = 5;
  21506. ColliderShape.SHAPETYPES_STATICPLANE = 6;
  21507. ColliderShape.SHAPETYPES_CONE = 7;
  21508. ColliderShape._tempVector30 = new Vector3();
  21509. class BoxColliderShape extends ColliderShape {
  21510. static __init__() {
  21511. BoxColliderShape._btSize = Physics3D._bullet.btVector3_create(0, 0, 0);
  21512. }
  21513. get sizeX() {
  21514. return this._sizeX;
  21515. }
  21516. get sizeY() {
  21517. return this._sizeY;
  21518. }
  21519. get sizeZ() {
  21520. return this._sizeZ;
  21521. }
  21522. constructor(sizeX = 1.0, sizeY = 1.0, sizeZ = 1.0) {
  21523. super();
  21524. this._sizeX = sizeX;
  21525. this._sizeY = sizeY;
  21526. this._sizeZ = sizeZ;
  21527. this._type = ColliderShape.SHAPETYPES_BOX;
  21528. var bt = Physics3D._bullet;
  21529. bt.btVector3_setValue(BoxColliderShape._btSize, sizeX / 2, sizeY / 2, sizeZ / 2);
  21530. this._btShape = bt.btBoxShape_create(BoxColliderShape._btSize);
  21531. }
  21532. clone() {
  21533. var dest = new BoxColliderShape(this._sizeX, this._sizeY, this._sizeZ);
  21534. this.cloneTo(dest);
  21535. return dest;
  21536. }
  21537. }
  21538. class CapsuleColliderShape extends ColliderShape {
  21539. constructor(radius = 0.5, length = 1.25, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  21540. super();
  21541. this._radius = radius;
  21542. this._length = length;
  21543. this._orientation = orientation;
  21544. this._type = ColliderShape.SHAPETYPES_CAPSULE;
  21545. var bt = Physics3D._bullet;
  21546. switch (orientation) {
  21547. case ColliderShape.SHAPEORIENTATION_UPX:
  21548. this._btShape = bt.btCapsuleShapeX_create(radius, length - radius * 2);
  21549. break;
  21550. case ColliderShape.SHAPEORIENTATION_UPY:
  21551. this._btShape = bt.btCapsuleShape_create(radius, length - radius * 2);
  21552. break;
  21553. case ColliderShape.SHAPEORIENTATION_UPZ:
  21554. this._btShape = bt.btCapsuleShapeZ_create(radius, length - radius * 2);
  21555. break;
  21556. default:
  21557. throw "CapsuleColliderShape:unknown orientation.";
  21558. }
  21559. }
  21560. get radius() {
  21561. return this._radius;
  21562. }
  21563. get length() {
  21564. return this._length;
  21565. }
  21566. get orientation() {
  21567. return this._orientation;
  21568. }
  21569. _setScale(value) {
  21570. var fixScale = CapsuleColliderShape._tempVector30;
  21571. switch (this.orientation) {
  21572. case ColliderShape.SHAPEORIENTATION_UPX:
  21573. fixScale.x = value.x;
  21574. fixScale.y = fixScale.z = Math.max(value.y, value.z);
  21575. break;
  21576. case ColliderShape.SHAPEORIENTATION_UPY:
  21577. fixScale.y = value.y;
  21578. fixScale.x = fixScale.z = Math.max(value.x, value.z);
  21579. break;
  21580. case ColliderShape.SHAPEORIENTATION_UPZ:
  21581. fixScale.z = value.z;
  21582. fixScale.x = fixScale.y = Math.max(value.x, value.y);
  21583. break;
  21584. default:
  21585. throw "CapsuleColliderShape:unknown orientation.";
  21586. }
  21587. super._setScale(fixScale);
  21588. }
  21589. clone() {
  21590. var dest = new CapsuleColliderShape(this._radius, this._length, this._orientation);
  21591. this.cloneTo(dest);
  21592. return dest;
  21593. }
  21594. }
  21595. CapsuleColliderShape._tempVector30 = new Vector3();
  21596. class CompoundColliderShape extends ColliderShape {
  21597. constructor() {
  21598. super();
  21599. this._childColliderShapes = [];
  21600. this._type = ColliderShape.SHAPETYPES_COMPOUND;
  21601. this._btShape = Physics3D._bullet.btCompoundShape_create();
  21602. }
  21603. static __init__() {
  21604. var bt = Physics3D._bullet;
  21605. CompoundColliderShape._btVector3One = bt.btVector3_create(1, 1, 1);
  21606. CompoundColliderShape._btTransform = bt.btTransform_create();
  21607. CompoundColliderShape._btOffset = bt.btVector3_create(0, 0, 0);
  21608. CompoundColliderShape._btRotation = bt.btQuaternion_create(0, 0, 0, 1);
  21609. }
  21610. _clearChildShape(shape) {
  21611. shape._attatched = false;
  21612. shape._compoundParent = null;
  21613. shape._indexInCompound = -1;
  21614. }
  21615. _addReference() {
  21616. }
  21617. _removeReference() {
  21618. }
  21619. _updateChildTransform(shape) {
  21620. var bt = Physics3D._bullet;
  21621. var offset = shape.localOffset;
  21622. var rotation = shape.localRotation;
  21623. var btOffset = ColliderShape._btVector30;
  21624. var btQuaternion = ColliderShape._btQuaternion0;
  21625. var btTransform = ColliderShape._btTransform0;
  21626. bt.btVector3_setValue(btOffset, -offset.x, offset.y, offset.z);
  21627. bt.btQuaternion_setValue(btQuaternion, -rotation.x, rotation.y, rotation.z, -rotation.w);
  21628. bt.btTransform_setOrigin(btTransform, btOffset);
  21629. bt.btTransform_setRotation(btTransform, btQuaternion);
  21630. bt.btCompoundShape_updateChildTransform(this._btShape, shape._indexInCompound, btTransform, true);
  21631. }
  21632. addChildShape(shape) {
  21633. if (shape._attatched)
  21634. throw "CompoundColliderShape: this shape has attatched to other entity.";
  21635. shape._attatched = true;
  21636. shape._compoundParent = this;
  21637. shape._indexInCompound = this._childColliderShapes.length;
  21638. this._childColliderShapes.push(shape);
  21639. var offset = shape.localOffset;
  21640. var rotation = shape.localRotation;
  21641. var bt = Physics3D._bullet;
  21642. bt.btVector3_setValue(CompoundColliderShape._btOffset, -offset.x, offset.y, offset.z);
  21643. bt.btQuaternion_setValue(CompoundColliderShape._btRotation, -rotation.x, rotation.y, rotation.z, -rotation.w);
  21644. bt.btTransform_setOrigin(CompoundColliderShape._btTransform, CompoundColliderShape._btOffset);
  21645. bt.btTransform_setRotation(CompoundColliderShape._btTransform, CompoundColliderShape._btRotation);
  21646. var btScale = bt.btCollisionShape_getLocalScaling(this._btShape);
  21647. bt.btCollisionShape_setLocalScaling(this._btShape, CompoundColliderShape._btVector3One);
  21648. bt.btCompoundShape_addChildShape(this._btShape, CompoundColliderShape._btTransform, shape._btShape);
  21649. bt.btCollisionShape_setLocalScaling(this._btShape, btScale);
  21650. (this._attatchedCollisionObject) && (this._attatchedCollisionObject.colliderShape = this);
  21651. }
  21652. removeChildShape(shape) {
  21653. if (shape._compoundParent === this) {
  21654. var index = shape._indexInCompound;
  21655. this._clearChildShape(shape);
  21656. var endShape = this._childColliderShapes[this._childColliderShapes.length - 1];
  21657. endShape._indexInCompound = index;
  21658. this._childColliderShapes[index] = endShape;
  21659. this._childColliderShapes.pop();
  21660. Physics3D._bullet.btCompoundShape_removeChildShapeByIndex(this._btShape, index);
  21661. }
  21662. }
  21663. clearChildShape() {
  21664. for (var i = 0, n = this._childColliderShapes.length; i < n; i++) {
  21665. this._clearChildShape(this._childColliderShapes[i]);
  21666. Physics3D._bullet.btCompoundShape_removeChildShapeByIndex(this._btShape, 0);
  21667. }
  21668. this._childColliderShapes.length = 0;
  21669. }
  21670. getChildShapeCount() {
  21671. return this._childColliderShapes.length;
  21672. }
  21673. cloneTo(destObject) {
  21674. var destCompoundColliderShape = destObject;
  21675. destCompoundColliderShape.clearChildShape();
  21676. for (var i = 0, n = this._childColliderShapes.length; i < n; i++)
  21677. destCompoundColliderShape.addChildShape(this._childColliderShapes[i].clone());
  21678. }
  21679. clone() {
  21680. var dest = new CompoundColliderShape();
  21681. this.cloneTo(dest);
  21682. return dest;
  21683. }
  21684. destroy() {
  21685. super.destroy();
  21686. for (var i = 0, n = this._childColliderShapes.length; i < n; i++) {
  21687. var childShape = this._childColliderShapes[i];
  21688. if (childShape._referenceCount === 0)
  21689. childShape.destroy();
  21690. }
  21691. }
  21692. }
  21693. class ConeColliderShape extends ColliderShape {
  21694. constructor(radius = 0.5, height = 1.0, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  21695. super();
  21696. this._radius = 1;
  21697. this._height = 0.5;
  21698. this._radius = radius;
  21699. this._height = height;
  21700. this._orientation = orientation;
  21701. this._type = ColliderShape.SHAPETYPES_CYLINDER;
  21702. var bt = Physics3D._bullet;
  21703. switch (orientation) {
  21704. case ColliderShape.SHAPEORIENTATION_UPX:
  21705. this._btShape = bt.btConeShapeX_create(radius, height);
  21706. break;
  21707. case ColliderShape.SHAPEORIENTATION_UPY:
  21708. this._btShape = bt.btConeShape_create(radius, height);
  21709. break;
  21710. case ColliderShape.SHAPEORIENTATION_UPZ:
  21711. this._btShape = bt.btConeShapeZ_create(radius, height);
  21712. break;
  21713. default:
  21714. throw "ConeColliderShape:unknown orientation.";
  21715. }
  21716. }
  21717. get radius() {
  21718. return this._radius;
  21719. }
  21720. get height() {
  21721. return this._height;
  21722. }
  21723. get orientation() {
  21724. return this._orientation;
  21725. }
  21726. clone() {
  21727. var dest = new ConeColliderShape(this._radius, this._height, this._orientation);
  21728. this.cloneTo(dest);
  21729. return dest;
  21730. }
  21731. }
  21732. class CylinderColliderShape extends ColliderShape {
  21733. constructor(radius = 0.5, height = 1.0, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  21734. super();
  21735. this._radius = 1;
  21736. this._height = 0.5;
  21737. this._radius = radius;
  21738. this._height = height;
  21739. this._orientation = orientation;
  21740. this._type = ColliderShape.SHAPETYPES_CYLINDER;
  21741. var bt = Physics3D._bullet;
  21742. switch (orientation) {
  21743. case ColliderShape.SHAPEORIENTATION_UPX:
  21744. bt.btVector3_setValue(CylinderColliderShape._btSize, height / 2, radius, radius);
  21745. this._btShape = bt.btCylinderShapeX_create(CylinderColliderShape._btSize);
  21746. break;
  21747. case ColliderShape.SHAPEORIENTATION_UPY:
  21748. bt.btVector3_setValue(CylinderColliderShape._btSize, radius, height / 2, radius);
  21749. this._btShape = bt.btCylinderShape_create(CylinderColliderShape._btSize);
  21750. break;
  21751. case ColliderShape.SHAPEORIENTATION_UPZ:
  21752. bt.btVector3_setValue(CylinderColliderShape._btSize, radius, radius, height / 2);
  21753. this._btShape = bt.btCylinderShapeZ_create(CylinderColliderShape._btSize);
  21754. break;
  21755. default:
  21756. throw "CapsuleColliderShape:unknown orientation.";
  21757. }
  21758. }
  21759. static __init__() {
  21760. CylinderColliderShape._btSize = Physics3D._bullet.btVector3_create(0, 0, 0);
  21761. }
  21762. get radius() {
  21763. return this._radius;
  21764. }
  21765. get height() {
  21766. return this._height;
  21767. }
  21768. get orientation() {
  21769. return this._orientation;
  21770. }
  21771. clone() {
  21772. var dest = new CylinderColliderShape(this._radius, this._height, this._orientation);
  21773. this.cloneTo(dest);
  21774. return dest;
  21775. }
  21776. }
  21777. class MeshColliderShape extends ColliderShape {
  21778. constructor() {
  21779. super();
  21780. this._mesh = null;
  21781. this._convex = false;
  21782. }
  21783. get mesh() {
  21784. return this._mesh;
  21785. }
  21786. set mesh(value) {
  21787. if (this._mesh !== value) {
  21788. var bt = Physics3D._bullet;
  21789. if (this._mesh) {
  21790. bt.destroy(this._btShape);
  21791. }
  21792. if (value) {
  21793. this._btShape = bt.btGImpactMeshShape_create(value._getPhysicMesh());
  21794. bt.btGImpactShapeInterface_updateBound(this._btShape);
  21795. }
  21796. this._mesh = value;
  21797. }
  21798. }
  21799. get convex() {
  21800. return this._convex;
  21801. }
  21802. set convex(value) {
  21803. this._convex = value;
  21804. }
  21805. _setScale(value) {
  21806. if (this._compoundParent) {
  21807. this.updateLocalTransformations();
  21808. }
  21809. else {
  21810. var bt = Physics3D._bullet;
  21811. bt.btVector3_setValue(ColliderShape._btScale, value.x, value.y, value.z);
  21812. bt.btCollisionShape_setLocalScaling(this._btShape, ColliderShape._btScale);
  21813. bt.btGImpactShapeInterface_updateBound(this._btShape);
  21814. }
  21815. }
  21816. cloneTo(destObject) {
  21817. var destMeshCollider = destObject;
  21818. destMeshCollider.convex = this._convex;
  21819. destMeshCollider.mesh = this._mesh;
  21820. super.cloneTo(destObject);
  21821. }
  21822. clone() {
  21823. var dest = new MeshColliderShape();
  21824. this.cloneTo(dest);
  21825. return dest;
  21826. }
  21827. destroy() {
  21828. if (this._btShape) {
  21829. Physics3D._bullet.btCollisionShape_destroy(this._btShape);
  21830. this._btShape = null;
  21831. }
  21832. }
  21833. }
  21834. class SphereColliderShape extends ColliderShape {
  21835. get radius() {
  21836. return this._radius;
  21837. }
  21838. constructor(radius = 0.5) {
  21839. super();
  21840. this._radius = radius;
  21841. this._type = ColliderShape.SHAPETYPES_SPHERE;
  21842. this._btShape = Physics3D._bullet.btSphereShape_create(radius);
  21843. }
  21844. clone() {
  21845. var dest = new SphereColliderShape(this._radius);
  21846. this.cloneTo(dest);
  21847. return dest;
  21848. }
  21849. }
  21850. class PhysicsComponent extends Laya.Component {
  21851. constructor(collisionGroup, canCollideWith) {
  21852. super();
  21853. this._restitution = 0.0;
  21854. this._friction = 0.5;
  21855. this._rollingFriction = 0.0;
  21856. this._ccdMotionThreshold = 0.0;
  21857. this._ccdSweptSphereRadius = 0.0;
  21858. this._collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER;
  21859. this._canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER;
  21860. this._colliderShape = null;
  21861. this._transformFlag = 2147483647;
  21862. this._enableProcessCollisions = true;
  21863. this._inPhysicUpdateListIndex = -1;
  21864. this.canScaleShape = true;
  21865. this._collisionGroup = collisionGroup;
  21866. this._canCollideWith = canCollideWith;
  21867. PhysicsComponent._physicObjectsMap[this.id] = this;
  21868. }
  21869. static __init__() {
  21870. var bt = Physics3D._bullet;
  21871. PhysicsComponent._btVector30 = bt.btVector3_create(0, 0, 0);
  21872. PhysicsComponent._btQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  21873. }
  21874. static _createAffineTransformationArray(tranX, tranY, tranZ, rotX, rotY, rotZ, rotW, scale, outE) {
  21875. var x2 = rotX + rotX, y2 = rotY + rotY, z2 = rotZ + rotZ;
  21876. var xx = rotX * x2, xy = rotX * y2, xz = rotX * z2, yy = rotY * y2, yz = rotY * z2, zz = rotZ * z2;
  21877. var wx = rotW * x2, wy = rotW * y2, wz = rotW * z2, sx = scale[0], sy = scale[1], sz = scale[2];
  21878. outE[0] = (1 - (yy + zz)) * sx;
  21879. outE[1] = (xy + wz) * sx;
  21880. outE[2] = (xz - wy) * sx;
  21881. outE[3] = 0;
  21882. outE[4] = (xy - wz) * sy;
  21883. outE[5] = (1 - (xx + zz)) * sy;
  21884. outE[6] = (yz + wx) * sy;
  21885. outE[7] = 0;
  21886. outE[8] = (xz + wy) * sz;
  21887. outE[9] = (yz - wx) * sz;
  21888. outE[10] = (1 - (xx + yy)) * sz;
  21889. outE[11] = 0;
  21890. outE[12] = tranX;
  21891. outE[13] = tranY;
  21892. outE[14] = tranZ;
  21893. outE[15] = 1;
  21894. }
  21895. static _creatShape(shapeData) {
  21896. var colliderShape;
  21897. switch (shapeData.type) {
  21898. case "BoxColliderShape":
  21899. var sizeData = shapeData.size;
  21900. colliderShape = sizeData ? new BoxColliderShape(sizeData[0], sizeData[1], sizeData[2]) : new BoxColliderShape();
  21901. break;
  21902. case "SphereColliderShape":
  21903. colliderShape = new SphereColliderShape(shapeData.radius);
  21904. break;
  21905. case "CapsuleColliderShape":
  21906. colliderShape = new CapsuleColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  21907. break;
  21908. case "MeshColliderShape":
  21909. var meshCollider = new MeshColliderShape();
  21910. shapeData.mesh && (meshCollider.mesh = Laya.Loader.getRes(shapeData.mesh));
  21911. colliderShape = meshCollider;
  21912. break;
  21913. case "ConeColliderShape":
  21914. colliderShape = new ConeColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  21915. break;
  21916. case "CylinderColliderShape":
  21917. colliderShape = new CylinderColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  21918. break;
  21919. default:
  21920. throw "unknown shape type.";
  21921. }
  21922. if (shapeData.center) {
  21923. var localOffset = colliderShape.localOffset;
  21924. localOffset.fromArray(shapeData.center);
  21925. colliderShape.localOffset = localOffset;
  21926. }
  21927. return colliderShape;
  21928. }
  21929. static physicVector3TransformQuat(source, qx, qy, qz, qw, out) {
  21930. var x = source.x, y = source.y, z = source.z, ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  21931. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  21932. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  21933. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  21934. }
  21935. static physicQuaternionMultiply(lx, ly, lz, lw, right, out) {
  21936. var rx = right.x;
  21937. var ry = right.y;
  21938. var rz = right.z;
  21939. var rw = right.w;
  21940. var a = (ly * rz - lz * ry);
  21941. var b = (lz * rx - lx * rz);
  21942. var c = (lx * ry - ly * rx);
  21943. var d = (lx * rx + ly * ry + lz * rz);
  21944. out.x = (lx * rw + rx * lw) + a;
  21945. out.y = (ly * rw + ry * lw) + b;
  21946. out.z = (lz * rw + rz * lw) + c;
  21947. out.w = lw * rw - d;
  21948. }
  21949. get restitution() {
  21950. return this._restitution;
  21951. }
  21952. set restitution(value) {
  21953. this._restitution = value;
  21954. this._btColliderObject && Physics3D._bullet.btCollisionObject_setRestitution(this._btColliderObject, value);
  21955. }
  21956. get friction() {
  21957. return this._friction;
  21958. }
  21959. set friction(value) {
  21960. this._friction = value;
  21961. this._btColliderObject && Physics3D._bullet.btCollisionObject_setFriction(this._btColliderObject, value);
  21962. }
  21963. get rollingFriction() {
  21964. return this._rollingFriction;
  21965. }
  21966. set rollingFriction(value) {
  21967. this._rollingFriction = value;
  21968. this._btColliderObject && Physics3D._bullet.btCollisionObject_setRollingFriction(this._btColliderObject, value);
  21969. }
  21970. get ccdMotionThreshold() {
  21971. return this._ccdMotionThreshold;
  21972. }
  21973. set ccdMotionThreshold(value) {
  21974. this._ccdMotionThreshold = value;
  21975. this._btColliderObject && Physics3D._bullet.btCollisionObject_setCcdMotionThreshold(this._btColliderObject, value);
  21976. }
  21977. get ccdSweptSphereRadius() {
  21978. return this._ccdSweptSphereRadius;
  21979. }
  21980. set ccdSweptSphereRadius(value) {
  21981. this._ccdSweptSphereRadius = value;
  21982. this._btColliderObject && Physics3D._bullet.btCollisionObject_setCcdSweptSphereRadius(this._btColliderObject, value);
  21983. }
  21984. get isActive() {
  21985. return this._btColliderObject ? Physics3D._bullet.btCollisionObject_isActive(this._btColliderObject) : false;
  21986. }
  21987. get enabled() {
  21988. return super.enabled;
  21989. }
  21990. set enabled(value) {
  21991. if (this._enabled != value) {
  21992. if (this._simulation && this._colliderShape) {
  21993. if (value) {
  21994. this._derivePhysicsTransformation(true);
  21995. this._addToSimulation();
  21996. }
  21997. else {
  21998. this._removeFromSimulation();
  21999. }
  22000. }
  22001. super.enabled = value;
  22002. }
  22003. }
  22004. get colliderShape() {
  22005. return this._colliderShape;
  22006. }
  22007. set colliderShape(value) {
  22008. var lastColliderShape = this._colliderShape;
  22009. if (lastColliderShape) {
  22010. lastColliderShape._attatched = false;
  22011. lastColliderShape._attatchedCollisionObject = null;
  22012. }
  22013. this._colliderShape = value;
  22014. if (value) {
  22015. if (value._attatched) {
  22016. throw "PhysicsComponent: this shape has attatched to other entity.";
  22017. }
  22018. else {
  22019. value._attatched = true;
  22020. value._attatchedCollisionObject = this;
  22021. }
  22022. if (this._btColliderObject) {
  22023. Physics3D._bullet.btCollisionObject_setCollisionShape(this._btColliderObject, value._btShape);
  22024. var canInSimulation = this._simulation && this._enabled;
  22025. (canInSimulation && lastColliderShape) && (this._removeFromSimulation());
  22026. this._onShapeChange(value);
  22027. if (canInSimulation) {
  22028. this._derivePhysicsTransformation(true);
  22029. this._addToSimulation();
  22030. }
  22031. }
  22032. }
  22033. else {
  22034. if (this._simulation && this._enabled)
  22035. lastColliderShape && this._removeFromSimulation();
  22036. }
  22037. }
  22038. get simulation() {
  22039. return this._simulation;
  22040. }
  22041. get collisionGroup() {
  22042. return this._collisionGroup;
  22043. }
  22044. set collisionGroup(value) {
  22045. if (this._collisionGroup !== value) {
  22046. this._collisionGroup = value;
  22047. if (this._simulation && this._colliderShape && this._enabled) {
  22048. this._removeFromSimulation();
  22049. this._addToSimulation();
  22050. }
  22051. }
  22052. }
  22053. get canCollideWith() {
  22054. return this._canCollideWith;
  22055. }
  22056. set canCollideWith(value) {
  22057. if (this._canCollideWith !== value) {
  22058. this._canCollideWith = value;
  22059. if (this._simulation && this._colliderShape && this._enabled) {
  22060. this._removeFromSimulation();
  22061. this._addToSimulation();
  22062. }
  22063. }
  22064. }
  22065. _parseShape(shapesData) {
  22066. var shapeCount = shapesData.length;
  22067. if (shapeCount === 1) {
  22068. var shape = PhysicsComponent._creatShape(shapesData[0]);
  22069. this.colliderShape = shape;
  22070. }
  22071. else {
  22072. var compoundShape = new CompoundColliderShape();
  22073. for (var i = 0; i < shapeCount; i++) {
  22074. shape = PhysicsComponent._creatShape(shapesData[i]);
  22075. compoundShape.addChildShape(shape);
  22076. }
  22077. this.colliderShape = compoundShape;
  22078. }
  22079. }
  22080. _onScaleChange(scale) {
  22081. this._colliderShape._setScale(scale);
  22082. }
  22083. _onEnable() {
  22084. this._simulation = this.owner._scene.physicsSimulation;
  22085. Physics3D._bullet.btCollisionObject_setContactProcessingThreshold(this._btColliderObject, 1e30);
  22086. if (this._colliderShape && this._enabled) {
  22087. this._derivePhysicsTransformation(true);
  22088. this._addToSimulation();
  22089. }
  22090. }
  22091. _onDisable() {
  22092. if (this._colliderShape && this._enabled) {
  22093. this._removeFromSimulation();
  22094. (this._inPhysicUpdateListIndex !== -1) && (this._simulation._physicsUpdateList.remove(this));
  22095. }
  22096. this._simulation = null;
  22097. }
  22098. _onDestroy() {
  22099. delete PhysicsComponent._physicObjectsMap[this.id];
  22100. Physics3D._bullet.btCollisionObject_destroy(this._btColliderObject);
  22101. this._colliderShape.destroy();
  22102. super._onDestroy();
  22103. this._btColliderObject = null;
  22104. this._colliderShape = null;
  22105. this._simulation = null;
  22106. this.owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  22107. }
  22108. _isValid() {
  22109. return this._simulation && this._colliderShape && this._enabled;
  22110. }
  22111. _parse(data) {
  22112. (data.collisionGroup != null) && (this.collisionGroup = data.collisionGroup);
  22113. (data.canCollideWith != null) && (this.canCollideWith = data.canCollideWith);
  22114. (data.ccdMotionThreshold != null) && (this.ccdMotionThreshold = data.ccdMotionThreshold);
  22115. (data.ccdSweptSphereRadius != null) && (this.ccdSweptSphereRadius = data.ccdSweptSphereRadius);
  22116. }
  22117. _setTransformFlag(type, value) {
  22118. if (value)
  22119. this._transformFlag |= type;
  22120. else
  22121. this._transformFlag &= ~type;
  22122. }
  22123. _getTransformFlag(type) {
  22124. return (this._transformFlag & type) != 0;
  22125. }
  22126. _addToSimulation() {
  22127. }
  22128. _removeFromSimulation() {
  22129. }
  22130. _derivePhysicsTransformation(force) {
  22131. this._innerDerivePhysicsTransformation(Physics3D._bullet.btCollisionObject_getWorldTransform(this._btColliderObject), force);
  22132. }
  22133. _innerDerivePhysicsTransformation(physicTransformOut, force) {
  22134. var bt = Physics3D._bullet;
  22135. var transform = this.owner._transform;
  22136. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  22137. var shapeOffset = this._colliderShape.localOffset;
  22138. var position = transform.position;
  22139. var btPosition = PhysicsComponent._btVector30;
  22140. if (shapeOffset.x !== 0 || shapeOffset.y !== 0 || shapeOffset.z !== 0) {
  22141. var physicPosition = PhysicsComponent._tempVector30;
  22142. var worldMat = transform.worldMatrix;
  22143. Vector3.transformCoordinate(shapeOffset, worldMat, physicPosition);
  22144. bt.btVector3_setValue(btPosition, -physicPosition.x, physicPosition.y, physicPosition.z);
  22145. }
  22146. else {
  22147. bt.btVector3_setValue(btPosition, -position.x, position.y, position.z);
  22148. }
  22149. bt.btTransform_setOrigin(physicTransformOut, btPosition);
  22150. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  22151. }
  22152. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) {
  22153. var shapeRotation = this._colliderShape.localRotation;
  22154. var btRotation = PhysicsComponent._btQuaternion0;
  22155. var rotation = transform.rotation;
  22156. if (shapeRotation.x !== 0 || shapeRotation.y !== 0 || shapeRotation.z !== 0 || shapeRotation.w !== 1) {
  22157. var physicRotation = PhysicsComponent._tempQuaternion0;
  22158. PhysicsComponent.physicQuaternionMultiply(rotation.x, rotation.y, rotation.z, rotation.w, shapeRotation, physicRotation);
  22159. bt.btQuaternion_setValue(btRotation, -physicRotation.x, physicRotation.y, physicRotation.z, -physicRotation.w);
  22160. }
  22161. else {
  22162. bt.btQuaternion_setValue(btRotation, -rotation.x, rotation.y, rotation.z, -rotation.w);
  22163. }
  22164. bt.btTransform_setRotation(physicTransformOut, btRotation);
  22165. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  22166. }
  22167. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  22168. this._onScaleChange(transform.getWorldLossyScale());
  22169. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  22170. }
  22171. }
  22172. _updateTransformComponent(physicsTransform) {
  22173. var bt = Physics3D._bullet;
  22174. var localOffset = this._colliderShape.localOffset;
  22175. var localRotation = this._colliderShape.localRotation;
  22176. var transform = this.owner._transform;
  22177. var position = transform.position;
  22178. var rotation = transform.rotation;
  22179. var btPosition = bt.btTransform_getOrigin(physicsTransform);
  22180. var btRotation = bt.btTransform_getRotation(physicsTransform);
  22181. var btRotX = -bt.btQuaternion_x(btRotation);
  22182. var btRotY = bt.btQuaternion_y(btRotation);
  22183. var btRotZ = bt.btQuaternion_z(btRotation);
  22184. var btRotW = -bt.btQuaternion_w(btRotation);
  22185. if (localOffset.x !== 0 || localOffset.y !== 0 || localOffset.z !== 0) {
  22186. var rotShapePosition = PhysicsComponent._tempVector30;
  22187. PhysicsComponent.physicVector3TransformQuat(localOffset, btRotX, btRotY, btRotZ, btRotW, rotShapePosition);
  22188. position.x = -bt.btVector3_x(btPosition) - rotShapePosition.x;
  22189. position.y = bt.btVector3_y(btPosition) - rotShapePosition.y;
  22190. position.z = bt.btVector3_z(btPosition) - rotShapePosition.z;
  22191. }
  22192. else {
  22193. position.x = -bt.btVector3_x(btPosition);
  22194. position.y = bt.btVector3_y(btPosition);
  22195. position.z = bt.btVector3_z(btPosition);
  22196. }
  22197. transform.position = position;
  22198. if (localRotation.x !== 0 || localRotation.y !== 0 || localRotation.z !== 0 || localRotation.w !== 1) {
  22199. var invertShapeRotaion = PhysicsComponent._tempQuaternion0;
  22200. localRotation.invert(invertShapeRotaion);
  22201. PhysicsComponent.physicQuaternionMultiply(btRotX, btRotY, btRotZ, btRotW, invertShapeRotaion, rotation);
  22202. }
  22203. else {
  22204. rotation.x = btRotX;
  22205. rotation.y = btRotY;
  22206. rotation.z = btRotZ;
  22207. rotation.w = btRotW;
  22208. }
  22209. transform.rotation = rotation;
  22210. }
  22211. _onShapeChange(colShape) {
  22212. var btColObj = this._btColliderObject;
  22213. var bt = Physics3D._bullet;
  22214. var flags = bt.btCollisionObject_getCollisionFlags(btColObj);
  22215. if (colShape.needsCustomCollisionCallback) {
  22216. if ((flags & PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK) === 0)
  22217. bt.btCollisionObject_setCollisionFlags(btColObj, flags | PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK);
  22218. }
  22219. else {
  22220. if ((flags & PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK) > 0)
  22221. bt.btCollisionObject_setCollisionFlags(btColObj, flags ^ PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK);
  22222. }
  22223. }
  22224. _onAdded() {
  22225. this.enabled = this._enabled;
  22226. this.restitution = this._restitution;
  22227. this.friction = this._friction;
  22228. this.rollingFriction = this._rollingFriction;
  22229. this.ccdMotionThreshold = this._ccdMotionThreshold;
  22230. this.ccdSweptSphereRadius = this._ccdSweptSphereRadius;
  22231. this.owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  22232. }
  22233. _onTransformChanged(flag) {
  22234. if (PhysicsComponent._addUpdateList) {
  22235. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  22236. if (flag) {
  22237. this._transformFlag |= flag;
  22238. if (this._isValid() && this._inPhysicUpdateListIndex === -1)
  22239. this._simulation._physicsUpdateList.add(this);
  22240. }
  22241. }
  22242. }
  22243. _cloneTo(dest) {
  22244. var destPhysicsComponent = dest;
  22245. destPhysicsComponent.restitution = this._restitution;
  22246. destPhysicsComponent.friction = this._friction;
  22247. destPhysicsComponent.rollingFriction = this._rollingFriction;
  22248. destPhysicsComponent.ccdMotionThreshold = this._ccdMotionThreshold;
  22249. destPhysicsComponent.ccdSweptSphereRadius = this._ccdSweptSphereRadius;
  22250. destPhysicsComponent.collisionGroup = this._collisionGroup;
  22251. destPhysicsComponent.canCollideWith = this._canCollideWith;
  22252. destPhysicsComponent.canScaleShape = this.canScaleShape;
  22253. (this._colliderShape) && (destPhysicsComponent.colliderShape = this._colliderShape.clone());
  22254. }
  22255. }
  22256. PhysicsComponent.ACTIVATIONSTATE_ACTIVE_TAG = 1;
  22257. PhysicsComponent.ACTIVATIONSTATE_ISLAND_SLEEPING = 2;
  22258. PhysicsComponent.ACTIVATIONSTATE_WANTS_DEACTIVATION = 3;
  22259. PhysicsComponent.ACTIVATIONSTATE_DISABLE_DEACTIVATION = 4;
  22260. PhysicsComponent.ACTIVATIONSTATE_DISABLE_SIMULATION = 5;
  22261. PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT = 1;
  22262. PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT = 2;
  22263. PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE = 4;
  22264. PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK = 8;
  22265. PhysicsComponent.COLLISIONFLAGS_CHARACTER_OBJECT = 16;
  22266. PhysicsComponent.COLLISIONFLAGS_DISABLE_VISUALIZE_OBJECT = 32;
  22267. PhysicsComponent.COLLISIONFLAGS_DISABLE_SPU_COLLISION_PROCESSING = 64;
  22268. PhysicsComponent._tempVector30 = new Vector3();
  22269. PhysicsComponent._tempQuaternion0 = new Quaternion();
  22270. PhysicsComponent._tempQuaternion1 = new Quaternion();
  22271. PhysicsComponent._tempMatrix4x40 = new Matrix4x4();
  22272. PhysicsComponent._physicObjectsMap = {};
  22273. PhysicsComponent._addUpdateList = true;
  22274. class PhysicsSimulation {
  22275. constructor(configuration, flags = 0) {
  22276. this._gravity = new Vector3(0, -10, 0);
  22277. this._btVector3Zero = Physics3D._bullet.btVector3_create(0, 0, 0);
  22278. this._btDefaultQuaternion = Physics3D._bullet.btQuaternion_create(0, 0, 0, -1);
  22279. this._collisionsUtils = new CollisionTool();
  22280. this._previousFrameCollisions = [];
  22281. this._currentFrameCollisions = [];
  22282. this._physicsUpdateList = new PhysicsUpdateList();
  22283. this._characters = [];
  22284. this._updatedRigidbodies = 0;
  22285. this.maxSubSteps = 1;
  22286. this.fixedTimeStep = 1.0 / 60.0;
  22287. this.maxSubSteps = configuration.maxSubSteps;
  22288. this.fixedTimeStep = configuration.fixedTimeStep;
  22289. var bt = Physics3D._bullet;
  22290. this._btCollisionConfiguration = bt.btDefaultCollisionConfiguration_create();
  22291. this._btDispatcher = bt.btCollisionDispatcher_create(this._btCollisionConfiguration);
  22292. this._btBroadphase = bt.btDbvtBroadphase_create();
  22293. bt.btOverlappingPairCache_setInternalGhostPairCallback(bt.btDbvtBroadphase_getOverlappingPairCache(this._btBroadphase), bt.btGhostPairCallback_create());
  22294. var conFlags = configuration.flags;
  22295. if (conFlags & PhysicsSimulation.PHYSICSENGINEFLAGS_COLLISIONSONLY) {
  22296. this._btCollisionWorld = new bt.btCollisionWorld(this._btDispatcher, this._btBroadphase, this._btCollisionConfiguration);
  22297. }
  22298. else if (conFlags & PhysicsSimulation.PHYSICSENGINEFLAGS_SOFTBODYSUPPORT) {
  22299. throw "PhysicsSimulation:SoftBody processing is not yet available";
  22300. }
  22301. else {
  22302. var solver = bt.btSequentialImpulseConstraintSolver_create();
  22303. this._btDiscreteDynamicsWorld = bt.btDiscreteDynamicsWorld_create(this._btDispatcher, this._btBroadphase, solver, this._btCollisionConfiguration);
  22304. this._btCollisionWorld = this._btDiscreteDynamicsWorld;
  22305. }
  22306. if (this._btDiscreteDynamicsWorld) {
  22307. this._btSolverInfo = bt.btDynamicsWorld_getSolverInfo(this._btDiscreteDynamicsWorld);
  22308. this._btDispatchInfo = bt.btCollisionWorld_getDispatchInfo(this._btDiscreteDynamicsWorld);
  22309. }
  22310. this._btClosestRayResultCallback = bt.ClosestRayResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  22311. this._btAllHitsRayResultCallback = bt.AllHitsRayResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  22312. this._btClosestConvexResultCallback = bt.ClosestConvexResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  22313. this._btAllConvexResultCallback = bt.AllConvexResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  22314. bt.btGImpactCollisionAlgorithm_RegisterAlgorithm(this._btDispatcher);
  22315. }
  22316. static __init__() {
  22317. var bt = Physics3D._bullet;
  22318. PhysicsSimulation._btTempVector30 = bt.btVector3_create(0, 0, 0);
  22319. PhysicsSimulation._btTempVector31 = bt.btVector3_create(0, 0, 0);
  22320. PhysicsSimulation._btTempQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  22321. PhysicsSimulation._btTempQuaternion1 = bt.btQuaternion_create(0, 0, 0, 1);
  22322. PhysicsSimulation._btTempTransform0 = bt.btTransform_create();
  22323. PhysicsSimulation._btTempTransform1 = bt.btTransform_create();
  22324. }
  22325. static createConstraint() {
  22326. }
  22327. get continuousCollisionDetection() {
  22328. return Physics3D._bullet.btCollisionWorld_get_m_useContinuous(this._btDispatchInfo);
  22329. }
  22330. set continuousCollisionDetection(value) {
  22331. Physics3D._bullet.btCollisionWorld_set_m_useContinuous(this._btDispatchInfo, value);
  22332. }
  22333. get gravity() {
  22334. if (!this._btDiscreteDynamicsWorld)
  22335. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  22336. return this._gravity;
  22337. }
  22338. set gravity(value) {
  22339. if (!this._btDiscreteDynamicsWorld)
  22340. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  22341. this._gravity = value;
  22342. var bt = Physics3D._bullet;
  22343. var btGravity = PhysicsSimulation._btTempVector30;
  22344. bt.btVector3_setValue(btGravity, -value.x, value.y, value.z);
  22345. bt.btDiscreteDynamicsWorld_setGravity(this._btDiscreteDynamicsWorld, btGravity);
  22346. }
  22347. get speculativeContactRestitution() {
  22348. if (!this._btDiscreteDynamicsWorld)
  22349. throw "Simulation:Cannot Cannot perform this action when the physics engine is set to CollisionsOnly";
  22350. return Physics3D._bullet.btDiscreteDynamicsWorld_getApplySpeculativeContactRestitution(this._btDiscreteDynamicsWorld);
  22351. }
  22352. set speculativeContactRestitution(value) {
  22353. if (!this._btDiscreteDynamicsWorld)
  22354. throw "Simulation:Cannot Cannot perform this action when the physics engine is set to CollisionsOnly";
  22355. Physics3D._bullet.btDiscreteDynamicsWorld_setApplySpeculativeContactRestitution(this._btDiscreteDynamicsWorld, value);
  22356. }
  22357. _simulate(deltaTime) {
  22358. this._updatedRigidbodies = 0;
  22359. var bt = Physics3D._bullet;
  22360. if (this._btDiscreteDynamicsWorld)
  22361. bt.btDiscreteDynamicsWorld_stepSimulation(this._btDiscreteDynamicsWorld, deltaTime, this.maxSubSteps, this.fixedTimeStep);
  22362. else
  22363. bt.PerformDiscreteCollisionDetection(this._btCollisionWorld);
  22364. }
  22365. _destroy() {
  22366. var bt = Physics3D._bullet;
  22367. if (this._btDiscreteDynamicsWorld) {
  22368. bt.btCollisionWorld_destroy(this._btDiscreteDynamicsWorld);
  22369. this._btDiscreteDynamicsWorld = null;
  22370. }
  22371. else {
  22372. bt.btCollisionWorld_destroy(this._btCollisionWorld);
  22373. this._btCollisionWorld = null;
  22374. }
  22375. bt.btDbvtBroadphase_destroy(this._btBroadphase);
  22376. this._btBroadphase = null;
  22377. bt.btCollisionDispatcher_destroy(this._btDispatcher);
  22378. this._btDispatcher = null;
  22379. bt.btDefaultCollisionConfiguration_destroy(this._btCollisionConfiguration);
  22380. this._btCollisionConfiguration = null;
  22381. }
  22382. _addPhysicsCollider(component, group, mask) {
  22383. Physics3D._bullet.btCollisionWorld_addCollisionObject(this._btCollisionWorld, component._btColliderObject, group, mask);
  22384. }
  22385. _removePhysicsCollider(component) {
  22386. Physics3D._bullet.btCollisionWorld_removeCollisionObject(this._btCollisionWorld, component._btColliderObject);
  22387. }
  22388. _addRigidBody(rigidBody, group, mask) {
  22389. if (!this._btDiscreteDynamicsWorld)
  22390. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  22391. Physics3D._bullet.btDiscreteDynamicsWorld_addRigidBody(this._btCollisionWorld, rigidBody._btColliderObject, group, mask);
  22392. }
  22393. _removeRigidBody(rigidBody) {
  22394. if (!this._btDiscreteDynamicsWorld)
  22395. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  22396. Physics3D._bullet.btDiscreteDynamicsWorld_removeRigidBody(this._btCollisionWorld, rigidBody._btColliderObject);
  22397. }
  22398. _addCharacter(character, group, mask) {
  22399. if (!this._btDiscreteDynamicsWorld)
  22400. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  22401. var bt = Physics3D._bullet;
  22402. bt.btCollisionWorld_addCollisionObject(this._btCollisionWorld, character._btColliderObject, group, mask);
  22403. bt.btDynamicsWorld_addAction(this._btCollisionWorld, character._btKinematicCharacter);
  22404. }
  22405. _removeCharacter(character) {
  22406. if (!this._btDiscreteDynamicsWorld)
  22407. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  22408. var bt = Physics3D._bullet;
  22409. bt.btCollisionWorld_removeCollisionObject(this._btCollisionWorld, character._btColliderObject);
  22410. bt.btDynamicsWorld_removeAction(this._btCollisionWorld, character._btKinematicCharacter);
  22411. }
  22412. raycastFromTo(from, to, out = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  22413. var bt = Physics3D._bullet;
  22414. var rayResultCall = this._btClosestRayResultCallback;
  22415. var rayFrom = PhysicsSimulation._btTempVector30;
  22416. var rayTo = PhysicsSimulation._btTempVector31;
  22417. bt.btVector3_setValue(rayFrom, -from.x, from.y, from.z);
  22418. bt.btVector3_setValue(rayTo, -to.x, to.y, to.z);
  22419. bt.ClosestRayResultCallback_set_m_rayFromWorld(rayResultCall, rayFrom);
  22420. bt.ClosestRayResultCallback_set_m_rayToWorld(rayResultCall, rayTo);
  22421. bt.RayResultCallback_set_m_collisionFilterGroup(rayResultCall, collisonGroup);
  22422. bt.RayResultCallback_set_m_collisionFilterMask(rayResultCall, collisionMask);
  22423. bt.RayResultCallback_set_m_collisionObject(rayResultCall, null);
  22424. bt.RayResultCallback_set_m_closestHitFraction(rayResultCall, 1);
  22425. bt.btCollisionWorld_rayTest(this._btCollisionWorld, rayFrom, rayTo, rayResultCall);
  22426. if (bt.RayResultCallback_hasHit(rayResultCall)) {
  22427. if (out) {
  22428. out.succeeded = true;
  22429. out.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.RayResultCallback_get_m_collisionObject(rayResultCall))];
  22430. out.hitFraction = bt.RayResultCallback_get_m_closestHitFraction(rayResultCall);
  22431. var btPoint = bt.ClosestRayResultCallback_get_m_hitPointWorld(rayResultCall);
  22432. var point = out.point;
  22433. point.x = -bt.btVector3_x(btPoint);
  22434. point.y = bt.btVector3_y(btPoint);
  22435. point.z = bt.btVector3_z(btPoint);
  22436. var btNormal = bt.ClosestRayResultCallback_get_m_hitNormalWorld(rayResultCall);
  22437. var normal = out.normal;
  22438. normal.x = -bt.btVector3_x(btNormal);
  22439. normal.y = bt.btVector3_y(btNormal);
  22440. normal.z = bt.btVector3_z(btNormal);
  22441. }
  22442. return true;
  22443. }
  22444. else {
  22445. if (out)
  22446. out.succeeded = false;
  22447. return false;
  22448. }
  22449. }
  22450. raycastAllFromTo(from, to, out, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  22451. var bt = Physics3D._bullet;
  22452. var rayResultCall = this._btAllHitsRayResultCallback;
  22453. var rayFrom = PhysicsSimulation._btTempVector30;
  22454. var rayTo = PhysicsSimulation._btTempVector31;
  22455. out.length = 0;
  22456. bt.btVector3_setValue(rayFrom, -from.x, from.y, from.z);
  22457. bt.btVector3_setValue(rayTo, -to.x, to.y, to.z);
  22458. bt.AllHitsRayResultCallback_set_m_rayFromWorld(rayResultCall, rayFrom);
  22459. bt.AllHitsRayResultCallback_set_m_rayToWorld(rayResultCall, rayTo);
  22460. bt.RayResultCallback_set_m_collisionFilterGroup(rayResultCall, collisonGroup);
  22461. bt.RayResultCallback_set_m_collisionFilterMask(rayResultCall, collisionMask);
  22462. var collisionObjects = bt.AllHitsRayResultCallback_get_m_collisionObjects(rayResultCall);
  22463. var btPoints = bt.AllHitsRayResultCallback_get_m_hitPointWorld(rayResultCall);
  22464. var btNormals = bt.AllHitsRayResultCallback_get_m_hitNormalWorld(rayResultCall);
  22465. var btFractions = bt.AllHitsRayResultCallback_get_m_hitFractions(rayResultCall);
  22466. bt.tBtCollisionObjectArray_clear(collisionObjects);
  22467. bt.tVector3Array_clear(btPoints);
  22468. bt.tVector3Array_clear(btNormals);
  22469. bt.tScalarArray_clear(btFractions);
  22470. bt.btCollisionWorld_rayTest(this._btCollisionWorld, rayFrom, rayTo, rayResultCall);
  22471. var count = bt.tBtCollisionObjectArray_size(collisionObjects);
  22472. if (count > 0) {
  22473. this._collisionsUtils.recoverAllHitResultsPool();
  22474. for (var i = 0; i < count; i++) {
  22475. var hitResult = this._collisionsUtils.getHitResult();
  22476. out.push(hitResult);
  22477. hitResult.succeeded = true;
  22478. hitResult.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.tBtCollisionObjectArray_at(collisionObjects, i))];
  22479. hitResult.hitFraction = bt.tScalarArray_at(btFractions, i);
  22480. var btPoint = bt.tVector3Array_at(btPoints, i);
  22481. var pointE = hitResult.point;
  22482. pointE.x = -bt.btVector3_x(btPoint);
  22483. pointE.y = bt.btVector3_y(btPoint);
  22484. pointE.z = bt.btVector3_z(btPoint);
  22485. var btNormal = bt.tVector3Array_at(btNormals, i);
  22486. var normal = hitResult.normal;
  22487. normal.x = -bt.btVector3_x(btNormal);
  22488. normal.y = bt.btVector3_y(btNormal);
  22489. normal.z = bt.btVector3_z(btNormal);
  22490. }
  22491. return true;
  22492. }
  22493. else {
  22494. return false;
  22495. }
  22496. }
  22497. rayCast(ray, outHitResult = null, distance = 2147483647, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  22498. var from = ray.origin;
  22499. var to = PhysicsSimulation._tempVector30;
  22500. Vector3.normalize(ray.direction, to);
  22501. Vector3.scale(to, distance, to);
  22502. Vector3.add(from, to, to);
  22503. return this.raycastFromTo(from, to, outHitResult, collisonGroup, collisionMask);
  22504. }
  22505. rayCastAll(ray, out, distance = 2147483647, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  22506. var from = ray.origin;
  22507. var to = PhysicsSimulation._tempVector30;
  22508. Vector3.normalize(ray.direction, to);
  22509. Vector3.scale(to, distance, to);
  22510. Vector3.add(from, to, to);
  22511. return this.raycastAllFromTo(from, to, out, collisonGroup, collisionMask);
  22512. }
  22513. shapeCast(shape, fromPosition, toPosition, out = null, fromRotation = null, toRotation = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, allowedCcdPenetration = 0.0) {
  22514. var bt = Physics3D._bullet;
  22515. var convexResultCall = this._btClosestConvexResultCallback;
  22516. var convexPosFrom = PhysicsSimulation._btTempVector30;
  22517. var convexPosTo = PhysicsSimulation._btTempVector31;
  22518. var convexRotFrom = PhysicsSimulation._btTempQuaternion0;
  22519. var convexRotTo = PhysicsSimulation._btTempQuaternion1;
  22520. var convexTransform = PhysicsSimulation._btTempTransform0;
  22521. var convexTransTo = PhysicsSimulation._btTempTransform1;
  22522. var sweepShape = shape._btShape;
  22523. bt.btVector3_setValue(convexPosFrom, -fromPosition.x, fromPosition.y, fromPosition.z);
  22524. bt.btVector3_setValue(convexPosTo, -toPosition.x, toPosition.y, toPosition.z);
  22525. bt.ConvexResultCallback_set_m_collisionFilterGroup(convexResultCall, collisonGroup);
  22526. bt.ConvexResultCallback_set_m_collisionFilterMask(convexResultCall, collisionMask);
  22527. bt.btTransform_setOrigin(convexTransform, convexPosFrom);
  22528. bt.btTransform_setOrigin(convexTransTo, convexPosTo);
  22529. if (fromRotation) {
  22530. bt.btQuaternion_setValue(convexRotFrom, -fromRotation.x, fromRotation.y, fromRotation.z, -fromRotation.w);
  22531. bt.btTransform_setRotation(convexTransform, convexRotFrom);
  22532. }
  22533. else {
  22534. bt.btTransform_setRotation(convexTransform, this._btDefaultQuaternion);
  22535. }
  22536. if (toRotation) {
  22537. bt.btQuaternion_setValue(convexRotTo, -toRotation.x, toRotation.y, toRotation.z, -toRotation.w);
  22538. bt.btTransform_setRotation(convexTransTo, convexRotTo);
  22539. }
  22540. else {
  22541. bt.btTransform_setRotation(convexTransTo, this._btDefaultQuaternion);
  22542. }
  22543. bt.ClosestConvexResultCallback_set_m_hitCollisionObject(convexResultCall, null);
  22544. bt.ConvexResultCallback_set_m_closestHitFraction(convexResultCall, 1);
  22545. bt.btCollisionWorld_convexSweepTest(this._btCollisionWorld, sweepShape, convexTransform, convexTransTo, convexResultCall, allowedCcdPenetration);
  22546. if (bt.ConvexResultCallback_hasHit(convexResultCall)) {
  22547. if (out) {
  22548. out.succeeded = true;
  22549. out.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.ClosestConvexResultCallback_get_m_hitCollisionObject(convexResultCall))];
  22550. out.hitFraction = bt.ConvexResultCallback_get_m_closestHitFraction(convexResultCall);
  22551. var btPoint = bt.ClosestConvexResultCallback_get_m_hitPointWorld(convexResultCall);
  22552. var btNormal = bt.ClosestConvexResultCallback_get_m_hitNormalWorld(convexResultCall);
  22553. var point = out.point;
  22554. var normal = out.normal;
  22555. point.x = -bt.btVector3_x(btPoint);
  22556. point.y = bt.btVector3_y(btPoint);
  22557. point.z = bt.btVector3_z(btPoint);
  22558. normal.x = -bt.btVector3_x(btNormal);
  22559. normal.y = bt.btVector3_y(btNormal);
  22560. normal.z = bt.btVector3_z(btNormal);
  22561. }
  22562. return true;
  22563. }
  22564. else {
  22565. if (out)
  22566. out.succeeded = false;
  22567. return false;
  22568. }
  22569. }
  22570. shapeCastAll(shape, fromPosition, toPosition, out, fromRotation = null, toRotation = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, allowedCcdPenetration = 0.0) {
  22571. var bt = Physics3D._bullet;
  22572. var convexResultCall = this._btAllConvexResultCallback;
  22573. var convexPosFrom = PhysicsSimulation._btTempVector30;
  22574. var convexPosTo = PhysicsSimulation._btTempVector31;
  22575. var convexRotFrom = PhysicsSimulation._btTempQuaternion0;
  22576. var convexRotTo = PhysicsSimulation._btTempQuaternion1;
  22577. var convexTransform = PhysicsSimulation._btTempTransform0;
  22578. var convexTransTo = PhysicsSimulation._btTempTransform1;
  22579. var sweepShape = shape._btShape;
  22580. out.length = 0;
  22581. bt.btVector3_setValue(convexPosFrom, -fromPosition.x, fromPosition.y, fromPosition.z);
  22582. bt.btVector3_setValue(convexPosTo, -toPosition.x, toPosition.y, toPosition.z);
  22583. bt.ConvexResultCallback_set_m_collisionFilterGroup(convexResultCall, collisonGroup);
  22584. bt.ConvexResultCallback_set_m_collisionFilterMask(convexResultCall, collisionMask);
  22585. bt.btTransform_setOrigin(convexTransform, convexPosFrom);
  22586. bt.btTransform_setOrigin(convexTransTo, convexPosTo);
  22587. if (fromRotation) {
  22588. bt.btQuaternion_setValue(convexRotFrom, -fromRotation.x, fromRotation.y, fromRotation.z, -fromRotation.w);
  22589. bt.btTransform_setRotation(convexTransform, convexRotFrom);
  22590. }
  22591. else {
  22592. bt.btTransform_setRotation(convexTransform, this._btDefaultQuaternion);
  22593. }
  22594. if (toRotation) {
  22595. bt.btQuaternion_setValue(convexRotTo, -toRotation.x, toRotation.y, toRotation.z, -toRotation.w);
  22596. bt.btTransform_setRotation(convexTransTo, convexRotTo);
  22597. }
  22598. else {
  22599. bt.btTransform_setRotation(convexTransTo, this._btDefaultQuaternion);
  22600. }
  22601. var collisionObjects = bt.AllConvexResultCallback_get_m_collisionObjects(convexResultCall);
  22602. bt.tBtCollisionObjectArray_clear(collisionObjects);
  22603. bt.btCollisionWorld_convexSweepTest(this._btCollisionWorld, sweepShape, convexTransform, convexTransTo, convexResultCall, allowedCcdPenetration);
  22604. var count = bt.tBtCollisionObjectArray_size(collisionObjects);
  22605. if (count > 0) {
  22606. var btPoints = bt.AllConvexResultCallback_get_m_hitPointWorld(convexResultCall);
  22607. var btNormals = bt.AllConvexResultCallback_get_m_hitNormalWorld(convexResultCall);
  22608. var btFractions = bt.AllConvexResultCallback_get_m_hitFractions(convexResultCall);
  22609. for (var i = 0; i < count; i++) {
  22610. var hitResult = this._collisionsUtils.getHitResult();
  22611. out.push(hitResult);
  22612. hitResult.succeeded = true;
  22613. hitResult.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.tBtCollisionObjectArray_at(collisionObjects, i))];
  22614. hitResult.hitFraction = bt.tScalarArray_at(btFractions, i);
  22615. var btPoint = bt.tVector3Array_at(btPoints, i);
  22616. var point = hitResult.point;
  22617. point.x = -bt.btVector3_x(btPoint);
  22618. point.y = bt.btVector3_y(btPoint);
  22619. point.z = bt.btVector3_z(btPoint);
  22620. var btNormal = bt.tVector3Array_at(btNormals, i);
  22621. var normal = hitResult.normal;
  22622. normal.x = -bt.btVector3_x(btNormal);
  22623. normal.y = bt.btVector3_y(btNormal);
  22624. normal.z = bt.btVector3_z(btNormal);
  22625. }
  22626. return true;
  22627. }
  22628. else {
  22629. return false;
  22630. }
  22631. }
  22632. addConstraint(constraint, disableCollisionsBetweenLinkedBodies = false) {
  22633. if (!this._btDiscreteDynamicsWorld)
  22634. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  22635. constraint._simulation = this;
  22636. }
  22637. removeConstraint(constraint) {
  22638. if (!this._btDiscreteDynamicsWorld)
  22639. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  22640. }
  22641. _updatePhysicsTransformFromRender() {
  22642. var elements = this._physicsUpdateList.elements;
  22643. for (var i = 0, n = this._physicsUpdateList.length; i < n; i++) {
  22644. var physicCollider = elements[i];
  22645. physicCollider._derivePhysicsTransformation(false);
  22646. physicCollider._inPhysicUpdateListIndex = -1;
  22647. }
  22648. this._physicsUpdateList.length = 0;
  22649. }
  22650. _updateCharacters() {
  22651. for (var i = 0, n = this._characters.length; i < n; i++) {
  22652. var character = this._characters[i];
  22653. character._updateTransformComponent(Physics3D._bullet.btCollisionObject_getWorldTransform(character._btColliderObject));
  22654. }
  22655. }
  22656. _updateCollisions() {
  22657. this._collisionsUtils.recoverAllContactPointsPool();
  22658. var previous = this._currentFrameCollisions;
  22659. this._currentFrameCollisions = this._previousFrameCollisions;
  22660. this._currentFrameCollisions.length = 0;
  22661. this._previousFrameCollisions = previous;
  22662. var loopCount = Laya.Stat.loopCount;
  22663. var bt = Physics3D._bullet;
  22664. var numManifolds = bt.btDispatcher_getNumManifolds(this._btDispatcher);
  22665. for (var i = 0; i < numManifolds; i++) {
  22666. var contactManifold = bt.btDispatcher_getManifoldByIndexInternal(this._btDispatcher, i);
  22667. var componentA = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.btPersistentManifold_getBody0(contactManifold))];
  22668. var componentB = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.btPersistentManifold_getBody1(contactManifold))];
  22669. var collision = null;
  22670. var isFirstCollision;
  22671. var contacts = null;
  22672. var isTrigger = componentA.isTrigger || componentB.isTrigger;
  22673. if (isTrigger && (componentA.owner._needProcessTriggers || componentB.owner._needProcessTriggers)) {
  22674. var numContacts = bt.btPersistentManifold_getNumContacts(contactManifold);
  22675. for (var j = 0; j < numContacts; j++) {
  22676. var pt = bt.btPersistentManifold_getContactPoint(contactManifold, j);
  22677. var distance = bt.btManifoldPoint_getDistance(pt);
  22678. if (distance <= 0) {
  22679. collision = this._collisionsUtils.getCollision(componentA, componentB);
  22680. contacts = collision.contacts;
  22681. isFirstCollision = collision._updateFrame !== loopCount;
  22682. if (isFirstCollision) {
  22683. collision._isTrigger = true;
  22684. contacts.length = 0;
  22685. }
  22686. break;
  22687. }
  22688. }
  22689. }
  22690. else if (componentA.owner._needProcessCollisions || componentB.owner._needProcessCollisions) {
  22691. if (componentA._enableProcessCollisions || componentB._enableProcessCollisions) {
  22692. numContacts = bt.btPersistentManifold_getNumContacts(contactManifold);
  22693. for (j = 0; j < numContacts; j++) {
  22694. pt = bt.btPersistentManifold_getContactPoint(contactManifold, j);
  22695. distance = bt.btManifoldPoint_getDistance(pt);
  22696. if (distance <= 0) {
  22697. var contactPoint = this._collisionsUtils.getContactPoints();
  22698. contactPoint.colliderA = componentA;
  22699. contactPoint.colliderB = componentB;
  22700. contactPoint.distance = distance;
  22701. var btNormal = bt.btManifoldPoint_get_m_normalWorldOnB(pt);
  22702. var normal = contactPoint.normal;
  22703. normal.x = -bt.btVector3_x(btNormal);
  22704. normal.y = bt.btVector3_y(btNormal);
  22705. normal.z = bt.btVector3_z(btNormal);
  22706. var btPostionA = bt.btManifoldPoint_get_m_positionWorldOnA(pt);
  22707. var positionOnA = contactPoint.positionOnA;
  22708. positionOnA.x = -bt.btVector3_x(btPostionA);
  22709. positionOnA.y = bt.btVector3_y(btPostionA);
  22710. positionOnA.z = bt.btVector3_z(btPostionA);
  22711. var btPostionB = bt.btManifoldPoint_get_m_positionWorldOnB(pt);
  22712. var positionOnB = contactPoint.positionOnB;
  22713. positionOnB.x = -bt.btVector3_x(btPostionB);
  22714. positionOnB.y = bt.btVector3_y(btPostionB);
  22715. positionOnB.z = bt.btVector3_z(btPostionB);
  22716. if (!collision) {
  22717. collision = this._collisionsUtils.getCollision(componentA, componentB);
  22718. contacts = collision.contacts;
  22719. isFirstCollision = collision._updateFrame !== loopCount;
  22720. if (isFirstCollision) {
  22721. collision._isTrigger = false;
  22722. contacts.length = 0;
  22723. }
  22724. }
  22725. contacts.push(contactPoint);
  22726. }
  22727. }
  22728. }
  22729. }
  22730. if (collision && isFirstCollision) {
  22731. this._currentFrameCollisions.push(collision);
  22732. collision._setUpdateFrame(loopCount);
  22733. }
  22734. }
  22735. }
  22736. _eventScripts() {
  22737. var loopCount = Laya.Stat.loopCount;
  22738. for (var i = 0, n = this._currentFrameCollisions.length; i < n; i++) {
  22739. var curFrameCol = this._currentFrameCollisions[i];
  22740. var colliderA = curFrameCol._colliderA;
  22741. var colliderB = curFrameCol._colliderB;
  22742. if (colliderA.destroyed || colliderB.destroyed)
  22743. continue;
  22744. if (loopCount - curFrameCol._lastUpdateFrame === 1) {
  22745. var ownerA = colliderA.owner;
  22746. var scriptsA = ownerA._scripts;
  22747. if (scriptsA) {
  22748. if (curFrameCol._isTrigger) {
  22749. if (ownerA._needProcessTriggers) {
  22750. for (var j = 0, m = scriptsA.length; j < m; j++)
  22751. scriptsA[j].onTriggerStay(colliderB);
  22752. }
  22753. }
  22754. else {
  22755. if (ownerA._needProcessCollisions) {
  22756. for (j = 0, m = scriptsA.length; j < m; j++) {
  22757. curFrameCol.other = colliderB;
  22758. scriptsA[j].onCollisionStay(curFrameCol);
  22759. }
  22760. }
  22761. }
  22762. }
  22763. var ownerB = colliderB.owner;
  22764. var scriptsB = ownerB._scripts;
  22765. if (scriptsB) {
  22766. if (curFrameCol._isTrigger) {
  22767. if (ownerB._needProcessTriggers) {
  22768. for (j = 0, m = scriptsB.length; j < m; j++)
  22769. scriptsB[j].onTriggerStay(colliderA);
  22770. }
  22771. }
  22772. else {
  22773. if (ownerB._needProcessCollisions) {
  22774. for (j = 0, m = scriptsB.length; j < m; j++) {
  22775. curFrameCol.other = colliderA;
  22776. scriptsB[j].onCollisionStay(curFrameCol);
  22777. }
  22778. }
  22779. }
  22780. }
  22781. }
  22782. else {
  22783. ownerA = colliderA.owner;
  22784. scriptsA = ownerA._scripts;
  22785. if (scriptsA) {
  22786. if (curFrameCol._isTrigger) {
  22787. if (ownerA._needProcessTriggers) {
  22788. for (j = 0, m = scriptsA.length; j < m; j++)
  22789. scriptsA[j].onTriggerEnter(colliderB);
  22790. }
  22791. }
  22792. else {
  22793. if (ownerA._needProcessCollisions) {
  22794. for (j = 0, m = scriptsA.length; j < m; j++) {
  22795. curFrameCol.other = colliderB;
  22796. scriptsA[j].onCollisionEnter(curFrameCol);
  22797. }
  22798. }
  22799. }
  22800. }
  22801. ownerB = colliderB.owner;
  22802. scriptsB = ownerB._scripts;
  22803. if (scriptsB) {
  22804. if (curFrameCol._isTrigger) {
  22805. if (ownerB._needProcessTriggers) {
  22806. for (j = 0, m = scriptsB.length; j < m; j++)
  22807. scriptsB[j].onTriggerEnter(colliderA);
  22808. }
  22809. }
  22810. else {
  22811. if (ownerB._needProcessCollisions) {
  22812. for (j = 0, m = scriptsB.length; j < m; j++) {
  22813. curFrameCol.other = colliderA;
  22814. scriptsB[j].onCollisionEnter(curFrameCol);
  22815. }
  22816. }
  22817. }
  22818. }
  22819. }
  22820. }
  22821. for (i = 0, n = this._previousFrameCollisions.length; i < n; i++) {
  22822. var preFrameCol = this._previousFrameCollisions[i];
  22823. var preColliderA = preFrameCol._colliderA;
  22824. var preColliderB = preFrameCol._colliderB;
  22825. if (preColliderA.destroyed || preColliderB.destroyed)
  22826. continue;
  22827. if (loopCount - preFrameCol._updateFrame === 1) {
  22828. this._collisionsUtils.recoverCollision(preFrameCol);
  22829. ownerA = preColliderA.owner;
  22830. scriptsA = ownerA._scripts;
  22831. if (scriptsA) {
  22832. if (preFrameCol._isTrigger) {
  22833. if (ownerA._needProcessTriggers) {
  22834. for (j = 0, m = scriptsA.length; j < m; j++)
  22835. scriptsA[j].onTriggerExit(preColliderB);
  22836. }
  22837. }
  22838. else {
  22839. if (ownerA._needProcessCollisions) {
  22840. for (j = 0, m = scriptsA.length; j < m; j++) {
  22841. preFrameCol.other = preColliderB;
  22842. scriptsA[j].onCollisionExit(preFrameCol);
  22843. }
  22844. }
  22845. }
  22846. }
  22847. ownerB = preColliderB.owner;
  22848. scriptsB = ownerB._scripts;
  22849. if (scriptsB) {
  22850. if (preFrameCol._isTrigger) {
  22851. if (ownerB._needProcessTriggers) {
  22852. for (j = 0, m = scriptsB.length; j < m; j++)
  22853. scriptsB[j].onTriggerExit(preColliderA);
  22854. }
  22855. }
  22856. else {
  22857. if (ownerB._needProcessCollisions) {
  22858. for (j = 0, m = scriptsB.length; j < m; j++) {
  22859. preFrameCol.other = preColliderA;
  22860. scriptsB[j].onCollisionExit(preFrameCol);
  22861. }
  22862. }
  22863. }
  22864. }
  22865. }
  22866. }
  22867. }
  22868. clearForces() {
  22869. if (!this._btDiscreteDynamicsWorld)
  22870. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  22871. Physics3D._bullet.btDiscreteDynamicsWorld_clearForces(this._btDiscreteDynamicsWorld);
  22872. }
  22873. }
  22874. PhysicsSimulation.PHYSICSENGINEFLAGS_NONE = 0x0;
  22875. PhysicsSimulation.PHYSICSENGINEFLAGS_COLLISIONSONLY = 0x1;
  22876. PhysicsSimulation.PHYSICSENGINEFLAGS_SOFTBODYSUPPORT = 0x2;
  22877. PhysicsSimulation.PHYSICSENGINEFLAGS_MULTITHREADED = 0x4;
  22878. PhysicsSimulation.PHYSICSENGINEFLAGS_USEHARDWAREWHENPOSSIBLE = 0x8;
  22879. PhysicsSimulation.SOLVERMODE_RANDMIZE_ORDER = 1;
  22880. PhysicsSimulation.SOLVERMODE_FRICTION_SEPARATE = 2;
  22881. PhysicsSimulation.SOLVERMODE_USE_WARMSTARTING = 4;
  22882. PhysicsSimulation.SOLVERMODE_USE_2_FRICTION_DIRECTIONS = 16;
  22883. PhysicsSimulation.SOLVERMODE_ENABLE_FRICTION_DIRECTION_CACHING = 32;
  22884. PhysicsSimulation.SOLVERMODE_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION = 64;
  22885. PhysicsSimulation.SOLVERMODE_CACHE_FRIENDLY = 128;
  22886. PhysicsSimulation.SOLVERMODE_SIMD = 256;
  22887. PhysicsSimulation.SOLVERMODE_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS = 512;
  22888. PhysicsSimulation.SOLVERMODE_ALLOW_ZERO_LENGTH_FRICTION_DIRECTIONS = 1024;
  22889. PhysicsSimulation._tempVector30 = new Vector3();
  22890. PhysicsSimulation.disableSimulation = false;
  22891. class Input3D {
  22892. constructor() {
  22893. this._eventList = [];
  22894. this._mouseTouch = new MouseTouch();
  22895. this._touchPool = [];
  22896. this._touches = new SimpleSingletonList();
  22897. this._multiTouchEnabled = true;
  22898. this._pushEventList = ((e) => {
  22899. (e.cancelable) && (e.preventDefault());
  22900. this._eventList.push(e);
  22901. }).bind(this);
  22902. }
  22903. __init__(canvas, scene) {
  22904. this._scene = scene;
  22905. canvas.oncontextmenu = function (e) {
  22906. return false;
  22907. };
  22908. }
  22909. _onCanvasEvent(canvas) {
  22910. canvas.addEventListener('mousedown', this._pushEventList);
  22911. canvas.addEventListener('mouseup', this._pushEventList, true);
  22912. canvas.addEventListener('mousemove', this._pushEventList, true);
  22913. canvas.addEventListener("touchstart", this._pushEventList);
  22914. canvas.addEventListener("touchend", this._pushEventList, true);
  22915. canvas.addEventListener("touchmove", this._pushEventList, true);
  22916. canvas.addEventListener("touchcancel", this._pushEventList, true);
  22917. }
  22918. _offCanvasEvent(canvas) {
  22919. canvas.removeEventListener('mousedown', this._pushEventList);
  22920. canvas.removeEventListener('mouseup', this._pushEventList, true);
  22921. canvas.removeEventListener('mousemove', this._pushEventList, true);
  22922. canvas.removeEventListener("touchstart", this._pushEventList);
  22923. canvas.removeEventListener("touchend", this._pushEventList, true);
  22924. canvas.removeEventListener("touchmove", this._pushEventList, true);
  22925. canvas.removeEventListener("touchcancel", this._pushEventList, true);
  22926. this._eventList.length = 0;
  22927. this._touches.clear();
  22928. }
  22929. touchCount() {
  22930. return this._touches.length;
  22931. }
  22932. get multiTouchEnabled() {
  22933. return this._multiTouchEnabled;
  22934. }
  22935. set multiTouchEnabled(value) {
  22936. this._multiTouchEnabled = value;
  22937. }
  22938. _getTouch(touchID) {
  22939. var touch = this._touchPool[touchID];
  22940. if (!touch) {
  22941. touch = new Touch();
  22942. this._touchPool[touchID] = touch;
  22943. touch._identifier = touchID;
  22944. }
  22945. return touch;
  22946. }
  22947. _mouseTouchDown() {
  22948. var touch = this._mouseTouch;
  22949. var sprite = touch.sprite;
  22950. touch._pressedSprite = sprite;
  22951. touch._pressedLoopCount = Laya.Stat.loopCount;
  22952. if (sprite) {
  22953. var scripts = sprite._scripts;
  22954. if (scripts) {
  22955. for (var i = 0, n = scripts.length; i < n; i++)
  22956. scripts[i].onMouseDown();
  22957. }
  22958. }
  22959. }
  22960. _mouseTouchUp() {
  22961. var i, n;
  22962. var touch = this._mouseTouch;
  22963. var lastPressedSprite = touch._pressedSprite;
  22964. touch._pressedSprite = null;
  22965. touch._pressedLoopCount = -1;
  22966. var sprite = touch.sprite;
  22967. if (sprite) {
  22968. if (sprite === lastPressedSprite) {
  22969. var scripts = sprite._scripts;
  22970. if (scripts) {
  22971. for (i = 0, n = scripts.length; i < n; i++)
  22972. scripts[i].onMouseClick();
  22973. }
  22974. }
  22975. }
  22976. if (lastPressedSprite) {
  22977. var lastScripts = lastPressedSprite._scripts;
  22978. if (lastScripts) {
  22979. for (i = 0, n = lastScripts.length; i < n; i++)
  22980. lastScripts[i].onMouseUp();
  22981. }
  22982. }
  22983. }
  22984. _mouseTouchRayCast(cameras) {
  22985. var touchHitResult = Input3D._tempHitResult0;
  22986. var touchPos = Input3D._tempVector20;
  22987. var touchRay = Input3D._tempRay0;
  22988. touchHitResult.succeeded = false;
  22989. var x = this._mouseTouch.mousePositionX;
  22990. var y = this._mouseTouch.mousePositionY;
  22991. touchPos.x = x;
  22992. touchPos.y = y;
  22993. for (var i = cameras.length - 1; i >= 0; i--) {
  22994. var camera = cameras[i];
  22995. var viewport = camera.viewport;
  22996. if (touchPos.x >= viewport.x && touchPos.y >= viewport.y && touchPos.x <= viewport.width && touchPos.y <= viewport.height) {
  22997. camera.viewportPointToRay(touchPos, touchRay);
  22998. var sucess = this._scene._physicsSimulation.rayCast(touchRay, touchHitResult);
  22999. if (sucess || (camera.clearFlag === BaseCamera.CLEARFLAG_SOLIDCOLOR || camera.clearFlag === BaseCamera.CLEARFLAG_SKY))
  23000. break;
  23001. }
  23002. }
  23003. var touch = this._mouseTouch;
  23004. var lastSprite = touch.sprite;
  23005. if (touchHitResult.succeeded) {
  23006. var touchSprite = touchHitResult.collider.owner;
  23007. touch.sprite = touchSprite;
  23008. var scripts = touchSprite._scripts;
  23009. if (lastSprite !== touchSprite) {
  23010. if (scripts) {
  23011. for (var j = 0, m = scripts.length; j < m; j++)
  23012. scripts[j].onMouseEnter();
  23013. }
  23014. }
  23015. }
  23016. else {
  23017. touch.sprite = null;
  23018. }
  23019. if (lastSprite && (lastSprite !== touchSprite)) {
  23020. var outScripts = lastSprite._scripts;
  23021. if (outScripts) {
  23022. for (j = 0, m = outScripts.length; j < m; j++)
  23023. outScripts[j].onMouseOut();
  23024. }
  23025. }
  23026. }
  23027. _changeTouches(changedTouches, flag) {
  23028. var offsetX = 0, offsetY = 0;
  23029. var lastCount = this._touches.length;
  23030. for (var j = 0, m = changedTouches.length; j < m; j++) {
  23031. var nativeTouch = changedTouches[j];
  23032. var identifier = nativeTouch.identifier;
  23033. if (!this._multiTouchEnabled && identifier !== 0)
  23034. continue;
  23035. var touch = this._getTouch(identifier);
  23036. var pos = touch._position;
  23037. var mousePoint = Input3D._tempPoint;
  23038. mousePoint.setTo(nativeTouch.pageX, nativeTouch.pageY);
  23039. Laya.ILaya.stage._canvasTransform.invertTransformPoint(mousePoint);
  23040. var posX = mousePoint.x;
  23041. var posY = mousePoint.y;
  23042. switch (flag) {
  23043. case 0:
  23044. this._touches.add(touch);
  23045. offsetX += posX;
  23046. offsetY += posY;
  23047. break;
  23048. case 1:
  23049. this._touches.remove(touch);
  23050. offsetX -= posX;
  23051. offsetY -= posY;
  23052. break;
  23053. case 2:
  23054. offsetX = posX - pos.x;
  23055. offsetY = posY - pos.y;
  23056. break;
  23057. }
  23058. pos.x = posX;
  23059. pos.y = posY;
  23060. }
  23061. var touchCount = this._touches.length;
  23062. if (touchCount === 0) {
  23063. this._mouseTouch.mousePositionX = 0;
  23064. this._mouseTouch.mousePositionY = 0;
  23065. }
  23066. else {
  23067. this._mouseTouch.mousePositionX = (this._mouseTouch.mousePositionX * lastCount + offsetX) / touchCount;
  23068. this._mouseTouch.mousePositionY = (this._mouseTouch.mousePositionY * lastCount + offsetY) / touchCount;
  23069. }
  23070. }
  23071. _update() {
  23072. var enablePhysics = Physics3D._enablePhysics && !PhysicsSimulation.disableSimulation;
  23073. var i, n, j, m;
  23074. n = this._eventList.length;
  23075. var cameras = this._scene._cameraPool;
  23076. if (n > 0) {
  23077. var rayCast = false;
  23078. for (i = 0; i < n; i++) {
  23079. var e = this._eventList[i];
  23080. switch (e.type) {
  23081. case "mousedown":
  23082. (enablePhysics) && (this._mouseTouchDown());
  23083. break;
  23084. case "mouseup":
  23085. (enablePhysics) && (this._mouseTouchUp());
  23086. break;
  23087. case "mousemove":
  23088. var mousePoint = Input3D._tempPoint;
  23089. mousePoint.setTo(e.pageX, e.pageY);
  23090. Laya.ILaya.stage._canvasTransform.invertTransformPoint(mousePoint);
  23091. this._mouseTouch.mousePositionX = mousePoint.x;
  23092. this._mouseTouch.mousePositionY = mousePoint.y;
  23093. (enablePhysics) && (rayCast = true);
  23094. break;
  23095. case "touchstart":
  23096. var lastLength = this._touches.length;
  23097. this._changeTouches(e.changedTouches, 0);
  23098. if (enablePhysics) {
  23099. rayCast = true;
  23100. (lastLength === 0) && (this._mouseTouchDown());
  23101. }
  23102. break;
  23103. case "touchend":
  23104. case "touchcancel":
  23105. this._changeTouches(e.changedTouches, 1);
  23106. (enablePhysics && this._touches.length === 0) && (this._mouseTouchUp());
  23107. break;
  23108. case "touchmove":
  23109. this._changeTouches(e.changedTouches, 2);
  23110. (enablePhysics) && (rayCast = true);
  23111. break;
  23112. default:
  23113. throw "Input3D:unkonwn event type.";
  23114. }
  23115. }
  23116. (rayCast) && (this._mouseTouchRayCast(cameras));
  23117. this._eventList.length = 0;
  23118. }
  23119. if (enablePhysics) {
  23120. var mouseTouch = this._mouseTouch;
  23121. var pressedSprite = mouseTouch._pressedSprite;
  23122. if (pressedSprite && (Laya.Stat.loopCount > mouseTouch._pressedLoopCount)) {
  23123. var pressedScripts = pressedSprite._scripts;
  23124. if (pressedScripts) {
  23125. for (j = 0, m = pressedScripts.length; j < m; j++)
  23126. pressedScripts[j].onMouseDrag();
  23127. }
  23128. }
  23129. var touchSprite = mouseTouch.sprite;
  23130. if (touchSprite) {
  23131. var scripts = touchSprite._scripts;
  23132. if (scripts) {
  23133. for (j = 0, m = scripts.length; j < m; j++)
  23134. scripts[j].onMouseOver();
  23135. }
  23136. }
  23137. }
  23138. }
  23139. getTouch(index) {
  23140. if (index < this._touches.length) {
  23141. return this._touches.elements[index];
  23142. }
  23143. else {
  23144. return null;
  23145. }
  23146. }
  23147. }
  23148. Input3D._tempPoint = new Laya.Point();
  23149. Input3D._tempVector20 = new Vector2();
  23150. Input3D._tempRay0 = new Ray(new Vector3(), new Vector3());
  23151. Input3D._tempHitResult0 = new HitResult();
  23152. class PhysicsSettings {
  23153. constructor() {
  23154. this.flags = 0;
  23155. this.maxSubSteps = 1;
  23156. this.fixedTimeStep = 1.0 / 60.0;
  23157. }
  23158. }
  23159. class VertexPositionTexture0 {
  23160. static get vertexDeclaration() {
  23161. return VertexPositionTexture0._vertexDeclaration;
  23162. }
  23163. static __init__() {
  23164. VertexPositionTexture0._vertexDeclaration = new VertexDeclaration(20, [new VertexElement(0, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0),
  23165. new VertexElement(12, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE0)]);
  23166. }
  23167. get position() {
  23168. return this._position;
  23169. }
  23170. get textureCoordinate0() {
  23171. return this._textureCoordinate0;
  23172. }
  23173. get vertexDeclaration() {
  23174. return VertexPositionTexture0._vertexDeclaration;
  23175. }
  23176. constructor(position, textureCoordinate0) {
  23177. this._position = position;
  23178. this._textureCoordinate0 = textureCoordinate0;
  23179. }
  23180. }
  23181. class SkyDome extends SkyMesh {
  23182. constructor(stacks = 48, slices = 48) {
  23183. super();
  23184. var gl = Laya.LayaGL.instance;
  23185. this._stacks = stacks;
  23186. this._slices = slices;
  23187. var vertexDeclaration = VertexPositionTexture0.vertexDeclaration;
  23188. var vertexFloatCount = vertexDeclaration.vertexStride / 4;
  23189. var numberVertices = (this._stacks + 1) * (this._slices + 1);
  23190. var numberIndices = (3 * this._stacks * (this._slices + 1)) * 2;
  23191. var vertices = new Float32Array(numberVertices * vertexFloatCount);
  23192. var indices = new Uint16Array(numberIndices);
  23193. var stackAngle = Math.PI / this._stacks;
  23194. var sliceAngle = (Math.PI * 2.0) / this._slices;
  23195. var vertexIndex = 0;
  23196. var vertexCount = 0;
  23197. var indexCount = 0;
  23198. for (var stack = 0; stack < (this._stacks + 1); stack++) {
  23199. var r = Math.sin(stack * stackAngle);
  23200. var y = Math.cos(stack * stackAngle);
  23201. for (var slice = 0; slice < (this._slices + 1); slice++) {
  23202. var x = r * Math.sin(slice * sliceAngle);
  23203. var z = r * Math.cos(slice * sliceAngle);
  23204. vertices[vertexCount + 0] = x * SkyDome._radius;
  23205. vertices[vertexCount + 1] = y * SkyDome._radius;
  23206. vertices[vertexCount + 2] = z * SkyDome._radius;
  23207. vertices[vertexCount + 3] = -(slice / this._slices) + 0.75;
  23208. vertices[vertexCount + 4] = stack / this._stacks;
  23209. vertexCount += vertexFloatCount;
  23210. if (stack != (this._stacks - 1)) {
  23211. indices[indexCount++] = vertexIndex + 1;
  23212. indices[indexCount++] = vertexIndex;
  23213. indices[indexCount++] = vertexIndex + (this._slices + 1);
  23214. indices[indexCount++] = vertexIndex + (this._slices + 1);
  23215. indices[indexCount++] = vertexIndex;
  23216. indices[indexCount++] = vertexIndex + (this._slices);
  23217. vertexIndex++;
  23218. }
  23219. }
  23220. }
  23221. this._vertexBuffer = new VertexBuffer3D(vertices.length * 4, gl.STATIC_DRAW, false);
  23222. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  23223. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indices.length, gl.STATIC_DRAW, false);
  23224. this._vertexBuffer.setData(vertices.buffer);
  23225. this._indexBuffer.setData(indices);
  23226. var bufferState = new BufferState();
  23227. bufferState.bind();
  23228. bufferState.applyVertexBuffer(this._vertexBuffer);
  23229. bufferState.applyIndexBuffer(this._indexBuffer);
  23230. bufferState.unBind();
  23231. this._bufferState = bufferState;
  23232. }
  23233. static __init__() {
  23234. SkyDome.instance = new SkyDome();
  23235. }
  23236. get stacks() {
  23237. return this._stacks;
  23238. }
  23239. get slices() {
  23240. return this._slices;
  23241. }
  23242. _render(state) {
  23243. var gl = Laya.LayaGL.instance;
  23244. var indexCount = this._indexBuffer.indexCount;
  23245. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  23246. Laya.Stat.trianglesFaces += indexCount / 3;
  23247. Laya.Stat.renderBatches++;
  23248. }
  23249. }
  23250. SkyDome._radius = 1;
  23251. class LightQueue {
  23252. constructor() {
  23253. this._length = 0;
  23254. this._elements = [];
  23255. }
  23256. add(light) {
  23257. if (this._length === this._elements.length)
  23258. this._elements.push(light);
  23259. else
  23260. this._elements[this._length] = light;
  23261. this._length++;
  23262. }
  23263. remove(light) {
  23264. var index = this._elements.indexOf(light);
  23265. this._length--;
  23266. if (index !== this._length) {
  23267. var end = this._elements[this._length];
  23268. this._elements[index] = end;
  23269. }
  23270. }
  23271. shift() {
  23272. this._length--;
  23273. return this._elements.shift();
  23274. }
  23275. }
  23276. class DirectionLightQueue extends LightQueue {
  23277. getSunLight() {
  23278. var maxIntIndex;
  23279. var maxIntensity = -1;
  23280. var elements = this._elements;
  23281. for (var i = 0; i < this._length; i++) {
  23282. var intensity = elements[i]._intensity;
  23283. if (maxIntensity < intensity) {
  23284. maxIntensity = intensity;
  23285. maxIntIndex = i;
  23286. }
  23287. }
  23288. return maxIntIndex;
  23289. }
  23290. }
  23291. class AlternateLightQueue extends LightQueue {
  23292. remove(light) {
  23293. var index = this._elements.indexOf(light);
  23294. this._elements.splice(index, 1);
  23295. this._length--;
  23296. }
  23297. }
  23298. class PixelLineFilter extends GeometryElement {
  23299. constructor(owner, maxLineCount) {
  23300. super();
  23301. this._floatCountPerVertices = 7;
  23302. this._minUpdate = Number.MAX_VALUE;
  23303. this._maxUpdate = Number.MIN_VALUE;
  23304. this._bufferState = new BufferState();
  23305. this._floatBound = new Float32Array(6);
  23306. this._calculateBound = false;
  23307. this._maxLineCount = 0;
  23308. this._lineCount = 0;
  23309. var pointCount = maxLineCount * 2;
  23310. this._owner = owner;
  23311. this._maxLineCount = maxLineCount;
  23312. this._vertices = new Float32Array(pointCount * this._floatCountPerVertices);
  23313. this._vertexBuffer = new VertexBuffer3D(PixelLineVertex.vertexDeclaration.vertexStride * pointCount, Laya.LayaGL.instance.STATIC_DRAW, false);
  23314. this._vertexBuffer.vertexDeclaration = PixelLineVertex.vertexDeclaration;
  23315. this._bufferState.bind();
  23316. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  23317. this._bufferState.unBind();
  23318. var min = PixelLineFilter._tempVector0;
  23319. var max = PixelLineFilter._tempVector1;
  23320. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23321. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23322. this._bounds = new Bounds(min, max);
  23323. }
  23324. _getType() {
  23325. return PixelLineFilter._type;
  23326. }
  23327. _resizeLineData(maxCount) {
  23328. var pointCount = maxCount * 2;
  23329. var lastVertices = this._vertices;
  23330. this._vertexBuffer.destroy();
  23331. this._maxLineCount = maxCount;
  23332. var vertexCount = pointCount * this._floatCountPerVertices;
  23333. this._vertices = new Float32Array(vertexCount);
  23334. this._vertexBuffer = new VertexBuffer3D(PixelLineVertex.vertexDeclaration.vertexStride * pointCount, Laya.LayaGL.instance.STATIC_DRAW, false);
  23335. this._vertexBuffer.vertexDeclaration = PixelLineVertex.vertexDeclaration;
  23336. if (vertexCount < lastVertices.length) {
  23337. this._vertices.set(new Float32Array(lastVertices.buffer, 0, vertexCount));
  23338. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, vertexCount * 4);
  23339. }
  23340. else {
  23341. this._vertices.set(lastVertices);
  23342. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, lastVertices.length * 4);
  23343. }
  23344. this._bufferState.bind();
  23345. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  23346. this._bufferState.unBind();
  23347. }
  23348. _updateLineVertices(offset, startPosition, endPosition, startColor, endColor) {
  23349. if (startPosition) {
  23350. this._vertices[offset + 0] = startPosition.x;
  23351. this._vertices[offset + 1] = startPosition.y;
  23352. this._vertices[offset + 2] = startPosition.z;
  23353. }
  23354. if (startColor) {
  23355. this._vertices[offset + 3] = startColor.r;
  23356. this._vertices[offset + 4] = startColor.g;
  23357. this._vertices[offset + 5] = startColor.b;
  23358. this._vertices[offset + 6] = startColor.a;
  23359. }
  23360. if (endPosition) {
  23361. this._vertices[offset + 7] = endPosition.x;
  23362. this._vertices[offset + 8] = endPosition.y;
  23363. this._vertices[offset + 9] = endPosition.z;
  23364. }
  23365. if (endColor) {
  23366. this._vertices[offset + 10] = endColor.r;
  23367. this._vertices[offset + 11] = endColor.g;
  23368. this._vertices[offset + 12] = endColor.b;
  23369. this._vertices[offset + 13] = endColor.a;
  23370. }
  23371. this._minUpdate = Math.min(this._minUpdate, offset);
  23372. this._maxUpdate = Math.max(this._maxUpdate, offset + this._floatCountPerVertices * 2);
  23373. var bounds = this._bounds;
  23374. var floatBound = this._floatBound;
  23375. var min = bounds.getMin(), max = bounds.getMax();
  23376. Vector3.min(min, startPosition, min);
  23377. Vector3.min(min, endPosition, min);
  23378. Vector3.max(max, startPosition, max);
  23379. Vector3.max(max, endPosition, max);
  23380. bounds.setMin(min);
  23381. bounds.setMax(max);
  23382. floatBound[0] = min.x, floatBound[1] = min.y, floatBound[2] = min.z;
  23383. floatBound[3] = max.x, floatBound[4] = max.y, floatBound[5] = max.z;
  23384. }
  23385. _reCalculateBound() {
  23386. if (this._calculateBound) {
  23387. var vertices = this._vertices;
  23388. var min = PixelLineFilter._tempVector0;
  23389. var max = PixelLineFilter._tempVector1;
  23390. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23391. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23392. for (var i = 0; i < this._lineCount * 2; ++i) {
  23393. var offset = this._floatCountPerVertices * i;
  23394. var x = vertices[offset + 0], y = vertices[offset + 1], z = vertices[offset + 2];
  23395. min.x = Math.min(x, min.x);
  23396. min.y = Math.min(y, min.y);
  23397. min.z = Math.min(z, min.z);
  23398. max.x = Math.max(x, max.x);
  23399. max.y = Math.max(y, max.y);
  23400. max.z = Math.max(z, max.z);
  23401. }
  23402. this._bounds.setMin(min);
  23403. this._bounds.setMax(max);
  23404. var floatBound = this._floatBound;
  23405. floatBound[0] = min.x, floatBound[1] = min.y, floatBound[2] = min.z;
  23406. floatBound[3] = max.x, floatBound[4] = max.y, floatBound[5] = max.z;
  23407. this._calculateBound = false;
  23408. }
  23409. }
  23410. _removeLineData(index) {
  23411. var floatCount = this._floatCountPerVertices * 2;
  23412. var nextIndex = index + 1;
  23413. var offset = index * floatCount;
  23414. var vertices = this._vertices;
  23415. var rightPartVertices = new Float32Array(vertices.buffer, nextIndex * floatCount * 4, (this._lineCount - nextIndex) * floatCount);
  23416. vertices.set(rightPartVertices, offset);
  23417. this._minUpdate = Math.min(this._minUpdate, offset);
  23418. this._maxUpdate = Math.max(this._maxUpdate, offset + rightPartVertices.length);
  23419. this._lineCount--;
  23420. var floatBound = this._floatBound;
  23421. var startX = vertices[offset], startY = vertices[offset + 1], startZ = vertices[offset + 2];
  23422. var endX = vertices[offset + 7], endY = vertices[offset + 8], endZ = vertices[offset + 9];
  23423. var minX = floatBound[0], minY = floatBound[1], minZ = floatBound[2];
  23424. var maxX = floatBound[3], maxY = floatBound[4], maxZ = floatBound[5];
  23425. if ((startX === minX) || (startX === maxX) || (startY === minY) || (startY === maxY) || (startZ === minZ) || (startZ === maxZ) ||
  23426. (endX === minX) || (endX === maxX) || (endY === minY) || (endY === maxY) || (endZ === minZ) || (endZ === maxZ))
  23427. this._calculateBound = true;
  23428. }
  23429. _updateLineData(index, startPosition, endPosition, startColor, endColor) {
  23430. var floatCount = this._floatCountPerVertices * 2;
  23431. this._updateLineVertices(index * floatCount, startPosition, endPosition, startColor, endColor);
  23432. }
  23433. _updateLineDatas(index, data) {
  23434. var floatCount = this._floatCountPerVertices * 2;
  23435. var count = data.length;
  23436. for (var i = 0; i < count; i++) {
  23437. var line = data[i];
  23438. this._updateLineVertices((index + i) * floatCount, line.startPosition, line.endPosition, line.startColor, line.endColor);
  23439. }
  23440. }
  23441. _getLineData(index, out) {
  23442. var startPosition = out.startPosition;
  23443. var startColor = out.startColor;
  23444. var endPosition = out.endPosition;
  23445. var endColor = out.endColor;
  23446. var vertices = this._vertices;
  23447. var offset = index * this._floatCountPerVertices * 2;
  23448. startPosition.x = vertices[offset + 0];
  23449. startPosition.y = vertices[offset + 1];
  23450. startPosition.z = vertices[offset + 2];
  23451. startColor.r = vertices[offset + 3];
  23452. startColor.g = vertices[offset + 4];
  23453. startColor.b = vertices[offset + 5];
  23454. startColor.a = vertices[offset + 6];
  23455. endPosition.x = vertices[offset + 7];
  23456. endPosition.y = vertices[offset + 8];
  23457. endPosition.z = vertices[offset + 9];
  23458. endColor.r = vertices[offset + 10];
  23459. endColor.g = vertices[offset + 11];
  23460. endColor.b = vertices[offset + 12];
  23461. endColor.a = vertices[offset + 13];
  23462. }
  23463. _prepareRender(state) {
  23464. return true;
  23465. }
  23466. _render(state) {
  23467. if (this._minUpdate !== Number.MAX_VALUE && this._maxUpdate !== Number.MIN_VALUE) {
  23468. this._vertexBuffer.setData(this._vertices.buffer, this._minUpdate * 4, this._minUpdate * 4, (this._maxUpdate - this._minUpdate) * 4);
  23469. this._minUpdate = Number.MAX_VALUE;
  23470. this._maxUpdate = Number.MIN_VALUE;
  23471. }
  23472. if (this._lineCount > 0) {
  23473. this._bufferState.bind();
  23474. var gl = Laya.LayaGL.instance;
  23475. gl.drawArrays(gl.LINES, 0, this._lineCount * 2);
  23476. Laya.Stat.renderBatches++;
  23477. }
  23478. }
  23479. destroy() {
  23480. if (this._destroyed)
  23481. return;
  23482. super.destroy();
  23483. this._bufferState.destroy();
  23484. this._vertexBuffer.destroy();
  23485. this._bufferState = null;
  23486. this._vertexBuffer = null;
  23487. this._vertices = null;
  23488. }
  23489. }
  23490. PixelLineFilter._tempVector0 = new Vector3();
  23491. PixelLineFilter._tempVector1 = new Vector3();
  23492. PixelLineFilter._type = GeometryElement._typeCounter++;
  23493. class PixelLineRenderer extends BaseRender {
  23494. constructor(owner) {
  23495. super(owner);
  23496. this._projectionViewWorldMatrix = new Matrix4x4();
  23497. }
  23498. _calculateBoundingBox() {
  23499. var worldMat = this._owner.transform.worldMatrix;
  23500. var lineFilter = this._owner._geometryFilter;
  23501. lineFilter._reCalculateBound();
  23502. lineFilter._bounds._tranform(worldMat, this._bounds);
  23503. if (Laya.Render.supportWebGLPlusCulling) {
  23504. var min = this._bounds.getMin();
  23505. var max = this._bounds.getMax();
  23506. var buffer = FrustumCulling._cullingBuffer;
  23507. buffer[this._cullingBufferIndex + 1] = min.x;
  23508. buffer[this._cullingBufferIndex + 2] = min.y;
  23509. buffer[this._cullingBufferIndex + 3] = min.z;
  23510. buffer[this._cullingBufferIndex + 4] = max.x;
  23511. buffer[this._cullingBufferIndex + 5] = max.y;
  23512. buffer[this._cullingBufferIndex + 6] = max.z;
  23513. }
  23514. }
  23515. _renderUpdateWithCamera(context, transform) {
  23516. var projectionView = context.projectionViewMatrix;
  23517. var sv = this._shaderValues;
  23518. if (transform) {
  23519. var worldMat = transform.worldMatrix;
  23520. sv.setMatrix4x4(Sprite3D.WORLDMATRIX, worldMat);
  23521. Matrix4x4.multiply(projectionView, worldMat, this._projectionViewWorldMatrix);
  23522. sv.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  23523. }
  23524. else {
  23525. sv.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  23526. sv.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  23527. }
  23528. }
  23529. }
  23530. class PixelLineSprite3D extends RenderableSprite3D {
  23531. get maxLineCount() {
  23532. return this._geometryFilter._maxLineCount;
  23533. }
  23534. set maxLineCount(value) {
  23535. this._geometryFilter._resizeLineData(value);
  23536. this._geometryFilter._lineCount = Math.min(this._geometryFilter._lineCount, value);
  23537. }
  23538. get lineCount() {
  23539. return this._geometryFilter._lineCount;
  23540. }
  23541. set lineCount(value) {
  23542. if (value > this.maxLineCount)
  23543. throw "PixelLineSprite3D: lineCount can't large than maxLineCount";
  23544. else
  23545. this._geometryFilter._lineCount = value;
  23546. }
  23547. get pixelLineRenderer() {
  23548. return this._render;
  23549. }
  23550. constructor(maxCount = 2, name = null) {
  23551. super(name);
  23552. this._geometryFilter = new PixelLineFilter(this, maxCount);
  23553. this._render = new PixelLineRenderer(this);
  23554. this._changeRenderObjects(this._render, 0, PixelLineMaterial.defaultMaterial);
  23555. }
  23556. _changeRenderObjects(sender, index, material) {
  23557. var renderObjects = this._render._renderElements;
  23558. (material) || (material = PixelLineMaterial.defaultMaterial);
  23559. var renderElement = renderObjects[index];
  23560. (renderElement) || (renderElement = renderObjects[index] = new RenderElement());
  23561. renderElement.setTransform(this._transform);
  23562. renderElement.setGeometry(this._geometryFilter);
  23563. renderElement.render = this._render;
  23564. renderElement.material = material;
  23565. }
  23566. addLine(startPosition, endPosition, startColor, endColor) {
  23567. if (this._geometryFilter._lineCount !== this._geometryFilter._maxLineCount)
  23568. this._geometryFilter._updateLineData(this._geometryFilter._lineCount++, startPosition, endPosition, startColor, endColor);
  23569. else
  23570. throw "PixelLineSprite3D: lineCount has equal with maxLineCount.";
  23571. }
  23572. addLines(lines) {
  23573. var lineCount = this._geometryFilter._lineCount;
  23574. var addCount = lines.length;
  23575. if (lineCount + addCount > this._geometryFilter._maxLineCount) {
  23576. throw "PixelLineSprite3D: lineCount plus lines count must less than maxLineCount.";
  23577. }
  23578. else {
  23579. this._geometryFilter._updateLineDatas(lineCount, lines);
  23580. this._geometryFilter._lineCount += addCount;
  23581. }
  23582. }
  23583. removeLine(index) {
  23584. if (index < this._geometryFilter._lineCount)
  23585. this._geometryFilter._removeLineData(index);
  23586. else
  23587. throw "PixelLineSprite3D: index must less than lineCount.";
  23588. }
  23589. setLine(index, startPosition, endPosition, startColor, endColor) {
  23590. if (index < this._geometryFilter._lineCount)
  23591. this._geometryFilter._updateLineData(index, startPosition, endPosition, startColor, endColor);
  23592. else
  23593. throw "PixelLineSprite3D: index must less than lineCount.";
  23594. }
  23595. getLine(index, out) {
  23596. if (index < this.lineCount)
  23597. this._geometryFilter._getLineData(index, out);
  23598. else
  23599. throw "PixelLineSprite3D: index must less than lineCount.";
  23600. }
  23601. clear() {
  23602. this._geometryFilter._lineCount = 0;
  23603. }
  23604. _create() {
  23605. return new PixelLineSprite3D();
  23606. }
  23607. }
  23608. class RenderQueue {
  23609. constructor(isTransparent = false) {
  23610. this.isTransparent = false;
  23611. this.elements = new SingletonList();
  23612. this.lastTransparentRenderElement = null;
  23613. this.lastTransparentBatched = false;
  23614. this.isTransparent = isTransparent;
  23615. }
  23616. _compare(left, right) {
  23617. var renderQueue = left.material.renderQueue - right.material.renderQueue;
  23618. if (renderQueue === 0) {
  23619. var sort = this.isTransparent ? right.render._distanceForSort - left.render._distanceForSort : left.render._distanceForSort - right.render._distanceForSort;
  23620. return sort + right.render.sortingFudge - left.render.sortingFudge;
  23621. }
  23622. else {
  23623. return renderQueue;
  23624. }
  23625. }
  23626. _partitionRenderObject(left, right) {
  23627. var elements = this.elements.elements;
  23628. var pivot = elements[Math.floor((right + left) / 2)];
  23629. while (left <= right) {
  23630. while (this._compare(elements[left], pivot) < 0)
  23631. left++;
  23632. while (this._compare(elements[right], pivot) > 0)
  23633. right--;
  23634. if (left < right) {
  23635. var temp = elements[left];
  23636. elements[left] = elements[right];
  23637. elements[right] = temp;
  23638. left++;
  23639. right--;
  23640. }
  23641. else if (left === right) {
  23642. left++;
  23643. break;
  23644. }
  23645. }
  23646. return left;
  23647. }
  23648. _quickSort(left, right) {
  23649. if (this.elements.length > 1) {
  23650. var index = this._partitionRenderObject(left, right);
  23651. var leftIndex = index - 1;
  23652. if (left < leftIndex)
  23653. this._quickSort(left, leftIndex);
  23654. if (index < right)
  23655. this._quickSort(index, right);
  23656. }
  23657. }
  23658. _render(context) {
  23659. var elements = this.elements.elements;
  23660. for (var i = 0, n = this.elements.length; i < n; i++)
  23661. elements[i]._render(context);
  23662. }
  23663. clear() {
  23664. this.elements.length = 0;
  23665. this.lastTransparentRenderElement = null;
  23666. this.lastTransparentBatched = false;
  23667. }
  23668. }
  23669. class BoundsOctreeNode {
  23670. constructor(octree, parent, baseLength, center) {
  23671. this._bounds = new BoundBox(new Vector3(), new Vector3());
  23672. this._objects = [];
  23673. this._isContaion = false;
  23674. this.center = new Vector3();
  23675. this.baseLength = 0.0;
  23676. this._setValues(octree, parent, baseLength, center);
  23677. }
  23678. static _encapsulates(outerBound, innerBound) {
  23679. return CollisionUtils.boxContainsBox(outerBound, innerBound) == ContainmentType.Contains;
  23680. }
  23681. _setValues(octree, parent, baseLength, center) {
  23682. this._octree = octree;
  23683. this._parent = parent;
  23684. this.baseLength = baseLength;
  23685. center.cloneTo(this.center);
  23686. var min = this._bounds.min;
  23687. var max = this._bounds.max;
  23688. var halfSize = (octree._looseness * baseLength) / 2;
  23689. min.setValue(center.x - halfSize, center.y - halfSize, center.z - halfSize);
  23690. max.setValue(center.x + halfSize, center.y + halfSize, center.z + halfSize);
  23691. }
  23692. _getChildBound(index) {
  23693. if (this._children != null && this._children[index]) {
  23694. return this._children[index]._bounds;
  23695. }
  23696. else {
  23697. var quarter = this.baseLength / 4;
  23698. var halfChildSize = ((this.baseLength / 2) * this._octree._looseness) / 2;
  23699. var bounds = BoundsOctreeNode._tempBoundBox;
  23700. var min = bounds.min;
  23701. var max = bounds.max;
  23702. switch (index) {
  23703. case 0:
  23704. min.x = this.center.x - quarter - halfChildSize;
  23705. min.y = this.center.y + quarter - halfChildSize;
  23706. min.z = this.center.z - quarter - halfChildSize;
  23707. max.x = this.center.x - quarter + halfChildSize;
  23708. max.y = this.center.y + quarter + halfChildSize;
  23709. max.z = this.center.z - quarter + halfChildSize;
  23710. break;
  23711. case 1:
  23712. min.x = this.center.x + quarter - halfChildSize;
  23713. min.y = this.center.y + quarter - halfChildSize;
  23714. min.z = this.center.z - quarter - halfChildSize;
  23715. max.x = this.center.x + quarter + halfChildSize;
  23716. max.y = this.center.y + quarter + halfChildSize;
  23717. max.z = this.center.z - quarter + halfChildSize;
  23718. break;
  23719. case 2:
  23720. min.x = this.center.x - quarter - halfChildSize;
  23721. min.y = this.center.y + quarter - halfChildSize;
  23722. min.z = this.center.z + quarter - halfChildSize;
  23723. max.x = this.center.x - quarter + halfChildSize;
  23724. max.y = this.center.y + quarter + halfChildSize;
  23725. max.z = this.center.z + quarter + halfChildSize;
  23726. break;
  23727. case 3:
  23728. min.x = this.center.x + quarter - halfChildSize;
  23729. min.y = this.center.y + quarter - halfChildSize;
  23730. min.z = this.center.z + quarter - halfChildSize;
  23731. max.x = this.center.x + quarter + halfChildSize;
  23732. max.y = this.center.y + quarter + halfChildSize;
  23733. max.z = this.center.z + quarter + halfChildSize;
  23734. break;
  23735. case 4:
  23736. min.x = this.center.x - quarter - halfChildSize;
  23737. min.y = this.center.y - quarter - halfChildSize;
  23738. min.z = this.center.z - quarter - halfChildSize;
  23739. max.x = this.center.x - quarter + halfChildSize;
  23740. max.y = this.center.y - quarter + halfChildSize;
  23741. max.z = this.center.z - quarter + halfChildSize;
  23742. break;
  23743. case 5:
  23744. min.x = this.center.x + quarter - halfChildSize;
  23745. min.y = this.center.y - quarter - halfChildSize;
  23746. min.z = this.center.z - quarter - halfChildSize;
  23747. max.x = this.center.x + quarter + halfChildSize;
  23748. max.y = this.center.y - quarter + halfChildSize;
  23749. max.z = this.center.z - quarter + halfChildSize;
  23750. break;
  23751. case 6:
  23752. min.x = this.center.x - quarter - halfChildSize;
  23753. min.y = this.center.y - quarter - halfChildSize;
  23754. min.z = this.center.z + quarter - halfChildSize;
  23755. max.x = this.center.x - quarter + halfChildSize;
  23756. max.y = this.center.y - quarter + halfChildSize;
  23757. max.z = this.center.z + quarter + halfChildSize;
  23758. break;
  23759. case 7:
  23760. min.x = this.center.x + quarter - halfChildSize;
  23761. min.y = this.center.y - quarter - halfChildSize;
  23762. min.z = this.center.z + quarter - halfChildSize;
  23763. max.x = this.center.x + quarter + halfChildSize;
  23764. max.y = this.center.y - quarter + halfChildSize;
  23765. max.z = this.center.z + quarter + halfChildSize;
  23766. break;
  23767. default:
  23768. }
  23769. return bounds;
  23770. }
  23771. }
  23772. _getChildCenter(index) {
  23773. if (this._children != null) {
  23774. return this._children[index].center;
  23775. }
  23776. else {
  23777. var quarter = this.baseLength / 4;
  23778. var childCenter = BoundsOctreeNode._tempVector30;
  23779. switch (index) {
  23780. case 0:
  23781. childCenter.x = this.center.x - quarter;
  23782. childCenter.y = this.center.y + quarter;
  23783. childCenter.z = this.center.z - quarter;
  23784. break;
  23785. case 1:
  23786. childCenter.x = this.center.x + quarter;
  23787. childCenter.y = this.center.y + quarter;
  23788. childCenter.z = this.center.z - quarter;
  23789. break;
  23790. case 2:
  23791. childCenter.x = this.center.x - quarter;
  23792. childCenter.y = this.center.y + quarter;
  23793. childCenter.z = this.center.z + quarter;
  23794. break;
  23795. case 3:
  23796. childCenter.x = this.center.x + quarter;
  23797. childCenter.y = this.center.y + quarter;
  23798. childCenter.z = this.center.z + quarter;
  23799. break;
  23800. case 4:
  23801. childCenter.x = this.center.x - quarter;
  23802. childCenter.y = this.center.y - quarter;
  23803. childCenter.z = this.center.z - quarter;
  23804. break;
  23805. case 5:
  23806. childCenter.x = this.center.x + quarter;
  23807. childCenter.y = this.center.y - quarter;
  23808. childCenter.z = this.center.z - quarter;
  23809. break;
  23810. case 6:
  23811. childCenter.x = this.center.x - quarter;
  23812. childCenter.y = this.center.y - quarter;
  23813. childCenter.z = this.center.z + quarter;
  23814. break;
  23815. case 7:
  23816. childCenter.x = this.center.x + quarter;
  23817. childCenter.y = this.center.y - quarter;
  23818. childCenter.z = this.center.z + quarter;
  23819. break;
  23820. default:
  23821. }
  23822. return childCenter;
  23823. }
  23824. }
  23825. _getChild(index) {
  23826. var quarter = this.baseLength / 4;
  23827. this._children || (this._children = []);
  23828. switch (index) {
  23829. case 0:
  23830. return this._children[0] || (this._children[0] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + -quarter, this.center.y + quarter, this.center.z - quarter)));
  23831. case 1:
  23832. return this._children[1] || (this._children[1] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + quarter, this.center.y + quarter, this.center.z - quarter)));
  23833. case 2:
  23834. return this._children[2] || (this._children[2] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x - quarter, this.center.y + quarter, this.center.z + quarter)));
  23835. case 3:
  23836. return this._children[3] || (this._children[3] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + quarter, this.center.y + quarter, this.center.z + quarter)));
  23837. case 4:
  23838. return this._children[4] || (this._children[4] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x - quarter, this.center.y - quarter, this.center.z - quarter)));
  23839. case 5:
  23840. return this._children[5] || (this._children[5] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + quarter, this.center.y - quarter, this.center.z - quarter)));
  23841. case 6:
  23842. return this._children[6] || (this._children[6] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x - quarter, this.center.y - quarter, this.center.z + quarter)));
  23843. case 7:
  23844. return this._children[7] || (this._children[7] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + quarter, this.center.y - quarter, this.center.z + quarter)));
  23845. default:
  23846. throw "BoundsOctreeNode: unknown index.";
  23847. }
  23848. }
  23849. _shouldMerge() {
  23850. var objectCount = this._objects.length;
  23851. for (var i = 0; i < 8; i++) {
  23852. var child = this._children[i];
  23853. if (child) {
  23854. if (child._children != null)
  23855. return false;
  23856. objectCount += child._objects.length;
  23857. }
  23858. }
  23859. return objectCount <= BoundsOctreeNode._NUM_OBJECTS_ALLOWED;
  23860. }
  23861. _mergeChildren() {
  23862. for (var i = 0; i < 8; i++) {
  23863. var child = this._children[i];
  23864. if (child) {
  23865. child._parent = null;
  23866. var childObjects = child._objects;
  23867. for (var j = childObjects.length - 1; j >= 0; j--) {
  23868. var childObject = childObjects[j];
  23869. this._objects.push(childObject);
  23870. childObject._setOctreeNode(this);
  23871. }
  23872. }
  23873. }
  23874. this._children = null;
  23875. }
  23876. _merge() {
  23877. if (this._children === null) {
  23878. var parent = this._parent;
  23879. if (parent && parent._shouldMerge()) {
  23880. parent._mergeChildren();
  23881. parent._merge();
  23882. }
  23883. }
  23884. }
  23885. _checkAddNode(object) {
  23886. if (this._children == null) {
  23887. if (this._objects.length < BoundsOctreeNode._NUM_OBJECTS_ALLOWED || (this.baseLength / 2) < this._octree._minSize) {
  23888. return this;
  23889. }
  23890. for (var i = this._objects.length - 1; i >= 0; i--) {
  23891. var existObject = this._objects[i];
  23892. var fitChildIndex = this._bestFitChild(existObject.bounds.getCenter());
  23893. if (BoundsOctreeNode._encapsulates(this._getChildBound(fitChildIndex), existObject.bounds._getBoundBox())) {
  23894. this._objects.splice(this._objects.indexOf(existObject), 1);
  23895. this._getChild(fitChildIndex)._add(existObject);
  23896. }
  23897. }
  23898. }
  23899. var newFitChildIndex = this._bestFitChild(object.bounds.getCenter());
  23900. if (BoundsOctreeNode._encapsulates(this._getChildBound(newFitChildIndex), object.bounds._getBoundBox()))
  23901. return this._getChild(newFitChildIndex)._checkAddNode(object);
  23902. else
  23903. return this;
  23904. }
  23905. _add(object) {
  23906. var addNode = this._checkAddNode(object);
  23907. addNode._objects.push(object);
  23908. object._setOctreeNode(addNode);
  23909. }
  23910. _remove(object) {
  23911. var index = this._objects.indexOf(object);
  23912. this._objects.splice(index, 1);
  23913. object._setOctreeNode(null);
  23914. this._merge();
  23915. }
  23916. _addUp(object) {
  23917. if ((CollisionUtils.boxContainsBox(this._bounds, object.bounds._getBoundBox()) === ContainmentType.Contains)) {
  23918. this._add(object);
  23919. return true;
  23920. }
  23921. else {
  23922. if (this._parent)
  23923. return this._parent._addUp(object);
  23924. else
  23925. return false;
  23926. }
  23927. }
  23928. _getCollidingWithFrustum(context, frustum, testVisible, camPos, customShader, replacementTag, isShadowCasterCull) {
  23929. if (testVisible) {
  23930. var type = frustum.containsBoundBox(this._bounds);
  23931. Laya.Stat.octreeNodeCulling++;
  23932. if (type === ContainmentType.Disjoint)
  23933. return;
  23934. testVisible = (type === ContainmentType.Intersects);
  23935. }
  23936. this._isContaion = !testVisible;
  23937. var camera = context.camera;
  23938. var scene = context.scene;
  23939. for (var i = 0, n = this._objects.length; i < n; i++) {
  23940. var render = this._objects[i];
  23941. var canPass;
  23942. if (isShadowCasterCull)
  23943. canPass = render._castShadow && render._enable;
  23944. else
  23945. canPass = camera._isLayerVisible(render._owner._layer) && render._enable;
  23946. if (canPass) {
  23947. if (testVisible) {
  23948. Laya.Stat.frustumCulling++;
  23949. if (!render._needRender(frustum, context))
  23950. continue;
  23951. }
  23952. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  23953. var elements = render._renderElements;
  23954. for (var j = 0, m = elements.length; j < m; j++) {
  23955. var element = elements[j];
  23956. element._update(scene, context, customShader, replacementTag);
  23957. }
  23958. }
  23959. }
  23960. if (this._children != null) {
  23961. for (i = 0; i < 8; i++) {
  23962. var child = this._children[i];
  23963. child && child._getCollidingWithFrustum(context, frustum, testVisible, camPos, customShader, replacementTag, isShadowCasterCull);
  23964. }
  23965. }
  23966. }
  23967. _getCollidingWithBoundBox(checkBound, testVisible, result) {
  23968. if (testVisible) {
  23969. var type = CollisionUtils.boxContainsBox(this._bounds, checkBound);
  23970. if (type === ContainmentType.Disjoint)
  23971. return;
  23972. testVisible = (type === ContainmentType.Intersects);
  23973. }
  23974. if (testVisible) {
  23975. for (var i = 0, n = this._objects.length; i < n; i++) {
  23976. var object = this._objects[i];
  23977. if (CollisionUtils.intersectsBoxAndBox(object.bounds._getBoundBox(), checkBound)) {
  23978. result.push(object);
  23979. }
  23980. }
  23981. }
  23982. if (this._children != null) {
  23983. for (i = 0; i < 8; i++) {
  23984. var child = this._children[i];
  23985. child._getCollidingWithBoundBox(checkBound, testVisible, result);
  23986. }
  23987. }
  23988. }
  23989. _bestFitChild(boundCenter) {
  23990. return (boundCenter.x <= this.center.x ? 0 : 1) + (boundCenter.y >= this.center.y ? 0 : 4) + (boundCenter.z <= this.center.z ? 0 : 2);
  23991. }
  23992. _update(object) {
  23993. if (CollisionUtils.boxContainsBox(this._bounds, object.bounds._getBoundBox()) === ContainmentType.Contains) {
  23994. var addNode = this._checkAddNode(object);
  23995. if (addNode !== object._getOctreeNode()) {
  23996. addNode._objects.push(object);
  23997. object._setOctreeNode(addNode);
  23998. var index = this._objects.indexOf(object);
  23999. this._objects.splice(index, 1);
  24000. this._merge();
  24001. }
  24002. return true;
  24003. }
  24004. else {
  24005. if (this._parent) {
  24006. var sucess = this._parent._addUp(object);
  24007. if (sucess) {
  24008. index = this._objects.indexOf(object);
  24009. this._objects.splice(index, 1);
  24010. this._merge();
  24011. }
  24012. return sucess;
  24013. }
  24014. else {
  24015. return false;
  24016. }
  24017. }
  24018. }
  24019. add(object) {
  24020. if (!BoundsOctreeNode._encapsulates(this._bounds, object.bounds._getBoundBox()))
  24021. return false;
  24022. this._add(object);
  24023. return true;
  24024. }
  24025. remove(object) {
  24026. if (object._getOctreeNode() !== this)
  24027. return false;
  24028. this._remove(object);
  24029. return true;
  24030. }
  24031. update(object) {
  24032. if (object._getOctreeNode() !== this)
  24033. return false;
  24034. return this._update(object);
  24035. }
  24036. shrinkIfPossible(minLength) {
  24037. if (this.baseLength < minLength * 2)
  24038. return this;
  24039. var bestFit = -1;
  24040. for (var i = 0, n = this._objects.length; i < n; i++) {
  24041. var object = this._objects[i];
  24042. var newBestFit = this._bestFitChild(object.bounds.getCenter());
  24043. if (i == 0 || newBestFit == bestFit) {
  24044. var childBounds = this._getChildBound(newBestFit);
  24045. if (BoundsOctreeNode._encapsulates(childBounds, object.bounds._getBoundBox()))
  24046. (i == 0) && (bestFit = newBestFit);
  24047. else
  24048. return this;
  24049. }
  24050. else {
  24051. return this;
  24052. }
  24053. }
  24054. if (this._children != null) {
  24055. var childHadContent = false;
  24056. for (i = 0, n = this._children.length; i < n; i++) {
  24057. var child = this._children[i];
  24058. if (child && child.hasAnyObjects()) {
  24059. if (childHadContent)
  24060. return this;
  24061. if (bestFit >= 0 && bestFit != i)
  24062. return this;
  24063. childHadContent = true;
  24064. bestFit = i;
  24065. }
  24066. }
  24067. }
  24068. else {
  24069. if (bestFit != -1) {
  24070. var childCenter = this._getChildCenter(bestFit);
  24071. this._setValues(this._octree, null, this.baseLength / 2, childCenter);
  24072. }
  24073. return this;
  24074. }
  24075. if (bestFit != -1) {
  24076. var newRoot = this._children[bestFit];
  24077. newRoot._parent = null;
  24078. return newRoot;
  24079. }
  24080. else {
  24081. return this;
  24082. }
  24083. }
  24084. hasAnyObjects() {
  24085. if (this._objects.length > 0)
  24086. return true;
  24087. if (this._children != null) {
  24088. for (var i = 0; i < 8; i++) {
  24089. var child = this._children[i];
  24090. if (child && child.hasAnyObjects())
  24091. return true;
  24092. }
  24093. }
  24094. return false;
  24095. }
  24096. getCollidingWithBoundBox(checkBound, result) {
  24097. this._getCollidingWithBoundBox(checkBound, true, result);
  24098. }
  24099. getCollidingWithRay(ray, result, maxDistance = Number.MAX_VALUE) {
  24100. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, this._bounds);
  24101. if (distance == -1 || distance > maxDistance)
  24102. return;
  24103. for (var i = 0, n = this._objects.length; i < n; i++) {
  24104. var object = this._objects[i];
  24105. distance = CollisionUtils.intersectsRayAndBoxRD(ray, object.bounds._getBoundBox());
  24106. if (distance !== -1 && distance <= maxDistance)
  24107. result.push(object);
  24108. }
  24109. if (this._children != null) {
  24110. for (i = 0; i < 8; i++) {
  24111. var child = this._children[i];
  24112. child.getCollidingWithRay(ray, result, maxDistance);
  24113. }
  24114. }
  24115. }
  24116. getCollidingWithFrustum(context, customShader, replacementTag, isShadowCasterCull) {
  24117. var cameraPos = context.camera.transform.position;
  24118. var boundFrustum = context.camera.boundFrustum;
  24119. this._getCollidingWithFrustum(context, boundFrustum, true, cameraPos, customShader, replacementTag, isShadowCasterCull);
  24120. }
  24121. isCollidingWithBoundBox(checkBound) {
  24122. if (!(CollisionUtils.intersectsBoxAndBox(this._bounds, checkBound)))
  24123. return false;
  24124. for (var i = 0, n = this._objects.length; i < n; i++) {
  24125. var object = this._objects[i];
  24126. if (CollisionUtils.intersectsBoxAndBox(object.bounds._getBoundBox(), checkBound))
  24127. return true;
  24128. }
  24129. if (this._children != null) {
  24130. for (i = 0; i < 8; i++) {
  24131. var child = this._children[i];
  24132. if (child.isCollidingWithBoundBox(checkBound))
  24133. return true;
  24134. }
  24135. }
  24136. return false;
  24137. }
  24138. isCollidingWithRay(ray, maxDistance = Number.MAX_VALUE) {
  24139. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, this._bounds);
  24140. if (distance == -1 || distance > maxDistance)
  24141. return false;
  24142. for (var i = 0, n = this._objects.length; i < n; i++) {
  24143. var object = this._objects[i];
  24144. distance = CollisionUtils.intersectsRayAndBoxRD(ray, object.bounds._getBoundBox());
  24145. if (distance !== -1 && distance <= maxDistance)
  24146. return true;
  24147. }
  24148. if (this._children != null) {
  24149. for (i = 0; i < 8; i++) {
  24150. var child = this._children[i];
  24151. if (child.isCollidingWithRay(ray, maxDistance))
  24152. return true;
  24153. }
  24154. }
  24155. return false;
  24156. }
  24157. getBound() {
  24158. return this._bounds;
  24159. }
  24160. drawAllBounds(debugLine, currentDepth, maxDepth) {
  24161. if (this._children === null && this._objects.length == 0)
  24162. return;
  24163. currentDepth++;
  24164. var color = BoundsOctreeNode._tempColor0;
  24165. if (this._isContaion) {
  24166. color.r = 0.0;
  24167. color.g = 0.0;
  24168. color.b = 1.0;
  24169. }
  24170. else {
  24171. var tint = maxDepth ? currentDepth / maxDepth : 0;
  24172. color.r = 1.0 - tint;
  24173. color.g = tint;
  24174. color.b = 0.0;
  24175. }
  24176. color.a = 0.3;
  24177. Utils3D._drawBound(debugLine, this._bounds, color);
  24178. if (this._children != null) {
  24179. for (var i = 0; i < 8; i++) {
  24180. var child = this._children[i];
  24181. child && child.drawAllBounds(debugLine, currentDepth, maxDepth);
  24182. }
  24183. }
  24184. }
  24185. drawAllObjects(debugLine, currentDepth, maxDepth) {
  24186. currentDepth++;
  24187. var color = BoundsOctreeNode._tempColor0;
  24188. if (this._isContaion) {
  24189. color.r = 0.0;
  24190. color.g = 0.0;
  24191. color.b = 1.0;
  24192. }
  24193. else {
  24194. var tint = maxDepth ? currentDepth / maxDepth : 0;
  24195. color.r = 1.0 - tint;
  24196. color.g = tint;
  24197. color.b = 0.0;
  24198. }
  24199. color.a = 1.0;
  24200. for (var i = 0, n = this._objects.length; i < n; i++)
  24201. Utils3D._drawBound(debugLine, this._objects[i].bounds._getBoundBox(), color);
  24202. if (this._children != null) {
  24203. for (i = 0; i < 8; i++) {
  24204. var child = this._children[i];
  24205. child && child.drawAllObjects(debugLine, currentDepth, maxDepth);
  24206. }
  24207. }
  24208. }
  24209. }
  24210. BoundsOctreeNode._tempVector3 = new Vector3();
  24211. BoundsOctreeNode._tempVector30 = new Vector3();
  24212. BoundsOctreeNode._tempVector31 = new Vector3();
  24213. BoundsOctreeNode._tempColor0 = new Color();
  24214. BoundsOctreeNode._tempBoundBox = new BoundBox(new Vector3(), new Vector3());
  24215. BoundsOctreeNode._NUM_OBJECTS_ALLOWED = 8;
  24216. class OctreeMotionList extends SingletonList {
  24217. constructor() {
  24218. super();
  24219. }
  24220. add(element) {
  24221. var index = element._getIndexInMotionList();
  24222. if (index !== -1)
  24223. throw "OctreeMotionList:element has in PhysicsUpdateList.";
  24224. this._add(element);
  24225. element._setIndexInMotionList(this.length++);
  24226. }
  24227. remove(element) {
  24228. var index = element._getIndexInMotionList();
  24229. this.length--;
  24230. if (index !== this.length) {
  24231. var end = this.elements[this.length];
  24232. this.elements[index] = end;
  24233. end._setIndexInMotionList(index);
  24234. }
  24235. element._setIndexInMotionList(-1);
  24236. }
  24237. }
  24238. class BoundsOctree {
  24239. constructor(initialWorldSize, initialWorldPos, minNodeSize, looseness) {
  24240. this._motionObjects = new OctreeMotionList();
  24241. this.count = 0;
  24242. if (minNodeSize > initialWorldSize) {
  24243. console.warn("Minimum node size must be at least as big as the initial world size. Was: " + minNodeSize + " Adjusted to: " + initialWorldSize);
  24244. minNodeSize = initialWorldSize;
  24245. }
  24246. this._initialSize = initialWorldSize;
  24247. this._minSize = minNodeSize;
  24248. this._looseness = Math.min(Math.max(looseness, 1.0), 2.0);
  24249. this._rootNode = new BoundsOctreeNode(this, null, initialWorldSize, initialWorldPos);
  24250. }
  24251. _getMaxDepth(node, depth) {
  24252. depth++;
  24253. var children = node._children;
  24254. if (children != null) {
  24255. var curDepth = depth;
  24256. for (var i = 0, n = children.length; i < n; i++) {
  24257. var child = children[i];
  24258. child && (depth = Math.max(this._getMaxDepth(child, curDepth), depth));
  24259. }
  24260. }
  24261. return depth;
  24262. }
  24263. _grow(growObjectCenter) {
  24264. var xDirection = growObjectCenter.x >= 0 ? 1 : -1;
  24265. var yDirection = growObjectCenter.y >= 0 ? 1 : -1;
  24266. var zDirection = growObjectCenter.z >= 0 ? 1 : -1;
  24267. var oldRoot = this._rootNode;
  24268. var half = this._rootNode.baseLength / 2;
  24269. var newLength = this._rootNode.baseLength * 2;
  24270. var rootCenter = this._rootNode.center;
  24271. var newCenter = new Vector3(rootCenter.x + xDirection * half, rootCenter.y + yDirection * half, rootCenter.z + zDirection * half);
  24272. this._rootNode = new BoundsOctreeNode(this, null, newLength, newCenter);
  24273. if (oldRoot.hasAnyObjects()) {
  24274. var rootPos = this._rootNode._bestFitChild(oldRoot.center);
  24275. var children = [];
  24276. for (var i = 0; i < 8; i++) {
  24277. if (i == rootPos) {
  24278. oldRoot._parent = this._rootNode;
  24279. children[i] = oldRoot;
  24280. }
  24281. }
  24282. this._rootNode._children = children;
  24283. }
  24284. }
  24285. add(object) {
  24286. var count = 0;
  24287. while (!this._rootNode.add(object)) {
  24288. var growCenter = BoundsOctree._tempVector30;
  24289. Vector3.subtract(object.bounds.getCenter(), this._rootNode.center, growCenter);
  24290. this._grow(growCenter);
  24291. if (++count > 20) {
  24292. throw "Aborted Add operation as it seemed to be going on forever (" + (count - 1) + ") attempts at growing the octree.";
  24293. }
  24294. }
  24295. this.count++;
  24296. }
  24297. remove(object) {
  24298. var removed = object._getOctreeNode().remove(object);
  24299. if (removed) {
  24300. this.count--;
  24301. }
  24302. return removed;
  24303. }
  24304. update(object) {
  24305. var count = 0;
  24306. var octreeNode = object._getOctreeNode();
  24307. if (octreeNode) {
  24308. while (!octreeNode._update(object)) {
  24309. var growCenter = BoundsOctree._tempVector30;
  24310. Vector3.subtract(object.bounds.getCenter(), this._rootNode.center, growCenter);
  24311. this._grow(growCenter);
  24312. if (++count > 20) {
  24313. throw "Aborted Add operation as it seemed to be going on forever (" + (count - 1) + ") attempts at growing the octree.";
  24314. }
  24315. }
  24316. return true;
  24317. }
  24318. else {
  24319. return false;
  24320. }
  24321. }
  24322. shrinkRootIfPossible() {
  24323. this._rootNode = this._rootNode.shrinkIfPossible(this._initialSize);
  24324. }
  24325. addMotionObject(object) {
  24326. this._motionObjects.add(object);
  24327. }
  24328. removeMotionObject(object) {
  24329. this._motionObjects.remove(object);
  24330. }
  24331. updateMotionObjects() {
  24332. var elements = this._motionObjects.elements;
  24333. for (var i = 0, n = this._motionObjects.length; i < n; i++) {
  24334. var object = elements[i];
  24335. this.update(object);
  24336. object._setIndexInMotionList(-1);
  24337. }
  24338. this._motionObjects.length = 0;
  24339. }
  24340. isCollidingWithBoundBox(checkBounds) {
  24341. return this._rootNode.isCollidingWithBoundBox(checkBounds);
  24342. }
  24343. isCollidingWithRay(ray, maxDistance = Number.MAX_VALUE) {
  24344. return this._rootNode.isCollidingWithRay(ray, maxDistance);
  24345. }
  24346. getCollidingWithBoundBox(checkBound, result) {
  24347. this._rootNode.getCollidingWithBoundBox(checkBound, result);
  24348. }
  24349. getCollidingWithRay(ray, result, maxDistance = Number.MAX_VALUE) {
  24350. this._rootNode.getCollidingWithRay(ray, result, maxDistance);
  24351. }
  24352. getCollidingWithFrustum(context, shader, replacementTag, isShadowCasterCull) {
  24353. this._rootNode.getCollidingWithFrustum(context, shader, replacementTag, isShadowCasterCull);
  24354. }
  24355. getMaxBounds() {
  24356. return this._rootNode.getBound();
  24357. }
  24358. drawAllBounds(pixelLine) {
  24359. var maxDepth = this._getMaxDepth(this._rootNode, -1);
  24360. this._rootNode.drawAllBounds(pixelLine, -1, maxDepth);
  24361. }
  24362. drawAllObjects(pixelLine) {
  24363. var maxDepth = this._getMaxDepth(this._rootNode, -1);
  24364. this._rootNode.drawAllObjects(pixelLine, -1, maxDepth);
  24365. }
  24366. }
  24367. BoundsOctree._tempVector30 = new Vector3();
  24368. class Scene3D extends Laya.Sprite {
  24369. constructor() {
  24370. super();
  24371. this._lightCount = 0;
  24372. this._pointLights = new LightQueue();
  24373. this._spotLights = new LightQueue();
  24374. this._directionLights = new DirectionLightQueue();
  24375. this._alternateLights = new AlternateLightQueue();
  24376. this._lightmaps = [];
  24377. this._skyRenderer = new SkyRenderer();
  24378. this._reflectionMode = 1;
  24379. this._input = new Input3D();
  24380. this._timer = Laya.ILaya.timer;
  24381. this._collsionTestList = [];
  24382. this._renders = new SimpleSingletonList();
  24383. this._opaqueQueue = new RenderQueue(false);
  24384. this._transparentQueue = new RenderQueue(true);
  24385. this._cameraPool = [];
  24386. this._animatorPool = new SimpleSingletonList();
  24387. this._scriptPool = new Array();
  24388. this._tempScriptPool = new Array();
  24389. this._needClearScriptPool = false;
  24390. this.currentCreationLayer = Math.pow(2, 0);
  24391. this.enableLight = true;
  24392. this._key = new Laya.SubmitKey();
  24393. this._time = 0;
  24394. this._pickIdToSprite = new Object();
  24395. if (Physics3D._enablePhysics)
  24396. this._physicsSimulation = new PhysicsSimulation(Scene3D.physicsSettings);
  24397. this._shaderValues = new ShaderData(null);
  24398. this.parallelSplitShadowMaps = [];
  24399. this.enableFog = false;
  24400. this.fogStart = 300;
  24401. this.fogRange = 1000;
  24402. this.fogColor = new Vector3(0.7, 0.7, 0.7);
  24403. this.ambientColor = new Vector3(0.212, 0.227, 0.259);
  24404. this.reflectionIntensity = 1.0;
  24405. (Config3D._config._multiLighting) || (this._shaderValues.addDefine(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING));
  24406. if (Laya.Render.supportWebGLPlusCulling) {
  24407. this._cullingBufferIndices = new Int32Array(1024);
  24408. this._cullingBufferResult = new Int32Array(1024);
  24409. }
  24410. this._scene = this;
  24411. this._input.__init__(Laya.Render.canvas, this);
  24412. if (Scene3D.octreeCulling) {
  24413. this._octree = new BoundsOctree(Scene3D.octreeInitialSize, Scene3D.octreeInitialCenter, Scene3D.octreeMinNodeSize, Scene3D.octreeLooseness);
  24414. }
  24415. if (FrustumCulling.debugFrustumCulling) {
  24416. this._debugTool = new PixelLineSprite3D();
  24417. var lineMaterial = new PixelLineMaterial();
  24418. lineMaterial.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  24419. lineMaterial.alphaTest = false;
  24420. lineMaterial.depthWrite = false;
  24421. lineMaterial.cull = RenderState.CULL_BACK;
  24422. lineMaterial.blend = RenderState.BLEND_ENABLE_ALL;
  24423. lineMaterial.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  24424. lineMaterial.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  24425. lineMaterial.depthTest = RenderState.DEPTHTEST_LESS;
  24426. this._debugTool.pixelLineRenderer.sharedMaterial = lineMaterial;
  24427. }
  24428. }
  24429. static __init__() {
  24430. var con = Config3D._config;
  24431. var multiLighting = con._multiLighting;
  24432. if (multiLighting) {
  24433. const width = 4;
  24434. var maxLightCount = con.maxLightCount;
  24435. var clusterSlices = con.lightClusterCount;
  24436. Cluster.instance = new Cluster(clusterSlices.x, clusterSlices.y, clusterSlices.z, Math.min(con.maxLightCount, con._maxAreaLightCountPerClusterAverage));
  24437. Scene3D._lightTexture = Utils3D._createFloatTextureBuffer(width, maxLightCount);
  24438. Scene3D._lightTexture.lock = true;
  24439. Scene3D._lightPixles = new Float32Array(maxLightCount * width * 4);
  24440. }
  24441. Scene3DShaderDeclaration.SHADERDEFINE_FOG = Shader3D.getDefineByName("FOG");
  24442. Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT = Shader3D.getDefineByName("DIRECTIONLIGHT");
  24443. Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT = Shader3D.getDefineByName("POINTLIGHT");
  24444. Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT = Shader3D.getDefineByName("SPOTLIGHT");
  24445. Scene3DShaderDeclaration.SHADERDEFINE_CAST_SHADOW = Shader3D.getDefineByName("CASTSHADOW");
  24446. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1 = Shader3D.getDefineByName("SHADOWMAP_PSSM1");
  24447. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2 = Shader3D.getDefineByName("SHADOWMAP_PSSM2");
  24448. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3 = Shader3D.getDefineByName("SHADOWMAP_PSSM3");
  24449. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO = Shader3D.getDefineByName("SHADOWMAP_PCF_NO");
  24450. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1 = Shader3D.getDefineByName("SHADOWMAP_PCF1");
  24451. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2 = Shader3D.getDefineByName("SHADOWMAP_PCF2");
  24452. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3 = Shader3D.getDefineByName("SHADOWMAP_PCF3");
  24453. Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP = Shader3D.getDefineByName("REFLECTMAP");
  24454. }
  24455. static load(url, complete) {
  24456. Laya.ILaya.loader.create(url, complete, null, Scene3D.HIERARCHY);
  24457. }
  24458. _allotPickColorByID(id, pickColor) {
  24459. var pickColorR = Math.floor(id / (255 * 255));
  24460. id -= pickColorR * 255 * 255;
  24461. var pickColorG = Math.floor(id / 255);
  24462. id -= pickColorG * 255;
  24463. var pickColorB = id;
  24464. pickColor.x = pickColorR / 255;
  24465. pickColor.y = pickColorG / 255;
  24466. pickColor.z = pickColorB / 255;
  24467. pickColor.w = 1.0;
  24468. }
  24469. _searchIDByPickColor(pickColor) {
  24470. var id = pickColor.x * 255 * 255 + pickColor.y * 255 + pickColor.z;
  24471. return id;
  24472. }
  24473. get url() {
  24474. return this._url;
  24475. }
  24476. get enableFog() {
  24477. return this._enableFog;
  24478. }
  24479. set enableFog(value) {
  24480. if (this._enableFog !== value) {
  24481. this._enableFog = value;
  24482. if (value) {
  24483. this._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_FOG);
  24484. }
  24485. else
  24486. this._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_FOG);
  24487. }
  24488. }
  24489. get fogColor() {
  24490. return this._shaderValues.getVector3(Scene3D.FOGCOLOR);
  24491. }
  24492. set fogColor(value) {
  24493. this._shaderValues.setVector3(Scene3D.FOGCOLOR, value);
  24494. }
  24495. get fogStart() {
  24496. return this._shaderValues.getNumber(Scene3D.FOGSTART);
  24497. }
  24498. set fogStart(value) {
  24499. this._shaderValues.setNumber(Scene3D.FOGSTART, value);
  24500. }
  24501. get fogRange() {
  24502. return this._shaderValues.getNumber(Scene3D.FOGRANGE);
  24503. }
  24504. set fogRange(value) {
  24505. this._shaderValues.setNumber(Scene3D.FOGRANGE, value);
  24506. }
  24507. get ambientColor() {
  24508. return this._shaderValues.getVector3(Scene3D.AMBIENTCOLOR);
  24509. }
  24510. set ambientColor(value) {
  24511. this._shaderValues.setVector3(Scene3D.AMBIENTCOLOR, value);
  24512. }
  24513. get skyRenderer() {
  24514. return this._skyRenderer;
  24515. }
  24516. get customReflection() {
  24517. return this._shaderValues.getTexture(Scene3D.REFLECTIONTEXTURE);
  24518. }
  24519. set customReflection(value) {
  24520. this._shaderValues.setTexture(Scene3D.REFLECTIONTEXTURE, value);
  24521. if (value)
  24522. this._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  24523. else
  24524. this._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_REFLECTMAP);
  24525. }
  24526. get reflectionIntensity() {
  24527. return this._shaderValues.getNumber(Scene3D.REFLETIONINTENSITY);
  24528. }
  24529. set reflectionIntensity(value) {
  24530. value = Math.max(Math.min(value, 1.0), 0.0);
  24531. this._shaderValues.setNumber(Scene3D.REFLETIONINTENSITY, value);
  24532. }
  24533. get physicsSimulation() {
  24534. return this._physicsSimulation;
  24535. }
  24536. get reflectionMode() {
  24537. return this._reflectionMode;
  24538. }
  24539. set reflectionMode(value) {
  24540. this._reflectionMode = value;
  24541. }
  24542. get timer() {
  24543. return this._timer;
  24544. }
  24545. set timer(value) {
  24546. this._timer = value;
  24547. }
  24548. get input() {
  24549. return this._input;
  24550. }
  24551. _setLightmapToChildNode(sprite) {
  24552. if (sprite instanceof RenderableSprite3D)
  24553. sprite._render._applyLightMapParams();
  24554. var children = sprite._children;
  24555. for (var i = 0, n = children.length; i < n; i++)
  24556. this._setLightmapToChildNode(children[i]);
  24557. }
  24558. _update() {
  24559. var delta = this.timer._delta / 1000;
  24560. this._time += delta;
  24561. this._shaderValues.setNumber(Scene3D.TIME, this._time);
  24562. var simulation = this._physicsSimulation;
  24563. if (Physics3D._enablePhysics && !PhysicsSimulation.disableSimulation) {
  24564. simulation._updatePhysicsTransformFromRender();
  24565. PhysicsComponent._addUpdateList = false;
  24566. simulation._simulate(delta);
  24567. simulation._updateCharacters();
  24568. PhysicsComponent._addUpdateList = true;
  24569. simulation._updateCollisions();
  24570. simulation._eventScripts();
  24571. }
  24572. this._input._update();
  24573. this._clearScript();
  24574. this._updateScript();
  24575. Animator._update(this);
  24576. this._lateUpdateScript();
  24577. }
  24578. _binarySearchIndexInCameraPool(camera) {
  24579. var start = 0;
  24580. var end = this._cameraPool.length - 1;
  24581. var mid;
  24582. while (start <= end) {
  24583. mid = Math.floor((start + end) / 2);
  24584. var midValue = this._cameraPool[mid]._renderingOrder;
  24585. if (midValue == camera._renderingOrder)
  24586. return mid;
  24587. else if (midValue > camera._renderingOrder)
  24588. end = mid - 1;
  24589. else
  24590. start = mid + 1;
  24591. }
  24592. return start;
  24593. }
  24594. onEnable() {
  24595. this._input._onCanvasEvent(Laya.Render.canvas);
  24596. }
  24597. onDisable() {
  24598. this._input._offCanvasEvent(Laya.Render.canvas);
  24599. }
  24600. _setCreateURL(url) {
  24601. this._url = Laya.URL.formatURL(url);
  24602. }
  24603. _getGroup() {
  24604. return this._group;
  24605. }
  24606. _setGroup(value) {
  24607. this._group = value;
  24608. }
  24609. _clearScript() {
  24610. if (this._needClearScriptPool) {
  24611. var scripts = this._scriptPool;
  24612. for (var i = 0, n = scripts.length; i < n; i++) {
  24613. var script = scripts[i];
  24614. if (script) {
  24615. script._indexInPool = this._tempScriptPool.length;
  24616. this._tempScriptPool.push(script);
  24617. }
  24618. }
  24619. this._scriptPool = this._tempScriptPool;
  24620. scripts.length = 0;
  24621. this._tempScriptPool = scripts;
  24622. this._needClearScriptPool = false;
  24623. }
  24624. }
  24625. _updateScript() {
  24626. var scripts = this._scriptPool;
  24627. for (var i = 0, n = scripts.length; i < n; i++) {
  24628. var script = scripts[i];
  24629. (script && script.enabled) && (script.onUpdate());
  24630. }
  24631. }
  24632. _lateUpdateScript() {
  24633. var scripts = this._scriptPool;
  24634. for (var i = 0, n = scripts.length; i < n; i++) {
  24635. var script = scripts[i];
  24636. (script && script.enabled) && (script.onLateUpdate());
  24637. }
  24638. }
  24639. _addScript(script) {
  24640. var scripts = this._scriptPool;
  24641. script._indexInPool = scripts.length;
  24642. scripts.push(script);
  24643. }
  24644. _removeScript(script) {
  24645. this._scriptPool[script._indexInPool] = null;
  24646. script._indexInPool = -1;
  24647. this._needClearScriptPool = true;
  24648. }
  24649. _preRenderScript() {
  24650. var scripts = this._scriptPool;
  24651. for (var i = 0, n = scripts.length; i < n; i++) {
  24652. var script = scripts[i];
  24653. (script && script.enabled) && (script.onPreRender());
  24654. }
  24655. }
  24656. _postRenderScript() {
  24657. var scripts = this._scriptPool;
  24658. for (var i = 0, n = scripts.length; i < n; i++) {
  24659. var script = scripts[i];
  24660. (script && script.enabled) && (script.onPostRender());
  24661. }
  24662. }
  24663. _prepareSceneToRender() {
  24664. var shaderValues = this._shaderValues;
  24665. var multiLighting = Config3D._config._multiLighting;
  24666. if (multiLighting) {
  24667. var ligTex = Scene3D._lightTexture;
  24668. var ligPix = Scene3D._lightPixles;
  24669. const pixelWidth = ligTex.width;
  24670. const floatWidth = pixelWidth * 4;
  24671. var curCount = 0;
  24672. var dirCount = this._directionLights._length;
  24673. var dirElements = this._directionLights._elements;
  24674. if (dirCount > 0) {
  24675. var sunLightIndex = this._directionLights.getSunLight();
  24676. for (var i = 0; i < dirCount; i++, curCount++) {
  24677. var dirLight = dirElements[i];
  24678. var dir = dirLight._direction;
  24679. var intCor = dirLight._intensityColor;
  24680. var off = floatWidth * curCount;
  24681. Vector3.scale(dirLight.color, dirLight._intensity, intCor);
  24682. dirLight.transform.worldMatrix.getForward(dir);
  24683. Vector3.normalize(dir, dir);
  24684. ligPix[off] = intCor.x;
  24685. ligPix[off + 1] = intCor.y;
  24686. ligPix[off + 2] = intCor.z;
  24687. ligPix[off + 4] = dir.x;
  24688. ligPix[off + 5] = dir.y;
  24689. ligPix[off + 6] = dir.z;
  24690. if (i == sunLightIndex) {
  24691. shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, intCor);
  24692. shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dir);
  24693. }
  24694. }
  24695. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  24696. }
  24697. else {
  24698. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  24699. }
  24700. var poiCount = this._pointLights._length;
  24701. if (poiCount > 0) {
  24702. var poiElements = this._pointLights._elements;
  24703. for (var i = 0; i < poiCount; i++, curCount++) {
  24704. var poiLight = poiElements[i];
  24705. var pos = poiLight.transform.position;
  24706. var intCor = poiLight._intensityColor;
  24707. var off = floatWidth * curCount;
  24708. Vector3.scale(poiLight.color, poiLight._intensity, intCor);
  24709. ligPix[off] = intCor.x;
  24710. ligPix[off + 1] = intCor.y;
  24711. ligPix[off + 2] = intCor.z;
  24712. ligPix[off + 3] = poiLight.range;
  24713. ligPix[off + 4] = pos.x;
  24714. ligPix[off + 5] = pos.y;
  24715. ligPix[off + 6] = pos.z;
  24716. }
  24717. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  24718. }
  24719. else {
  24720. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  24721. }
  24722. var spoCount = this._spotLights._length;
  24723. if (spoCount > 0) {
  24724. var spoElements = this._spotLights._elements;
  24725. for (var i = 0; i < spoCount; i++, curCount++) {
  24726. var spoLight = spoElements[i];
  24727. var dir = spoLight._direction;
  24728. var pos = spoLight.transform.position;
  24729. var intCor = spoLight._intensityColor;
  24730. var off = floatWidth * curCount;
  24731. Vector3.scale(spoLight.color, spoLight._intensity, intCor);
  24732. spoLight.transform.worldMatrix.getForward(dir);
  24733. Vector3.normalize(dir, dir);
  24734. ligPix[off] = intCor.x;
  24735. ligPix[off + 1] = intCor.y;
  24736. ligPix[off + 2] = intCor.z;
  24737. ligPix[off + 3] = spoLight.range;
  24738. ligPix[off + 4] = pos.x;
  24739. ligPix[off + 5] = pos.y;
  24740. ligPix[off + 6] = pos.z;
  24741. ligPix[off + 7] = spoLight.spotAngle * Math.PI / 180;
  24742. ligPix[off + 8] = dir.x;
  24743. ligPix[off + 9] = dir.y;
  24744. ligPix[off + 10] = dir.z;
  24745. }
  24746. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  24747. }
  24748. else {
  24749. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  24750. }
  24751. (curCount > 0) && (ligTex.setSubPixels(0, 0, pixelWidth, curCount, ligPix, 0));
  24752. shaderValues.setTexture(Scene3D.LIGHTBUFFER, ligTex);
  24753. shaderValues.setInt(Scene3D.DIRECTIONLIGHTCOUNT, this._directionLights._length);
  24754. shaderValues.setTexture(Scene3D.CLUSTERBUFFER, Cluster.instance._clusterTexture);
  24755. }
  24756. else {
  24757. if (this._directionLights._length > 0) {
  24758. var dirLight = this._directionLights._elements[0];
  24759. Vector3.scale(dirLight.color, dirLight._intensity, dirLight._intensityColor);
  24760. dirLight.transform.worldMatrix.getForward(dirLight._direction);
  24761. Vector3.normalize(dirLight._direction, dirLight._direction);
  24762. shaderValues.setVector3(Scene3D.LIGHTDIRCOLOR, dirLight._intensityColor);
  24763. shaderValues.setVector3(Scene3D.LIGHTDIRECTION, dirLight._direction);
  24764. shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, dirLight._intensityColor);
  24765. shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dirLight._direction);
  24766. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  24767. }
  24768. else {
  24769. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  24770. }
  24771. if (this._pointLights._length > 0) {
  24772. var poiLight = this._pointLights._elements[0];
  24773. Vector3.scale(poiLight.color, poiLight._intensity, poiLight._intensityColor);
  24774. shaderValues.setVector3(Scene3D.POINTLIGHTCOLOR, poiLight._intensityColor);
  24775. shaderValues.setVector3(Scene3D.POINTLIGHTPOS, poiLight.transform.position);
  24776. shaderValues.setNumber(Scene3D.POINTLIGHTRANGE, poiLight.range);
  24777. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  24778. }
  24779. else {
  24780. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  24781. }
  24782. if (this._spotLights._length > 0) {
  24783. var spotLight = this._spotLights._elements[0];
  24784. Vector3.scale(spotLight.color, spotLight._intensity, spotLight._intensityColor);
  24785. shaderValues.setVector3(Scene3D.SPOTLIGHTCOLOR, spotLight._intensityColor);
  24786. shaderValues.setVector3(Scene3D.SPOTLIGHTPOS, spotLight.transform.position);
  24787. spotLight.transform.worldMatrix.getForward(spotLight._direction);
  24788. Vector3.normalize(spotLight._direction, spotLight._direction);
  24789. shaderValues.setVector3(Scene3D.SPOTLIGHTDIRECTION, spotLight._direction);
  24790. shaderValues.setNumber(Scene3D.SPOTLIGHTRANGE, spotLight.range);
  24791. shaderValues.setNumber(Scene3D.SPOTLIGHTSPOTANGLE, spotLight.spotAngle * Math.PI / 180);
  24792. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  24793. }
  24794. else {
  24795. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  24796. }
  24797. }
  24798. }
  24799. _addCamera(camera) {
  24800. var index = this._binarySearchIndexInCameraPool(camera);
  24801. var order = camera._renderingOrder;
  24802. var count = this._cameraPool.length;
  24803. while (index < count && this._cameraPool[index]._renderingOrder <= order)
  24804. index++;
  24805. this._cameraPool.splice(index, 0, camera);
  24806. }
  24807. _removeCamera(camera) {
  24808. this._cameraPool.splice(this._cameraPool.indexOf(camera), 1);
  24809. }
  24810. _preCulling(context, camera, shader, replacementTag) {
  24811. FrustumCulling.renderObjectCulling(camera, this, context, shader, replacementTag, false);
  24812. }
  24813. _clear(gl, state) {
  24814. var viewport = state.viewport;
  24815. var camera = state.camera;
  24816. var renderTex = camera._getRenderTexture();
  24817. var vpX, vpY;
  24818. var vpW = viewport.width;
  24819. var vpH = viewport.height;
  24820. if (camera._needInternalRenderTexture()) {
  24821. vpX = 0;
  24822. vpY = 0;
  24823. }
  24824. else {
  24825. vpX = viewport.x;
  24826. vpY = camera._getCanvasHeight() - viewport.y - vpH;
  24827. }
  24828. gl.viewport(vpX, vpY, vpW, vpH);
  24829. var flag;
  24830. var clearFlag = camera.clearFlag;
  24831. if (clearFlag === BaseCamera.CLEARFLAG_SKY && !(camera.skyRenderer._isAvailable() || this._skyRenderer._isAvailable()))
  24832. clearFlag = BaseCamera.CLEARFLAG_SOLIDCOLOR;
  24833. switch (clearFlag) {
  24834. case BaseCamera.CLEARFLAG_SOLIDCOLOR:
  24835. var clearColor = camera.clearColor;
  24836. gl.enable(gl.SCISSOR_TEST);
  24837. gl.scissor(vpX, vpY, vpW, vpH);
  24838. if (clearColor)
  24839. gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  24840. else
  24841. gl.clearColor(0, 0, 0, 0);
  24842. if (renderTex) {
  24843. flag = gl.COLOR_BUFFER_BIT;
  24844. switch (renderTex.depthStencilFormat) {
  24845. case Laya.RenderTextureDepthFormat.DEPTH_16:
  24846. flag |= gl.DEPTH_BUFFER_BIT;
  24847. break;
  24848. case Laya.RenderTextureDepthFormat.STENCIL_8:
  24849. flag |= gl.STENCIL_BUFFER_BIT;
  24850. break;
  24851. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_16_8:
  24852. flag |= gl.DEPTH_BUFFER_BIT;
  24853. flag |= gl.STENCIL_BUFFER_BIT;
  24854. break;
  24855. }
  24856. }
  24857. else {
  24858. flag = gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;
  24859. }
  24860. Laya.WebGLContext.setDepthMask(gl, true);
  24861. gl.clear(flag);
  24862. gl.disable(gl.SCISSOR_TEST);
  24863. break;
  24864. case BaseCamera.CLEARFLAG_SKY:
  24865. case BaseCamera.CLEARFLAG_DEPTHONLY:
  24866. gl.enable(gl.SCISSOR_TEST);
  24867. gl.scissor(vpX, vpY, vpW, vpH);
  24868. if (renderTex) {
  24869. switch (renderTex.depthStencilFormat) {
  24870. case Laya.RenderTextureDepthFormat.DEPTH_16:
  24871. flag = gl.DEPTH_BUFFER_BIT;
  24872. break;
  24873. case Laya.RenderTextureDepthFormat.STENCIL_8:
  24874. flag = gl.STENCIL_BUFFER_BIT;
  24875. break;
  24876. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_16_8:
  24877. flag = gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT;
  24878. break;
  24879. }
  24880. }
  24881. else {
  24882. flag = gl.DEPTH_BUFFER_BIT;
  24883. }
  24884. Laya.WebGLContext.setDepthMask(gl, true);
  24885. gl.clear(flag);
  24886. gl.disable(gl.SCISSOR_TEST);
  24887. break;
  24888. case BaseCamera.CLEARFLAG_NONE:
  24889. break;
  24890. default:
  24891. throw new Error("BaseScene:camera clearFlag invalid.");
  24892. }
  24893. }
  24894. _renderScene(context) {
  24895. var camera = context.camera;
  24896. this._opaqueQueue._render(context);
  24897. if (camera.clearFlag === BaseCamera.CLEARFLAG_SKY) {
  24898. if (camera.skyRenderer._isAvailable())
  24899. camera.skyRenderer._render(context);
  24900. else if (this._skyRenderer._isAvailable())
  24901. this._skyRenderer._render(context);
  24902. }
  24903. this._transparentQueue._render(context);
  24904. if (FrustumCulling.debugFrustumCulling) {
  24905. var renderElements = this._debugTool._render._renderElements;
  24906. for (var i = 0, n = renderElements.length; i < n; i++) {
  24907. renderElements[i]._update(this, context, null, null);
  24908. renderElements[i]._render(context);
  24909. }
  24910. }
  24911. }
  24912. _parse(data, spriteMap) {
  24913. var lightMapsData = data.lightmaps;
  24914. if (lightMapsData) {
  24915. var lightMapCount = lightMapsData.length;
  24916. var lightmaps = [];
  24917. for (var i = 0; i < lightMapCount; i++)
  24918. lightmaps[i] = Laya.Loader.getRes(lightMapsData[i].path);
  24919. this.setlightmaps(lightmaps);
  24920. }
  24921. var ambientColorData = data.ambientColor;
  24922. if (ambientColorData) {
  24923. var ambCol = this.ambientColor;
  24924. ambCol.fromArray(ambientColorData);
  24925. this.ambientColor = ambCol;
  24926. }
  24927. var skyData = data.sky;
  24928. if (skyData) {
  24929. this._skyRenderer.material = Laya.Loader.getRes(skyData.material.path);
  24930. switch (skyData.mesh) {
  24931. case "SkyBox":
  24932. this._skyRenderer.mesh = SkyBox.instance;
  24933. break;
  24934. case "SkyDome":
  24935. this._skyRenderer.mesh = SkyDome.instance;
  24936. break;
  24937. default:
  24938. this.skyRenderer.mesh = SkyBox.instance;
  24939. }
  24940. }
  24941. var reflectionTextureData = data.reflectionTexture;
  24942. reflectionTextureData && (this.customReflection = Laya.Loader.getRes(reflectionTextureData));
  24943. this.enableFog = data.enableFog;
  24944. this.fogStart = data.fogStart;
  24945. this.fogRange = data.fogRange;
  24946. var fogColorData = data.fogColor;
  24947. if (fogColorData) {
  24948. var fogCol = this.fogColor;
  24949. fogCol.fromArray(fogColorData);
  24950. this.fogColor = fogCol;
  24951. }
  24952. }
  24953. _onActive() {
  24954. super._onActive();
  24955. Laya.ILaya.stage._scene3Ds.push(this);
  24956. }
  24957. _onInActive() {
  24958. super._onInActive();
  24959. var scenes = Laya.ILaya.stage._scene3Ds;
  24960. scenes.splice(scenes.indexOf(this), 1);
  24961. }
  24962. _addRenderObject(render) {
  24963. if (this._octree && render._supportOctree) {
  24964. this._octree.add(render);
  24965. }
  24966. else {
  24967. this._renders.add(render);
  24968. if (Laya.Render.supportWebGLPlusCulling) {
  24969. var indexInList = render._getIndexInList();
  24970. var length = this._cullingBufferIndices.length;
  24971. if (indexInList >= length) {
  24972. var tempIndices = this._cullingBufferIndices;
  24973. var tempResult = this._cullingBufferResult;
  24974. this._cullingBufferIndices = new Int32Array(length + 1024);
  24975. this._cullingBufferResult = new Int32Array(length + 1024);
  24976. this._cullingBufferIndices.set(tempIndices, 0);
  24977. this._cullingBufferResult.set(tempResult, 0);
  24978. }
  24979. this._cullingBufferIndices[indexInList] = render._cullingBufferIndex;
  24980. }
  24981. }
  24982. }
  24983. _removeRenderObject(render) {
  24984. if (this._octree && render._supportOctree) {
  24985. this._octree.remove(render);
  24986. }
  24987. else {
  24988. var endRender;
  24989. if (Laya.Render.supportWebGLPlusCulling) {
  24990. endRender = this._renders.elements[this._renders.length - 1];
  24991. }
  24992. this._renders.remove(render);
  24993. if (Laya.Render.supportWebGLPlusCulling) {
  24994. this._cullingBufferIndices[endRender._getIndexInList()] = endRender._cullingBufferIndex;
  24995. }
  24996. }
  24997. }
  24998. _getRenderQueue(index) {
  24999. if (index <= 2500)
  25000. return this._opaqueQueue;
  25001. else
  25002. return this._transparentQueue;
  25003. }
  25004. setlightmaps(value) {
  25005. var maps = this._lightmaps;
  25006. for (var i = 0, n = maps.length; i < n; i++)
  25007. maps[i]._removeReference();
  25008. if (value) {
  25009. var count = value.length;
  25010. maps.length = count;
  25011. for (i = 0; i < count; i++) {
  25012. var lightMap = value[i];
  25013. lightMap._addReference();
  25014. maps[i] = lightMap;
  25015. }
  25016. }
  25017. else {
  25018. throw new Error("Scene3D: value value can't be null.");
  25019. }
  25020. for (i = 0, n = this._children.length; i < n; i++)
  25021. this._setLightmapToChildNode(this._children[i]);
  25022. }
  25023. getlightmaps() {
  25024. return this._lightmaps.slice();
  25025. }
  25026. destroy(destroyChild = true) {
  25027. if (this.destroyed)
  25028. return;
  25029. super.destroy(destroyChild);
  25030. this._skyRenderer.destroy();
  25031. this._skyRenderer = null;
  25032. this._directionLights = null;
  25033. this._pointLights = null;
  25034. this._spotLights = null;
  25035. this._alternateLights = null;
  25036. this._lightmaps = null;
  25037. this._shaderValues = null;
  25038. this._renders = null;
  25039. this._cameraPool = null;
  25040. this._octree = null;
  25041. this.parallelSplitShadowMaps = null;
  25042. this._physicsSimulation && this._physicsSimulation._destroy();
  25043. Laya.Loader.clearRes(this.url);
  25044. }
  25045. render(ctx, x, y) {
  25046. ctx._curSubmit = Laya.SubmitBase.RENDERBASE;
  25047. this._children.length > 0 && ctx.addRenderObject(this);
  25048. }
  25049. renderSubmit() {
  25050. var gl = Laya.LayaGL.instance;
  25051. this._prepareSceneToRender();
  25052. var i, n, n1;
  25053. for (i = 0, n = this._cameraPool.length, n1 = n - 1; i < n; i++) {
  25054. if (Laya.Render.supportWebGLPlusRendering)
  25055. ShaderData.setRuntimeValueMode((i == n1) ? true : false);
  25056. var camera = this._cameraPool[i];
  25057. camera.enableRender && camera.render();
  25058. }
  25059. Laya.Context.set2DRenderConfig();
  25060. return 1;
  25061. }
  25062. getRenderType() {
  25063. return 0;
  25064. }
  25065. releaseRender() {
  25066. }
  25067. reUse(context, pos) {
  25068. return 0;
  25069. }
  25070. }
  25071. Scene3D.HIERARCHY = "HIERARCHY";
  25072. Scene3D.physicsSettings = new PhysicsSettings();
  25073. Scene3D.octreeCulling = false;
  25074. Scene3D.octreeInitialSize = 64.0;
  25075. Scene3D.octreeInitialCenter = new Vector3(0, 0, 0);
  25076. Scene3D.octreeMinNodeSize = 2.0;
  25077. Scene3D.octreeLooseness = 1.25;
  25078. Scene3D.REFLECTIONMODE_SKYBOX = 0;
  25079. Scene3D.REFLECTIONMODE_CUSTOM = 1;
  25080. Scene3D.FOGCOLOR = Shader3D.propertyNameToID("u_FogColor");
  25081. Scene3D.FOGSTART = Shader3D.propertyNameToID("u_FogStart");
  25082. Scene3D.FOGRANGE = Shader3D.propertyNameToID("u_FogRange");
  25083. Scene3D.DIRECTIONLIGHTCOUNT = Shader3D.propertyNameToID("u_DirationLightCount");
  25084. Scene3D.LIGHTBUFFER = Shader3D.propertyNameToID("u_LightBuffer");
  25085. Scene3D.CLUSTERBUFFER = Shader3D.propertyNameToID("u_LightClusterBuffer");
  25086. Scene3D.SUNLIGHTDIRECTION = Shader3D.propertyNameToID("u_SunLight.direction");
  25087. Scene3D.SUNLIGHTDIRCOLOR = Shader3D.propertyNameToID("u_SunLight.color");
  25088. Scene3D.LIGHTDIRECTION = Shader3D.propertyNameToID("u_DirectionLight.direction");
  25089. Scene3D.LIGHTDIRCOLOR = Shader3D.propertyNameToID("u_DirectionLight.color");
  25090. Scene3D.POINTLIGHTPOS = Shader3D.propertyNameToID("u_PointLight.position");
  25091. Scene3D.POINTLIGHTRANGE = Shader3D.propertyNameToID("u_PointLight.range");
  25092. Scene3D.POINTLIGHTATTENUATION = Shader3D.propertyNameToID("u_PointLight.attenuation");
  25093. Scene3D.POINTLIGHTCOLOR = Shader3D.propertyNameToID("u_PointLight.color");
  25094. Scene3D.SPOTLIGHTPOS = Shader3D.propertyNameToID("u_SpotLight.position");
  25095. Scene3D.SPOTLIGHTDIRECTION = Shader3D.propertyNameToID("u_SpotLight.direction");
  25096. Scene3D.SPOTLIGHTSPOTANGLE = Shader3D.propertyNameToID("u_SpotLight.spot");
  25097. Scene3D.SPOTLIGHTRANGE = Shader3D.propertyNameToID("u_SpotLight.range");
  25098. Scene3D.SPOTLIGHTCOLOR = Shader3D.propertyNameToID("u_SpotLight.color");
  25099. Scene3D.SHADOWDISTANCE = Shader3D.propertyNameToID("u_shadowPSSMDistance");
  25100. Scene3D.SHADOWLIGHTVIEWPROJECT = Shader3D.propertyNameToID("u_lightShadowVP");
  25101. Scene3D.SHADOWMAPPCFOFFSET = Shader3D.propertyNameToID("u_shadowPCFoffset");
  25102. Scene3D.SHADOWMAPTEXTURE1 = Shader3D.propertyNameToID("u_shadowMap1");
  25103. Scene3D.SHADOWMAPTEXTURE2 = Shader3D.propertyNameToID("u_shadowMap2");
  25104. Scene3D.SHADOWMAPTEXTURE3 = Shader3D.propertyNameToID("u_shadowMap3");
  25105. Scene3D.AMBIENTCOLOR = Shader3D.propertyNameToID("u_AmbientColor");
  25106. Scene3D.REFLECTIONTEXTURE = Shader3D.propertyNameToID("u_ReflectTexture");
  25107. Scene3D.REFLETIONINTENSITY = Shader3D.propertyNameToID("u_ReflectIntensity");
  25108. Scene3D.TIME = Shader3D.propertyNameToID("u_Time");
  25109. class SkinnedMeshSprite3DShaderDeclaration {
  25110. }
  25111. class SkinnedMeshRenderer extends MeshRenderer {
  25112. constructor(owner) {
  25113. super(owner);
  25114. this._bones = [];
  25115. this._skinnedDataLoopMarks = [];
  25116. this._localBounds = new Bounds(Vector3._ZERO, Vector3._ZERO);
  25117. this._cacheAnimationNode = [];
  25118. }
  25119. get localBounds() {
  25120. return this._localBounds;
  25121. }
  25122. set localBounds(value) {
  25123. this._localBounds = value;
  25124. }
  25125. get rootBone() {
  25126. return this._cacheRootBone;
  25127. }
  25128. set rootBone(value) {
  25129. if (this._cacheRootBone != value) {
  25130. if (this._cacheRootBone)
  25131. this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  25132. else
  25133. this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  25134. if (value)
  25135. value.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  25136. else
  25137. this._owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  25138. this._cacheRootBone = value;
  25139. this._onWorldMatNeedChange(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE);
  25140. }
  25141. }
  25142. get bones() {
  25143. return this._bones;
  25144. }
  25145. _computeSkinnedData() {
  25146. if (this._cacheMesh && this._cacheAvatar || this._cacheMesh && !this._cacheAvatar) {
  25147. var bindPoses = this._cacheMesh._inverseBindPoses;
  25148. var meshBindPoseIndices = this._cacheMesh._bindPoseIndices;
  25149. var pathMarks = this._cacheMesh._skinDataPathMarks;
  25150. for (var i = 0, n = this._cacheMesh.subMeshCount; i < n; i++) {
  25151. var subMeshBoneIndices = this._cacheMesh.getSubMesh(i)._boneIndicesList;
  25152. var subData = this._skinnedData[i];
  25153. for (var j = 0, m = subMeshBoneIndices.length; j < m; j++) {
  25154. var boneIndices = subMeshBoneIndices[j];
  25155. this._computeSubSkinnedData(bindPoses, boneIndices, meshBindPoseIndices, subData[j], pathMarks);
  25156. }
  25157. }
  25158. }
  25159. }
  25160. _computeSubSkinnedData(bindPoses, boneIndices, meshBindPoseInices, data, pathMarks) {
  25161. for (var k = 0, q = boneIndices.length; k < q; k++) {
  25162. var index = boneIndices[k];
  25163. if (this._skinnedDataLoopMarks[index] === Laya.Stat.loopCount) {
  25164. var p = pathMarks[index];
  25165. var preData = this._skinnedData[p[0]][p[1]];
  25166. var srcIndex = p[2] * 16;
  25167. var dstIndex = k * 16;
  25168. for (var d = 0; d < 16; d++)
  25169. data[dstIndex + d] = preData[srcIndex + d];
  25170. }
  25171. else {
  25172. if (!this._cacheAvatar) {
  25173. var boneIndex = meshBindPoseInices[index];
  25174. Utils3D._mulMatrixArray(this._bones[boneIndex].transform.worldMatrix.elements, bindPoses[boneIndex], data, k * 16);
  25175. }
  25176. else {
  25177. Utils3D._mulMatrixArray(this._cacheAnimationNode[index].transform.getWorldMatrix(), bindPoses[meshBindPoseInices[index]], data, k * 16);
  25178. }
  25179. this._skinnedDataLoopMarks[index] = Laya.Stat.loopCount;
  25180. }
  25181. }
  25182. }
  25183. _onWorldMatNeedChange(flag) {
  25184. this._boundsChange = true;
  25185. if (this._octreeNode) {
  25186. if (this._cacheAvatar) {
  25187. if (this._indexInOctreeMotionList === -1)
  25188. this._octreeNode._octree.addMotionObject(this);
  25189. }
  25190. else {
  25191. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  25192. if (flag) {
  25193. if (this._indexInOctreeMotionList === -1)
  25194. this._octreeNode._octree.addMotionObject(this);
  25195. }
  25196. }
  25197. }
  25198. }
  25199. _createRenderElement() {
  25200. return new RenderElement();
  25201. }
  25202. _onMeshChange(value) {
  25203. super._onMeshChange(value);
  25204. this._cacheMesh = value;
  25205. var subMeshCount = value.subMeshCount;
  25206. this._skinnedData = [];
  25207. this._skinnedDataLoopMarks.length = value._bindPoseIndices.length;
  25208. for (var i = 0; i < subMeshCount; i++) {
  25209. var subBoneIndices = value.getSubMesh(i)._boneIndicesList;
  25210. var subCount = subBoneIndices.length;
  25211. var subData = this._skinnedData[i] = [];
  25212. for (var j = 0; j < subCount; j++)
  25213. subData[j] = new Float32Array(subBoneIndices[j].length * 16);
  25214. }
  25215. (this._cacheAvatar && value) && (this._getCacheAnimationNodes());
  25216. }
  25217. _setCacheAnimator(animator) {
  25218. this._cacheAnimator = animator;
  25219. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  25220. this._setRootNode();
  25221. }
  25222. _calculateBoundingBox() {
  25223. if (!this._cacheAvatar) {
  25224. if (this._cacheRootBone)
  25225. this._localBounds._tranform(this._cacheRootBone.transform.worldMatrix, this._bounds);
  25226. else
  25227. this._localBounds._tranform(this._owner.transform.worldMatrix, this._bounds);
  25228. }
  25229. else {
  25230. if (this._cacheAnimator && this._rootBone) {
  25231. var worldMat = SkinnedMeshRenderer._tempMatrix4x4;
  25232. Utils3D.matrix4x4MultiplyMFM(this._cacheAnimator.owner.transform.worldMatrix, this._cacheRootAnimationNode.transform.getWorldMatrix(), worldMat);
  25233. this._localBounds._tranform(worldMat, this._bounds);
  25234. }
  25235. else {
  25236. super._calculateBoundingBox();
  25237. }
  25238. }
  25239. if (Laya.Render.supportWebGLPlusCulling) {
  25240. var min = this._bounds.getMin();
  25241. var max = this._bounds.getMax();
  25242. var buffer = FrustumCulling._cullingBuffer;
  25243. buffer[this._cullingBufferIndex + 1] = min.x;
  25244. buffer[this._cullingBufferIndex + 2] = min.y;
  25245. buffer[this._cullingBufferIndex + 3] = min.z;
  25246. buffer[this._cullingBufferIndex + 4] = max.x;
  25247. buffer[this._cullingBufferIndex + 5] = max.y;
  25248. buffer[this._cullingBufferIndex + 6] = max.z;
  25249. }
  25250. }
  25251. _renderUpdate(context, transform) {
  25252. if (this._cacheAnimator) {
  25253. this._computeSkinnedData();
  25254. if (!this._cacheAvatar) {
  25255. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  25256. }
  25257. else {
  25258. var aniOwnerTrans = this._cacheAnimator.owner._transform;
  25259. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, aniOwnerTrans.worldMatrix);
  25260. }
  25261. }
  25262. else {
  25263. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  25264. }
  25265. }
  25266. _renderUpdateWithCamera(context, transform) {
  25267. var projectionView = context.projectionViewMatrix;
  25268. if (this._cacheAnimator) {
  25269. if (!this._cacheAvatar) {
  25270. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  25271. }
  25272. else {
  25273. var aniOwnerTrans = this._cacheAnimator.owner._transform;
  25274. Matrix4x4.multiply(projectionView, aniOwnerTrans.worldMatrix, this._projectionViewWorldMatrix);
  25275. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  25276. }
  25277. }
  25278. else {
  25279. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  25280. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  25281. }
  25282. }
  25283. _destroy() {
  25284. super._destroy();
  25285. if (!this._cacheAvatar) {
  25286. if (this._cacheRootBone)
  25287. (!this._cacheRootBone.destroyed) && (this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  25288. else
  25289. (this._owner && !this._owner.destroyed) && (this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  25290. }
  25291. else {
  25292. if (this._cacheRootAnimationNode)
  25293. this._cacheRootAnimationNode.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  25294. }
  25295. }
  25296. get bounds() {
  25297. if (this._boundsChange || this._cacheAvatar) {
  25298. this._calculateBoundingBox();
  25299. this._boundsChange = false;
  25300. }
  25301. return this._bounds;
  25302. }
  25303. _setRootBone(name) {
  25304. this._rootBone = name;
  25305. this._setRootNode();
  25306. }
  25307. _setRootNode() {
  25308. var rootNode;
  25309. if (this._cacheAnimator && this._rootBone && this._cacheAvatar)
  25310. rootNode = this._cacheAnimator._avatarNodeMap[this._rootBone];
  25311. else
  25312. rootNode = null;
  25313. if (this._cacheRootAnimationNode != rootNode) {
  25314. this._onWorldMatNeedChange(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE);
  25315. this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  25316. if (this._cacheRootAnimationNode)
  25317. this._cacheRootAnimationNode.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  25318. (rootNode) && (rootNode.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  25319. this._cacheRootAnimationNode = rootNode;
  25320. }
  25321. }
  25322. _getCacheAnimationNodes() {
  25323. var meshBoneNames = this._cacheMesh._boneNames;
  25324. var bindPoseIndices = this._cacheMesh._bindPoseIndices;
  25325. var innerBindPoseCount = bindPoseIndices.length;
  25326. if (!Laya.Render.supportWebGLPlusAnimation) {
  25327. this._cacheAnimationNode.length = innerBindPoseCount;
  25328. var nodeMap = this._cacheAnimator._avatarNodeMap;
  25329. for (var i = 0; i < innerBindPoseCount; i++) {
  25330. var node = nodeMap[meshBoneNames[bindPoseIndices[i]]];
  25331. this._cacheAnimationNode[i] = node;
  25332. }
  25333. }
  25334. else {
  25335. this._cacheAnimationNodeIndices = new Uint16Array(innerBindPoseCount);
  25336. var nodeMapC = this._cacheAnimator._avatarNodeMap;
  25337. for (i = 0; i < innerBindPoseCount; i++) {
  25338. var nodeC = nodeMapC[meshBoneNames[bindPoseIndices[i]]];
  25339. this._cacheAnimationNodeIndices[i] = nodeC ? nodeC._worldMatrixIndex : 0;
  25340. }
  25341. }
  25342. }
  25343. _setCacheAvatar(value) {
  25344. if (this._cacheAvatar !== value) {
  25345. if (this._cacheMesh) {
  25346. this._cacheAvatar = value;
  25347. if (value) {
  25348. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  25349. this._getCacheAnimationNodes();
  25350. }
  25351. }
  25352. else {
  25353. this._cacheAvatar = value;
  25354. }
  25355. this._setRootNode();
  25356. }
  25357. }
  25358. _computeSubSkinnedDataNative(worldMatrixs, cacheAnimationNodeIndices, inverseBindPosesBuffer, boneIndices, bindPoseInices, data) {
  25359. Laya.LayaGL.instance.computeSubSkinnedData(worldMatrixs, cacheAnimationNodeIndices, inverseBindPosesBuffer, boneIndices, bindPoseInices, data);
  25360. }
  25361. _computeSkinnedDataForNative() {
  25362. if (this._cacheMesh && this._cacheAvatar || this._cacheMesh && !this._cacheAvatar) {
  25363. var bindPoses = this._cacheMesh._inverseBindPoses;
  25364. var meshBindPoseIndices = this._cacheMesh._bindPoseIndices;
  25365. var pathMarks = this._cacheMesh._skinDataPathMarks;
  25366. for (var i = 0, n = this._cacheMesh.subMeshCount; i < n; i++) {
  25367. var subMeshBoneIndices = this._cacheMesh.getSubMesh(i)._boneIndicesList;
  25368. var subData = this._skinnedData[i];
  25369. for (var j = 0, m = subMeshBoneIndices.length; j < m; j++) {
  25370. var boneIndices = subMeshBoneIndices[j];
  25371. if (this._cacheAvatar && Laya.Render.supportWebGLPlusAnimation)
  25372. this._computeSubSkinnedDataNative(this._cacheAnimator._animationNodeWorldMatrixs, this._cacheAnimationNodeIndices, this._cacheMesh._inverseBindPosesBuffer, boneIndices, meshBindPoseIndices, subData[j]);
  25373. else
  25374. this._computeSubSkinnedData(bindPoses, boneIndices, meshBindPoseIndices, subData[j], pathMarks);
  25375. }
  25376. }
  25377. }
  25378. }
  25379. }
  25380. SkinnedMeshRenderer._tempMatrix4x4 = new Matrix4x4();
  25381. class SkinnedMeshSprite3D extends RenderableSprite3D {
  25382. constructor(mesh = null, name = null) {
  25383. super(name);
  25384. this._meshFilter = new MeshFilter(this);
  25385. this._render = new SkinnedMeshRenderer(this);
  25386. (mesh) && (this._meshFilter.sharedMesh = mesh);
  25387. }
  25388. static __init__() {
  25389. SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE = Shader3D.getDefineByName("BONE");
  25390. }
  25391. get meshFilter() {
  25392. return this._meshFilter;
  25393. }
  25394. get skinnedMeshRenderer() {
  25395. return this._render;
  25396. }
  25397. _parse(data, spriteMap) {
  25398. super._parse(data, spriteMap);
  25399. var render = this.skinnedMeshRenderer;
  25400. var lightmapIndex = data.lightmapIndex;
  25401. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  25402. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  25403. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  25404. var meshPath;
  25405. meshPath = data.meshPath;
  25406. if (meshPath) {
  25407. var mesh = Laya.Loader.getRes(meshPath);
  25408. (mesh) && (this.meshFilter.sharedMesh = mesh);
  25409. }
  25410. var materials = data.materials;
  25411. if (materials) {
  25412. var sharedMaterials = render.sharedMaterials;
  25413. var materialCount = materials.length;
  25414. sharedMaterials.length = materialCount;
  25415. for (var i = 0; i < materialCount; i++) {
  25416. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  25417. }
  25418. render.sharedMaterials = sharedMaterials;
  25419. }
  25420. var boundBox = data.boundBox;
  25421. var min = boundBox.min;
  25422. var max = boundBox.max;
  25423. render.localBounds.setMin(new Vector3(min[0], min[1], min[2]));
  25424. render.localBounds.setMax(new Vector3(max[0], max[1], max[2]));
  25425. if (spriteMap) {
  25426. var rootBoneData = data.rootBone;
  25427. render.rootBone = spriteMap[rootBoneData];
  25428. var bonesData = data.bones;
  25429. var n;
  25430. for (i = 0, n = bonesData.length; i < n; i++)
  25431. render.bones.push(spriteMap[bonesData[i]]);
  25432. }
  25433. else {
  25434. (data.rootBone) && (render._setRootBone(data.rootBone));
  25435. }
  25436. }
  25437. _changeHierarchyAnimator(animator) {
  25438. super._changeHierarchyAnimator(animator);
  25439. this.skinnedMeshRenderer._setCacheAnimator(animator);
  25440. }
  25441. _changeAnimatorAvatar(avatar) {
  25442. this.skinnedMeshRenderer._setCacheAvatar(avatar);
  25443. }
  25444. _cloneTo(destObject, srcRoot, dstRoot) {
  25445. var meshSprite3D = destObject;
  25446. meshSprite3D.meshFilter.sharedMesh = this.meshFilter.sharedMesh;
  25447. var meshRender = this._render;
  25448. var destMeshRender = meshSprite3D._render;
  25449. destMeshRender.enable = meshRender.enable;
  25450. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  25451. destMeshRender.castShadow = meshRender.castShadow;
  25452. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  25453. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  25454. destMeshRender.receiveShadow = meshRender.receiveShadow;
  25455. destMeshRender.sortingFudge = meshRender.sortingFudge;
  25456. destMeshRender._rootBone = meshRender._rootBone;
  25457. var bones = meshRender.bones;
  25458. var destBones = destMeshRender.bones;
  25459. var bonesCount = bones.length;
  25460. destBones.length = bonesCount;
  25461. var rootBone = meshRender.rootBone;
  25462. if (rootBone) {
  25463. var pathes = Utils3D._getHierarchyPath(srcRoot, rootBone, SkinnedMeshSprite3D._tempArray0);
  25464. if (pathes)
  25465. destMeshRender.rootBone = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  25466. else
  25467. destMeshRender.rootBone = rootBone;
  25468. }
  25469. for (var i = 0; i < bones.length; i++) {
  25470. pathes = Utils3D._getHierarchyPath(srcRoot, bones[i], SkinnedMeshSprite3D._tempArray0);
  25471. if (pathes)
  25472. destBones[i] = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  25473. else
  25474. destBones[i] = bones[i];
  25475. }
  25476. var lbb = meshRender.localBounds;
  25477. (lbb) && (lbb.cloneTo(destMeshRender.localBounds));
  25478. super._cloneTo(destObject, srcRoot, dstRoot);
  25479. }
  25480. destroy(destroyChild = true) {
  25481. if (this.destroyed)
  25482. return;
  25483. super.destroy(destroyChild);
  25484. this._meshFilter.destroy();
  25485. }
  25486. _create() {
  25487. return new SkinnedMeshSprite3D();
  25488. }
  25489. }
  25490. SkinnedMeshSprite3D._tempArray0 = [];
  25491. SkinnedMeshSprite3D.BONES = Shader3D.propertyNameToID("u_Bones");
  25492. class TrailMaterial extends Material {
  25493. constructor() {
  25494. super();
  25495. this.setShaderName("Trail");
  25496. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  25497. this._shaderValues.setVector(TrailMaterial.TINTCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  25498. this.renderMode = TrailMaterial.RENDERMODE_ALPHABLENDED;
  25499. }
  25500. static __initDefine__() {
  25501. TrailMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  25502. TrailMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  25503. TrailMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  25504. }
  25505. get _TintColorR() {
  25506. return this._color.x;
  25507. }
  25508. set _TintColorR(value) {
  25509. this._color.x = value;
  25510. this.color = this._color;
  25511. }
  25512. get _TintColorG() {
  25513. return this._color.y;
  25514. }
  25515. set _TintColorG(value) {
  25516. this._color.y = value;
  25517. this.color = this._color;
  25518. }
  25519. get _TintColorB() {
  25520. return this._color.z;
  25521. }
  25522. set _TintColorB(value) {
  25523. this._color.z = value;
  25524. this.color = this._color;
  25525. }
  25526. get _TintColorA() {
  25527. return this._color.w;
  25528. }
  25529. set _TintColorA(value) {
  25530. this._color.w = value;
  25531. this.color = this._color;
  25532. }
  25533. get _MainTex_STX() {
  25534. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).x;
  25535. }
  25536. set _MainTex_STX(x) {
  25537. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25538. tilOff.x = x;
  25539. this.tilingOffset = tilOff;
  25540. }
  25541. get _MainTex_STY() {
  25542. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).y;
  25543. }
  25544. set _MainTex_STY(y) {
  25545. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25546. tilOff.y = y;
  25547. this.tilingOffset = tilOff;
  25548. }
  25549. get _MainTex_STZ() {
  25550. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).z;
  25551. }
  25552. set _MainTex_STZ(z) {
  25553. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25554. tilOff.z = z;
  25555. this.tilingOffset = tilOff;
  25556. }
  25557. get _MainTex_STW() {
  25558. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).w;
  25559. }
  25560. set _MainTex_STW(w) {
  25561. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25562. tilOff.w = w;
  25563. this.tilingOffset = tilOff;
  25564. }
  25565. set renderMode(value) {
  25566. switch (value) {
  25567. case TrailMaterial.RENDERMODE_ADDTIVE:
  25568. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  25569. this.alphaTest = false;
  25570. this.depthWrite = false;
  25571. this.cull = RenderState.CULL_NONE;
  25572. this.blend = RenderState.BLEND_ENABLE_ALL;
  25573. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  25574. this.blendDst = RenderState.BLENDPARAM_ONE;
  25575. this.depthTest = RenderState.DEPTHTEST_LESS;
  25576. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_ADDTIVEFOG);
  25577. break;
  25578. case TrailMaterial.RENDERMODE_ALPHABLENDED:
  25579. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  25580. this.alphaTest = false;
  25581. this.depthWrite = false;
  25582. this.cull = RenderState.CULL_NONE;
  25583. this.blend = RenderState.BLEND_ENABLE_ALL;
  25584. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  25585. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  25586. this.depthTest = RenderState.DEPTHTEST_LESS;
  25587. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_ADDTIVEFOG);
  25588. break;
  25589. default:
  25590. throw new Error("TrailMaterial : renderMode value error.");
  25591. }
  25592. }
  25593. get colorR() {
  25594. return this._TintColorR;
  25595. }
  25596. set colorR(value) {
  25597. this._TintColorR = value;
  25598. }
  25599. get colorG() {
  25600. return this._TintColorG;
  25601. }
  25602. set colorG(value) {
  25603. this._TintColorG = value;
  25604. }
  25605. get colorB() {
  25606. return this._TintColorB;
  25607. }
  25608. set colorB(value) {
  25609. this._TintColorB = value;
  25610. }
  25611. get colorA() {
  25612. return this._TintColorA;
  25613. }
  25614. set colorA(value) {
  25615. this._TintColorA = value;
  25616. }
  25617. get color() {
  25618. return this._shaderValues.getVector(TrailMaterial.TINTCOLOR);
  25619. }
  25620. set color(value) {
  25621. this._shaderValues.setVector(TrailMaterial.TINTCOLOR, value);
  25622. }
  25623. get texture() {
  25624. return this._shaderValues.getTexture(TrailMaterial.MAINTEXTURE);
  25625. }
  25626. set texture(value) {
  25627. if (value)
  25628. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_MAINTEXTURE);
  25629. else
  25630. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_MAINTEXTURE);
  25631. this._shaderValues.setTexture(TrailMaterial.MAINTEXTURE, value);
  25632. }
  25633. get tilingOffsetX() {
  25634. return this._MainTex_STX;
  25635. }
  25636. set tilingOffsetX(x) {
  25637. this._MainTex_STX = x;
  25638. }
  25639. get tilingOffsetY() {
  25640. return this._MainTex_STY;
  25641. }
  25642. set tilingOffsetY(y) {
  25643. this._MainTex_STY = y;
  25644. }
  25645. get tilingOffsetZ() {
  25646. return this._MainTex_STZ;
  25647. }
  25648. set tilingOffsetZ(z) {
  25649. this._MainTex_STZ = z;
  25650. }
  25651. get tilingOffsetW() {
  25652. return this._MainTex_STW;
  25653. }
  25654. set tilingOffsetW(w) {
  25655. this._MainTex_STW = w;
  25656. }
  25657. get tilingOffset() {
  25658. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  25659. }
  25660. set tilingOffset(value) {
  25661. if (value) {
  25662. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  25663. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  25664. else
  25665. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  25666. }
  25667. else {
  25668. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  25669. }
  25670. this._shaderValues.setVector(TrailMaterial.TILINGOFFSET, value);
  25671. }
  25672. set depthWrite(value) {
  25673. this._shaderValues.setBool(TrailMaterial.DEPTH_WRITE, value);
  25674. }
  25675. get depthWrite() {
  25676. return this._shaderValues.getBool(TrailMaterial.DEPTH_WRITE);
  25677. }
  25678. set cull(value) {
  25679. this._shaderValues.setInt(TrailMaterial.CULL, value);
  25680. }
  25681. get cull() {
  25682. return this._shaderValues.getInt(TrailMaterial.CULL);
  25683. }
  25684. set blend(value) {
  25685. this._shaderValues.setInt(TrailMaterial.BLEND, value);
  25686. }
  25687. get blend() {
  25688. return this._shaderValues.getInt(TrailMaterial.BLEND);
  25689. }
  25690. set blendSrc(value) {
  25691. this._shaderValues.setInt(TrailMaterial.BLEND_SRC, value);
  25692. }
  25693. get blendSrc() {
  25694. return this._shaderValues.getInt(TrailMaterial.BLEND_SRC);
  25695. }
  25696. set blendDst(value) {
  25697. this._shaderValues.setInt(TrailMaterial.BLEND_DST, value);
  25698. }
  25699. get blendDst() {
  25700. return this._shaderValues.getInt(TrailMaterial.BLEND_DST);
  25701. }
  25702. set depthTest(value) {
  25703. this._shaderValues.setInt(TrailMaterial.DEPTH_TEST, value);
  25704. }
  25705. get depthTest() {
  25706. return this._shaderValues.getInt(TrailMaterial.DEPTH_TEST);
  25707. }
  25708. clone() {
  25709. var dest = new TrailMaterial();
  25710. this.cloneTo(dest);
  25711. return dest;
  25712. }
  25713. }
  25714. TrailMaterial.RENDERMODE_ALPHABLENDED = 0;
  25715. TrailMaterial.RENDERMODE_ADDTIVE = 1;
  25716. TrailMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_MainTexture");
  25717. TrailMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_MainColor");
  25718. TrailMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  25719. TrailMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  25720. TrailMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  25721. TrailMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  25722. TrailMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  25723. TrailMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  25724. TrailMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  25725. class TextureMode {
  25726. }
  25727. TextureMode.Stretch = 0;
  25728. TextureMode.Tile = 1;
  25729. (function (TrailAlignment) {
  25730. TrailAlignment[TrailAlignment["View"] = 0] = "View";
  25731. TrailAlignment[TrailAlignment["TransformZ"] = 1] = "TransformZ";
  25732. })(exports.TrailAlignment || (exports.TrailAlignment = {}));
  25733. class VertexTrail {
  25734. static get vertexDeclaration1() {
  25735. return VertexTrail._vertexDeclaration1;
  25736. }
  25737. static get vertexDeclaration2() {
  25738. return VertexTrail._vertexDeclaration2;
  25739. }
  25740. get vertexDeclaration() {
  25741. return VertexTrail._vertexDeclaration1;
  25742. }
  25743. static __init__() {
  25744. VertexTrail._vertexDeclaration1 = new VertexDeclaration(32, [new VertexElement(0, VertexElementFormat.Vector3, VertexTrail.TRAIL_POSITION0),
  25745. new VertexElement(12, VertexElementFormat.Vector3, VertexTrail.TRAIL_OFFSETVECTOR),
  25746. new VertexElement(24, VertexElementFormat.Single, VertexTrail.TRAIL_TIME0),
  25747. new VertexElement(28, VertexElementFormat.Single, VertexTrail.TRAIL_TEXTURECOORDINATE0Y)]);
  25748. VertexTrail._vertexDeclaration2 = new VertexDeclaration(20, [new VertexElement(0, VertexElementFormat.Single, VertexTrail.TRAIL_TEXTURECOORDINATE0X),
  25749. new VertexElement(4, VertexElementFormat.Color, VertexTrail.TRAIL_COLOR)]);
  25750. }
  25751. }
  25752. VertexTrail.TRAIL_POSITION0 = 0;
  25753. VertexTrail.TRAIL_OFFSETVECTOR = 1;
  25754. VertexTrail.TRAIL_TIME0 = 2;
  25755. VertexTrail.TRAIL_TEXTURECOORDINATE0Y = 3;
  25756. VertexTrail.TRAIL_TEXTURECOORDINATE0X = 4;
  25757. VertexTrail.TRAIL_COLOR = 5;
  25758. class TrailGeometry extends GeometryElement {
  25759. constructor(owner) {
  25760. super();
  25761. this._floatCountPerVertices1 = 8;
  25762. this._floatCountPerVertices2 = 5;
  25763. this._increaseSegementCount = 16;
  25764. this._activeIndex = 0;
  25765. this._endIndex = 0;
  25766. this._needAddFirstVertex = false;
  25767. this._isTempEndVertex = false;
  25768. this._vertices1 = null;
  25769. this._vertices2 = null;
  25770. this._lastFixedVertexPosition = new Vector3();
  25771. this._bufferState = new BufferState();
  25772. this.tmpColor = new Color();
  25773. this._disappearBoundsMode = false;
  25774. this._owner = owner;
  25775. this._segementCount = this._increaseSegementCount;
  25776. this._resizeData(this._segementCount, this._bufferState);
  25777. var bounds = this._owner._owner.trailRenderer.bounds;
  25778. var sprite3dPosition = this._owner._owner.transform.position;
  25779. bounds.setMin(sprite3dPosition);
  25780. bounds.setMax(sprite3dPosition);
  25781. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  25782. }
  25783. _resizeData(segementCount, bufferState) {
  25784. this._subBirthTime = new Float32Array(segementCount);
  25785. this._subDistance = new Float64Array(segementCount);
  25786. var gl = Laya.LayaGL.instance;
  25787. var vertexCount = segementCount * 2;
  25788. var vertexDeclaration1 = VertexTrail.vertexDeclaration1;
  25789. var vertexDeclaration2 = VertexTrail.vertexDeclaration2;
  25790. var vertexBuffers = [];
  25791. var vertexbuffer1Size = vertexCount * vertexDeclaration1.vertexStride;
  25792. var vertexbuffer2Size = vertexCount * vertexDeclaration2.vertexStride;
  25793. var memorySize = vertexbuffer1Size + vertexbuffer2Size;
  25794. this._vertices1 = new Float32Array(vertexCount * this._floatCountPerVertices1);
  25795. this._vertices2 = new Float32Array(vertexCount * this._floatCountPerVertices2);
  25796. this._vertexBuffer1 = new VertexBuffer3D(vertexbuffer1Size, gl.STATIC_DRAW, false);
  25797. this._vertexBuffer1.vertexDeclaration = vertexDeclaration1;
  25798. this._vertexBuffer2 = new VertexBuffer3D(vertexbuffer2Size, gl.DYNAMIC_DRAW, false);
  25799. this._vertexBuffer2.vertexDeclaration = vertexDeclaration2;
  25800. vertexBuffers.push(this._vertexBuffer1);
  25801. vertexBuffers.push(this._vertexBuffer2);
  25802. bufferState.bind();
  25803. bufferState.applyVertexBuffers(vertexBuffers);
  25804. bufferState.unBind();
  25805. Laya.Resource._addMemory(memorySize, memorySize);
  25806. }
  25807. _resetData() {
  25808. var count = this._endIndex - this._activeIndex;
  25809. var oldVertices1 = new Float32Array(this._vertices1.buffer, this._floatCountPerVertices1 * 2 * this._activeIndex * 4, this._floatCountPerVertices1 * 2 * count);
  25810. var oldVertices2 = new Float32Array(this._vertices2.buffer, this._floatCountPerVertices2 * 2 * this._activeIndex * 4, this._floatCountPerVertices2 * 2 * count);
  25811. var oldSubDistance = new Float64Array(this._subDistance.buffer, this._activeIndex * 8, count);
  25812. var oldSubBirthTime = new Float32Array(this._subBirthTime.buffer, this._activeIndex * 4, count);
  25813. if (count === this._segementCount) {
  25814. this._vertexBuffer1.destroy();
  25815. this._vertexBuffer2.destroy();
  25816. this._segementCount += this._increaseSegementCount;
  25817. this._resizeData(this._segementCount, this._bufferState);
  25818. }
  25819. this._vertices1.set(oldVertices1, 0);
  25820. this._vertices2.set(oldVertices2, 0);
  25821. this._subDistance.set(oldSubDistance, 0);
  25822. this._subBirthTime.set(oldSubBirthTime, 0);
  25823. this._endIndex = count;
  25824. this._activeIndex = 0;
  25825. this._vertexBuffer1.setData(this._vertices1.buffer, 0, this._floatCountPerVertices1 * 2 * this._activeIndex * 4, this._floatCountPerVertices1 * 2 * count * 4);
  25826. this._vertexBuffer2.setData(this._vertices2.buffer, 0, this._floatCountPerVertices2 * 2 * this._activeIndex * 4, this._floatCountPerVertices2 * 2 * count * 4);
  25827. }
  25828. _updateTrail(camera, lastPosition, position) {
  25829. if (!Vector3.equals(lastPosition, position)) {
  25830. if ((this._endIndex - this._activeIndex) === 0)
  25831. this._addTrailByFirstPosition(camera, position);
  25832. else
  25833. this._addTrailByNextPosition(camera, position);
  25834. }
  25835. }
  25836. _addTrailByFirstPosition(camera, position) {
  25837. (this._endIndex === this._segementCount) && (this._resetData());
  25838. this._subDistance[this._endIndex] = 0;
  25839. this._subBirthTime[this._endIndex] = this._owner._curtime;
  25840. this._endIndex++;
  25841. position.cloneTo(this._lastFixedVertexPosition);
  25842. this._needAddFirstVertex = true;
  25843. }
  25844. _addTrailByNextPosition(camera, position) {
  25845. var delVector3 = TrailGeometry._tempVector30;
  25846. var pointAtoBVector3 = TrailGeometry._tempVector31;
  25847. switch (this._owner.alignment) {
  25848. case exports.TrailAlignment.View:
  25849. var cameraMatrix = camera.viewMatrix;
  25850. Vector3.transformCoordinate(position, cameraMatrix, TrailGeometry._tempVector33);
  25851. Vector3.transformCoordinate(this._lastFixedVertexPosition, cameraMatrix, TrailGeometry._tempVector34);
  25852. Vector3.subtract(TrailGeometry._tempVector33, TrailGeometry._tempVector34, delVector3);
  25853. Vector3.cross(TrailGeometry._tempVector33, delVector3, pointAtoBVector3);
  25854. break;
  25855. case exports.TrailAlignment.TransformZ:
  25856. Vector3.subtract(position, this._lastFixedVertexPosition, delVector3);
  25857. var forward = TrailGeometry._tempVector32;
  25858. this._owner._owner.transform.localMatrix.getForward(forward);
  25859. Vector3.cross(delVector3, forward, pointAtoBVector3);
  25860. break;
  25861. }
  25862. Vector3.normalize(pointAtoBVector3, pointAtoBVector3);
  25863. Vector3.scale(pointAtoBVector3, this._owner.widthMultiplier / 2, pointAtoBVector3);
  25864. var delLength = Vector3.scalarLength(delVector3);
  25865. var tempEndIndex;
  25866. var offset;
  25867. if (this._needAddFirstVertex) {
  25868. this._updateVerticesByPositionData(position, pointAtoBVector3, this._endIndex - 1);
  25869. this._needAddFirstVertex = false;
  25870. }
  25871. if (delLength - this._owner.minVertexDistance >= MathUtils3D.zeroTolerance) {
  25872. if (this._isTempEndVertex) {
  25873. tempEndIndex = this._endIndex - 1;
  25874. offset = delLength - this._subDistance[tempEndIndex];
  25875. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, tempEndIndex);
  25876. this._owner._totalLength += offset;
  25877. }
  25878. else {
  25879. (this._endIndex === this._segementCount) && (this._resetData());
  25880. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, this._endIndex);
  25881. this._owner._totalLength += delLength;
  25882. this._endIndex++;
  25883. }
  25884. position.cloneTo(this._lastFixedVertexPosition);
  25885. this._isTempEndVertex = false;
  25886. }
  25887. else {
  25888. if (this._isTempEndVertex) {
  25889. tempEndIndex = this._endIndex - 1;
  25890. offset = delLength - this._subDistance[tempEndIndex];
  25891. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, tempEndIndex);
  25892. this._owner._totalLength += offset;
  25893. }
  25894. else {
  25895. (this._endIndex === this._segementCount) && (this._resetData());
  25896. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, this._endIndex);
  25897. this._owner._totalLength += delLength;
  25898. this._endIndex++;
  25899. }
  25900. this._isTempEndVertex = true;
  25901. }
  25902. }
  25903. _updateVerticesByPositionData(position, pointAtoBVector3, index) {
  25904. var vertexOffset = this._floatCountPerVertices1 * 2 * index;
  25905. var curtime = this._owner._curtime;
  25906. this._vertices1[vertexOffset] = position.x;
  25907. this._vertices1[vertexOffset + 1] = position.y;
  25908. this._vertices1[vertexOffset + 2] = position.z;
  25909. this._vertices1[vertexOffset + 3] = -pointAtoBVector3.x;
  25910. this._vertices1[vertexOffset + 4] = -pointAtoBVector3.y;
  25911. this._vertices1[vertexOffset + 5] = -pointAtoBVector3.z;
  25912. this._vertices1[vertexOffset + 6] = curtime;
  25913. this._vertices1[vertexOffset + 7] = 1.0;
  25914. this._vertices1[vertexOffset + 8] = position.x;
  25915. this._vertices1[vertexOffset + 9] = position.y;
  25916. this._vertices1[vertexOffset + 10] = position.z;
  25917. this._vertices1[vertexOffset + 11] = pointAtoBVector3.x;
  25918. this._vertices1[vertexOffset + 12] = pointAtoBVector3.y;
  25919. this._vertices1[vertexOffset + 13] = pointAtoBVector3.z;
  25920. this._vertices1[vertexOffset + 14] = curtime;
  25921. this._vertices1[vertexOffset + 15] = 0.0;
  25922. var bounds = this._owner._owner.trailRenderer.bounds;
  25923. var min = bounds.getMin();
  25924. var max = bounds.getMax();
  25925. var up = TrailGeometry._tempVector35;
  25926. var down = TrailGeometry._tempVector36;
  25927. var out = TrailGeometry._tempVector32;
  25928. Vector3.add(position, pointAtoBVector3, up);
  25929. Vector3.subtract(position, pointAtoBVector3, down);
  25930. Vector3.min(down, up, out);
  25931. Vector3.min(min, out, min);
  25932. bounds.setMin(min);
  25933. Vector3.max(up, down, out);
  25934. Vector3.max(max, out, max);
  25935. bounds.setMax(max);
  25936. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  25937. var floatCount = this._floatCountPerVertices1 * 2;
  25938. this._vertexBuffer1.setData(this._vertices1.buffer, vertexOffset * 4, vertexOffset * 4, floatCount * 4);
  25939. }
  25940. _updateVerticesByPosition(position, pointAtoBVector3, delDistance, index) {
  25941. this._updateVerticesByPositionData(position, pointAtoBVector3, index);
  25942. this._subDistance[index] = delDistance;
  25943. this._subBirthTime[index] = this._owner._curtime;
  25944. }
  25945. _updateVertexBufferUV() {
  25946. var bounds;
  25947. var min, max;
  25948. if (this._disappearBoundsMode) {
  25949. bounds = this._owner._owner.trailRenderer.bounds;
  25950. min = bounds.getMin();
  25951. max = bounds.getMax();
  25952. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25953. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25954. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  25955. }
  25956. var vertexCount = this._endIndex;
  25957. var curLength = 0;
  25958. var gradient = this._owner.colorGradient;
  25959. var startAlphaIndex = gradient.colorAlphaKeysCount - 1;
  25960. var startColorIndex = gradient.colorRGBKeysCount - 1;
  25961. var totalLength = this._owner._totalLength;
  25962. var stride = this._floatCountPerVertices2 * 2;
  25963. for (var i = this._activeIndex; i < vertexCount; i++) {
  25964. (i !== this._activeIndex) && (curLength += this._subDistance[i]);
  25965. var uvX;
  25966. var lerpFactor;
  25967. if (this._owner.textureMode == TextureMode.Stretch) {
  25968. uvX = 1.0 - curLength / totalLength;
  25969. lerpFactor = uvX;
  25970. }
  25971. else {
  25972. lerpFactor = 1.0 - curLength / totalLength;
  25973. uvX = 1.0 - (totalLength - curLength);
  25974. }
  25975. startColorIndex = gradient.evaluateColorRGB(lerpFactor, this.tmpColor, startColorIndex, true);
  25976. startAlphaIndex = gradient.evaluateColorAlpha(lerpFactor, this.tmpColor, startAlphaIndex, true);
  25977. var index = i * stride;
  25978. this._vertices2[index + 0] = uvX;
  25979. this._vertices2[index + 1] = this.tmpColor.r;
  25980. this._vertices2[index + 2] = this.tmpColor.g;
  25981. this._vertices2[index + 3] = this.tmpColor.b;
  25982. this._vertices2[index + 4] = this.tmpColor.a;
  25983. this._vertices2[index + 5] = uvX;
  25984. this._vertices2[index + 6] = this.tmpColor.r;
  25985. this._vertices2[index + 7] = this.tmpColor.g;
  25986. this._vertices2[index + 8] = this.tmpColor.b;
  25987. this._vertices2[index + 9] = this.tmpColor.a;
  25988. if (this._disappearBoundsMode) {
  25989. var posOffset = this._floatCountPerVertices1 * 2 * i;
  25990. var pos = TrailGeometry._tempVector32;
  25991. var up = TrailGeometry._tempVector33;
  25992. var side = TrailGeometry._tempVector34;
  25993. pos.setValue(this._vertices1[posOffset + 0], this._vertices1[posOffset + 1], this._vertices1[posOffset + 2]);
  25994. up.setValue(this._vertices1[posOffset + 3], this._vertices1[posOffset + 4], this._vertices1[posOffset + 5]);
  25995. Vector3.add(pos, up, side);
  25996. Vector3.min(side, min, min);
  25997. Vector3.max(side, max, max);
  25998. Vector3.subtract(pos, up, side);
  25999. Vector3.min(side, min, min);
  26000. Vector3.max(side, max, max);
  26001. }
  26002. }
  26003. if (this._disappearBoundsMode) {
  26004. bounds.setMin(min);
  26005. bounds.setMax(max);
  26006. this._disappearBoundsMode = false;
  26007. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  26008. }
  26009. var offset = this._activeIndex * stride;
  26010. this._vertexBuffer2.setData(this._vertices2.buffer, offset * 4, offset * 4, (vertexCount * stride - offset) * 4);
  26011. }
  26012. _updateDisappear() {
  26013. var count = this._endIndex;
  26014. for (var i = this._activeIndex; i < count; i++) {
  26015. if (this._owner._curtime - this._subBirthTime[i] >= this._owner.time + MathUtils3D.zeroTolerance) {
  26016. var nextIndex = i + 1;
  26017. if (nextIndex !== count)
  26018. this._owner._totalLength -= this._subDistance[nextIndex];
  26019. if (this._isTempEndVertex && (nextIndex === count - 1)) {
  26020. var offset = this._floatCountPerVertices1 * i * 2;
  26021. var fixedPos = this._lastFixedVertexPosition;
  26022. fixedPos.x = this._vertices1[0];
  26023. fixedPos.y = this._vertices1[1];
  26024. fixedPos.z = this._vertices1[2];
  26025. this._isTempEndVertex = false;
  26026. }
  26027. this._activeIndex++;
  26028. this._disappearBoundsMode = true;
  26029. }
  26030. else {
  26031. break;
  26032. }
  26033. }
  26034. }
  26035. _getType() {
  26036. return TrailGeometry._type;
  26037. }
  26038. _prepareRender(state) {
  26039. return this._endIndex - this._activeIndex > 1;
  26040. }
  26041. _render(state) {
  26042. this._bufferState.bind();
  26043. var gl = Laya.LayaGL.instance;
  26044. var start = this._activeIndex * 2;
  26045. var count = this._endIndex * 2 - start;
  26046. gl.drawArrays(gl.TRIANGLE_STRIP, start, count);
  26047. Laya.Stat.renderBatches++;
  26048. Laya.Stat.trianglesFaces += count - 2;
  26049. }
  26050. destroy() {
  26051. super.destroy();
  26052. var memorySize = this._vertexBuffer1._byteLength + this._vertexBuffer2._byteLength;
  26053. Laya.Resource._addMemory(-memorySize, -memorySize);
  26054. this._bufferState.destroy();
  26055. this._vertexBuffer1.destroy();
  26056. this._vertexBuffer2.destroy();
  26057. this._bufferState = null;
  26058. this._vertices1 = null;
  26059. this._vertexBuffer1 = null;
  26060. this._vertices2 = null;
  26061. this._vertexBuffer2 = null;
  26062. this._subBirthTime = null;
  26063. this._subDistance = null;
  26064. this._lastFixedVertexPosition = null;
  26065. this._disappearBoundsMode = false;
  26066. }
  26067. _calculateBoundingBoxForNative() {
  26068. var trail = this._owner._owner.trailRenderer;
  26069. var bounds = trail.bounds;
  26070. var min = bounds.getMin();
  26071. var max = bounds.getMax();
  26072. var buffer = FrustumCulling._cullingBuffer;
  26073. buffer[trail._cullingBufferIndex + 1] = min.x;
  26074. buffer[trail._cullingBufferIndex + 2] = min.y;
  26075. buffer[trail._cullingBufferIndex + 3] = min.z;
  26076. buffer[trail._cullingBufferIndex + 4] = max.x;
  26077. buffer[trail._cullingBufferIndex + 5] = max.y;
  26078. buffer[trail._cullingBufferIndex + 6] = max.z;
  26079. }
  26080. }
  26081. TrailGeometry.ALIGNMENT_VIEW = 0;
  26082. TrailGeometry.ALIGNMENT_TRANSFORM_Z = 1;
  26083. TrailGeometry._tempVector30 = new Vector3();
  26084. TrailGeometry._tempVector31 = new Vector3();
  26085. TrailGeometry._tempVector32 = new Vector3();
  26086. TrailGeometry._tempVector33 = new Vector3();
  26087. TrailGeometry._tempVector34 = new Vector3();
  26088. TrailGeometry._tempVector35 = new Vector3();
  26089. TrailGeometry._tempVector36 = new Vector3();
  26090. TrailGeometry._type = GeometryElement._typeCounter++;
  26091. class TrailFilter {
  26092. constructor(owner) {
  26093. this._totalLength = 0;
  26094. this._lastPosition = new Vector3();
  26095. this._curtime = 0;
  26096. this.alignment = TrailFilter.ALIGNMENT_VIEW;
  26097. this._owner = owner;
  26098. this._initDefaultData();
  26099. this.addRenderElement();
  26100. }
  26101. get time() {
  26102. return this._time;
  26103. }
  26104. set time(value) {
  26105. this._time = value;
  26106. this._owner._render._shaderValues.setNumber(TrailFilter.LIFETIME, value);
  26107. }
  26108. get minVertexDistance() {
  26109. return this._minVertexDistance;
  26110. }
  26111. set minVertexDistance(value) {
  26112. this._minVertexDistance = value;
  26113. }
  26114. get widthMultiplier() {
  26115. return this._widthMultiplier;
  26116. }
  26117. set widthMultiplier(value) {
  26118. this._widthMultiplier = value;
  26119. }
  26120. get widthCurve() {
  26121. return this._widthCurve;
  26122. }
  26123. set widthCurve(value) {
  26124. this._widthCurve = value;
  26125. var widthCurveFloatArray = new Float32Array(value.length * 4);
  26126. var i, j, index = 0;
  26127. for (i = 0, j = value.length; i < j; i++) {
  26128. widthCurveFloatArray[index++] = value[i].time;
  26129. widthCurveFloatArray[index++] = value[i].inTangent;
  26130. widthCurveFloatArray[index++] = value[i].outTangent;
  26131. widthCurveFloatArray[index++] = value[i].value;
  26132. }
  26133. this._owner._render._shaderValues.setBuffer(TrailFilter.WIDTHCURVE, widthCurveFloatArray);
  26134. this._owner._render._shaderValues.setInt(TrailFilter.WIDTHCURVEKEYLENGTH, value.length);
  26135. }
  26136. get colorGradient() {
  26137. return this._colorGradient;
  26138. }
  26139. set colorGradient(value) {
  26140. this._colorGradient = value;
  26141. }
  26142. get textureMode() {
  26143. return this._textureMode;
  26144. }
  26145. set textureMode(value) {
  26146. this._textureMode = value;
  26147. }
  26148. addRenderElement() {
  26149. var render = this._owner._render;
  26150. var elements = render._renderElements;
  26151. var material = render.sharedMaterials[0];
  26152. (material) || (material = TrailMaterial.defaultMaterial);
  26153. var element = new RenderElement();
  26154. element.setTransform(this._owner._transform);
  26155. element.render = render;
  26156. element.material = material;
  26157. this._trialGeometry = new TrailGeometry(this);
  26158. element.setGeometry(this._trialGeometry);
  26159. elements.push(element);
  26160. }
  26161. _update(state) {
  26162. var render = this._owner._render;
  26163. this._curtime += state.scene.timer._delta / 1000;
  26164. render._shaderValues.setNumber(TrailFilter.CURTIME, this._curtime);
  26165. var curPos = this._owner.transform.position;
  26166. var element = render._renderElements[0]._geometry;
  26167. element._updateDisappear();
  26168. element._updateTrail(state.camera, this._lastPosition, curPos);
  26169. element._updateVertexBufferUV();
  26170. curPos.cloneTo(this._lastPosition);
  26171. }
  26172. _initDefaultData() {
  26173. this.time = 5.0;
  26174. this.minVertexDistance = 0.1;
  26175. this.widthMultiplier = 1;
  26176. this.textureMode = TextureMode.Stretch;
  26177. var widthKeyFrames = [];
  26178. var widthKeyFrame1 = new FloatKeyframe();
  26179. widthKeyFrame1.time = 0;
  26180. widthKeyFrame1.inTangent = 0;
  26181. widthKeyFrame1.outTangent = 0;
  26182. widthKeyFrame1.value = 1;
  26183. widthKeyFrames.push(widthKeyFrame1);
  26184. var widthKeyFrame2 = new FloatKeyframe();
  26185. widthKeyFrame2.time = 1;
  26186. widthKeyFrame2.inTangent = 0;
  26187. widthKeyFrame2.outTangent = 0;
  26188. widthKeyFrame2.value = 1;
  26189. widthKeyFrames.push(widthKeyFrame2);
  26190. this.widthCurve = widthKeyFrames;
  26191. var gradient = new Gradient(2, 2);
  26192. gradient.mode = GradientMode.Blend;
  26193. gradient.addColorRGB(0, Color.WHITE);
  26194. gradient.addColorRGB(1, Color.WHITE);
  26195. gradient.addColorAlpha(0, 1);
  26196. gradient.addColorAlpha(1, 1);
  26197. this.colorGradient = gradient;
  26198. }
  26199. destroy() {
  26200. this._trialGeometry.destroy();
  26201. this._trialGeometry = null;
  26202. this._widthCurve = null;
  26203. this._colorGradient = null;
  26204. }
  26205. }
  26206. TrailFilter.CURTIME = Shader3D.propertyNameToID("u_CurTime");
  26207. TrailFilter.LIFETIME = Shader3D.propertyNameToID("u_LifeTime");
  26208. TrailFilter.WIDTHCURVE = Shader3D.propertyNameToID("u_WidthCurve");
  26209. TrailFilter.WIDTHCURVEKEYLENGTH = Shader3D.propertyNameToID("u_WidthCurveKeyLength");
  26210. TrailFilter.ALIGNMENT_VIEW = 0;
  26211. TrailFilter.ALIGNMENT_TRANSFORM_Z = 1;
  26212. class TrailRenderer extends BaseRender {
  26213. constructor(owner) {
  26214. super(owner);
  26215. this._projectionViewWorldMatrix = new Matrix4x4();
  26216. }
  26217. _calculateBoundingBox() {
  26218. }
  26219. _needRender(boundFrustum, context) {
  26220. this._owner.trailFilter._update(context);
  26221. if (boundFrustum)
  26222. return boundFrustum.intersects(this.bounds._getBoundBox());
  26223. else
  26224. return true;
  26225. }
  26226. _updateForNative(context) {
  26227. this._owner.trailFilter._update(context);
  26228. }
  26229. _renderUpdate(state, transform) {
  26230. super._renderUpdate(state, transform);
  26231. }
  26232. _renderUpdateWithCamera(context, transform) {
  26233. var projectionView = context.projectionViewMatrix;
  26234. if (transform) {
  26235. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  26236. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  26237. }
  26238. else {
  26239. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  26240. }
  26241. }
  26242. }
  26243. class TrailSprite3D extends RenderableSprite3D {
  26244. static __init__() {
  26245. }
  26246. get trailFilter() {
  26247. return this._geometryFilter;
  26248. }
  26249. get trailRenderer() {
  26250. return this._render;
  26251. }
  26252. constructor(name = null) {
  26253. super(name);
  26254. this._render = new TrailRenderer(this);
  26255. this._geometryFilter = new TrailFilter(this);
  26256. }
  26257. _parse(data, spriteMap) {
  26258. super._parse(data, spriteMap);
  26259. var render = this._render;
  26260. var filter = this._geometryFilter;
  26261. var i, j;
  26262. var materials = data.materials;
  26263. if (materials) {
  26264. var sharedMaterials = render.sharedMaterials;
  26265. var materialCount = materials.length;
  26266. sharedMaterials.length = materialCount;
  26267. for (i = 0; i < materialCount; i++)
  26268. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  26269. render.sharedMaterials = sharedMaterials;
  26270. }
  26271. filter.time = data.time;
  26272. filter.minVertexDistance = data.minVertexDistance;
  26273. filter.widthMultiplier = data.widthMultiplier;
  26274. filter.textureMode = data.textureMode;
  26275. (data.alignment != null) && (filter.alignment = data.alignment);
  26276. var widthCurve = [];
  26277. var widthCurveData = data.widthCurve;
  26278. for (i = 0, j = widthCurveData.length; i < j; i++) {
  26279. var trailkeyframe = new FloatKeyframe();
  26280. trailkeyframe.time = widthCurveData[i].time;
  26281. trailkeyframe.inTangent = widthCurveData[i].inTangent;
  26282. trailkeyframe.outTangent = widthCurveData[i].outTangent;
  26283. trailkeyframe.value = widthCurveData[i].value;
  26284. widthCurve.push(trailkeyframe);
  26285. }
  26286. filter.widthCurve = widthCurve;
  26287. var colorGradientData = data.colorGradient;
  26288. var colorKeys = colorGradientData.colorKeys;
  26289. var alphaKeys = colorGradientData.alphaKeys;
  26290. var colorGradient = new Gradient(colorKeys.length, alphaKeys.length);
  26291. colorGradient.mode = colorGradientData.mode;
  26292. for (i = 0, j = colorKeys.length; i < j; i++) {
  26293. var colorKey = colorKeys[i];
  26294. colorGradient.addColorRGB(colorKey.time, new Color(colorKey.value[0], colorKey.value[1], colorKey.value[2], 1.0));
  26295. }
  26296. for (i = 0, j = alphaKeys.length; i < j; i++) {
  26297. var alphaKey = alphaKeys[i];
  26298. colorGradient.addColorAlpha(alphaKey.time, alphaKey.value);
  26299. }
  26300. filter.colorGradient = colorGradient;
  26301. }
  26302. _onActive() {
  26303. super._onActive();
  26304. this._transform.position.cloneTo(this._geometryFilter._lastPosition);
  26305. }
  26306. _cloneTo(destObject, srcSprite, dstSprite) {
  26307. super._cloneTo(destObject, srcSprite, dstSprite);
  26308. var i, j;
  26309. var destTrailSprite3D = destObject;
  26310. var destTrailFilter = destTrailSprite3D.trailFilter;
  26311. destTrailFilter.time = this.trailFilter.time;
  26312. destTrailFilter.minVertexDistance = this.trailFilter.minVertexDistance;
  26313. destTrailFilter.widthMultiplier = this.trailFilter.widthMultiplier;
  26314. destTrailFilter.textureMode = this.trailFilter.textureMode;
  26315. destTrailFilter.alignment = this.trailFilter.alignment;
  26316. var widthCurveData = this.trailFilter.widthCurve;
  26317. var widthCurve = [];
  26318. for (i = 0, j = widthCurveData.length; i < j; i++) {
  26319. var keyFrame = new FloatKeyframe();
  26320. widthCurveData[i].cloneTo(keyFrame);
  26321. widthCurve.push(keyFrame);
  26322. }
  26323. destTrailFilter.widthCurve = widthCurve;
  26324. var destColorGradient = new Gradient(this.trailFilter.colorGradient.maxColorRGBKeysCount, this.trailFilter.colorGradient.maxColorAlphaKeysCount);
  26325. this.trailFilter.colorGradient.cloneTo(destColorGradient);
  26326. destTrailFilter.colorGradient = destColorGradient;
  26327. var destTrailRender = destTrailSprite3D.trailRenderer;
  26328. destTrailRender.sharedMaterial = this.trailRenderer.sharedMaterial;
  26329. }
  26330. destroy(destroyChild = true) {
  26331. if (this.destroyed)
  26332. return;
  26333. super.destroy(destroyChild);
  26334. this._geometryFilter.destroy();
  26335. this._geometryFilter = null;
  26336. }
  26337. _create() {
  26338. return new TrailSprite3D();
  26339. }
  26340. }
  26341. class VertexPositionTerrain {
  26342. constructor(position, normal, textureCoord0, textureCoord1) {
  26343. this._position = position;
  26344. this._normal = normal;
  26345. this._textureCoord0 = textureCoord0;
  26346. this._textureCoord1 = textureCoord1;
  26347. }
  26348. static __init__() {
  26349. VertexPositionTerrain._vertexDeclaration = new VertexDeclaration(40, [new VertexElement(0, VertexElementFormat.Vector3, VertexPositionTerrain.TERRAIN_POSITION0),
  26350. new VertexElement(12, VertexElementFormat.Vector3, VertexPositionTerrain.TERRAIN_NORMAL0),
  26351. new VertexElement(24, VertexElementFormat.Vector2, VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE0),
  26352. new VertexElement(32, VertexElementFormat.Vector2, VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE1)]);
  26353. }
  26354. static get vertexDeclaration() {
  26355. return VertexPositionTerrain._vertexDeclaration;
  26356. }
  26357. get position() {
  26358. return this._position;
  26359. }
  26360. get normal() {
  26361. return this._normal;
  26362. }
  26363. get textureCoord0() {
  26364. return this._textureCoord0;
  26365. }
  26366. get textureCoord1() {
  26367. return this._textureCoord1;
  26368. }
  26369. get vertexDeclaration() {
  26370. return VertexPositionTerrain._vertexDeclaration;
  26371. }
  26372. }
  26373. VertexPositionTerrain.TERRAIN_POSITION0 = 0;
  26374. VertexPositionTerrain.TERRAIN_NORMAL0 = 1;
  26375. VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE0 = 2;
  26376. VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE1 = 3;
  26377. class BulletInteractive {
  26378. }
  26379. BulletInteractive._interactive = {
  26380. "getWorldTransform": (rigidBodyID, worldTransPointer) => {
  26381. },
  26382. "setWorldTransform": (rigidBodyID, worldTransPointer) => {
  26383. var rigidBody = PhysicsComponent._physicObjectsMap[rigidBodyID];
  26384. rigidBody._simulation._updatedRigidbodies++;
  26385. rigidBody._updateTransformComponent(worldTransPointer);
  26386. }
  26387. };
  26388. class CharacterController extends PhysicsComponent {
  26389. constructor(stepheight = 0.1, upAxis = null, collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  26390. super(collisionGroup, canCollideWith);
  26391. this._upAxis = new Vector3(0, 1, 0);
  26392. this._maxSlope = 45.0;
  26393. this._jumpSpeed = 10.0;
  26394. this._fallSpeed = 55.0;
  26395. this._gravity = new Vector3(0, -9.8 * 3, 0);
  26396. this._btKinematicCharacter = null;
  26397. this._stepHeight = stepheight;
  26398. (upAxis) && (this._upAxis = upAxis);
  26399. }
  26400. static __init__() {
  26401. CharacterController._btTempVector30 = Physics3D._bullet.btVector3_create(0, 0, 0);
  26402. }
  26403. get fallSpeed() {
  26404. return this._fallSpeed;
  26405. }
  26406. set fallSpeed(value) {
  26407. this._fallSpeed = value;
  26408. Physics3D._bullet.btKinematicCharacterController_setFallSpeed(this._btKinematicCharacter, value);
  26409. }
  26410. get jumpSpeed() {
  26411. return this._jumpSpeed;
  26412. }
  26413. set jumpSpeed(value) {
  26414. this._jumpSpeed = value;
  26415. Physics3D._bullet.btKinematicCharacterController_setJumpSpeed(this._btKinematicCharacter, value);
  26416. }
  26417. get gravity() {
  26418. return this._gravity;
  26419. }
  26420. set gravity(value) {
  26421. this._gravity = value;
  26422. var bt = Physics3D._bullet;
  26423. var btGravity = CharacterController._btTempVector30;
  26424. bt.btVector3_setValue(btGravity, -value.x, value.y, value.z);
  26425. bt.btKinematicCharacterController_setGravity(this._btKinematicCharacter, btGravity);
  26426. }
  26427. get maxSlope() {
  26428. return this._maxSlope;
  26429. }
  26430. set maxSlope(value) {
  26431. this._maxSlope = value;
  26432. Physics3D._bullet.btKinematicCharacterController_setMaxSlope(this._btKinematicCharacter, (value / 180) * Math.PI);
  26433. }
  26434. get isGrounded() {
  26435. return Physics3D._bullet.btKinematicCharacterController_onGround(this._btKinematicCharacter);
  26436. }
  26437. get stepHeight() {
  26438. return this._stepHeight;
  26439. }
  26440. set stepHeight(value) {
  26441. this._stepHeight = value;
  26442. this._constructCharacter();
  26443. }
  26444. get upAxis() {
  26445. return this._upAxis;
  26446. }
  26447. set upAxis(value) {
  26448. this._upAxis = value;
  26449. this._constructCharacter();
  26450. }
  26451. _constructCharacter() {
  26452. var bt = Physics3D._bullet;
  26453. if (this._btKinematicCharacter)
  26454. bt.btKinematicCharacterController_destroy(this._btKinematicCharacter);
  26455. var btUpAxis = CharacterController._btTempVector30;
  26456. bt.btVector3_setValue(btUpAxis, this._upAxis.x, this._upAxis.y, this._upAxis.z);
  26457. this._btKinematicCharacter = bt.btKinematicCharacterController_create(this._btColliderObject, this._colliderShape._btShape, this._stepHeight, btUpAxis);
  26458. this.fallSpeed = this._fallSpeed;
  26459. this.maxSlope = this._maxSlope;
  26460. this.jumpSpeed = this._jumpSpeed;
  26461. this.gravity = this._gravity;
  26462. }
  26463. _onShapeChange(colShape) {
  26464. super._onShapeChange(colShape);
  26465. this._constructCharacter();
  26466. }
  26467. _onAdded() {
  26468. var bt = Physics3D._bullet;
  26469. var ghostObject = bt.btPairCachingGhostObject_create();
  26470. bt.btCollisionObject_setUserIndex(ghostObject, this.id);
  26471. bt.btCollisionObject_setCollisionFlags(ghostObject, PhysicsComponent.COLLISIONFLAGS_CHARACTER_OBJECT);
  26472. this._btColliderObject = ghostObject;
  26473. if (this._colliderShape)
  26474. this._constructCharacter();
  26475. super._onAdded();
  26476. }
  26477. _addToSimulation() {
  26478. this._simulation._characters.push(this);
  26479. this._simulation._addCharacter(this, this._collisionGroup, this._canCollideWith);
  26480. }
  26481. _removeFromSimulation() {
  26482. this._simulation._removeCharacter(this);
  26483. var characters = this._simulation._characters;
  26484. characters.splice(characters.indexOf(this), 1);
  26485. }
  26486. _cloneTo(dest) {
  26487. super._cloneTo(dest);
  26488. var destCharacterController = dest;
  26489. destCharacterController.stepHeight = this._stepHeight;
  26490. destCharacterController.upAxis = this._upAxis;
  26491. destCharacterController.maxSlope = this._maxSlope;
  26492. destCharacterController.jumpSpeed = this._jumpSpeed;
  26493. destCharacterController.fallSpeed = this._fallSpeed;
  26494. destCharacterController.gravity = this._gravity;
  26495. }
  26496. _onDestroy() {
  26497. Physics3D._bullet.btKinematicCharacterController_destroy(this._btKinematicCharacter);
  26498. super._onDestroy();
  26499. this._btKinematicCharacter = null;
  26500. }
  26501. move(movement) {
  26502. var btMovement = CharacterController._btVector30;
  26503. var bt = Physics3D._bullet;
  26504. bt.btVector3_setValue(btMovement, -movement.x, movement.y, movement.z);
  26505. bt.btKinematicCharacterController_setWalkDirection(this._btKinematicCharacter, btMovement);
  26506. }
  26507. jump(velocity = null) {
  26508. var bt = Physics3D._bullet;
  26509. var btVelocity = CharacterController._btVector30;
  26510. if (velocity) {
  26511. Utils3D._convertToBulletVec3(velocity, btVelocity, true);
  26512. bt.btKinematicCharacterController_jump(this._btKinematicCharacter, btVelocity);
  26513. }
  26514. else {
  26515. bt.btVector3_setValue(btVelocity, 0, 0, 0);
  26516. bt.btKinematicCharacterController_jump(this._btKinematicCharacter, btVelocity);
  26517. }
  26518. }
  26519. }
  26520. CharacterController.UPAXIS_X = 0;
  26521. CharacterController.UPAXIS_Y = 1;
  26522. CharacterController.UPAXIS_Z = 2;
  26523. class PhysicsTriggerComponent extends PhysicsComponent {
  26524. constructor(collisionGroup, canCollideWith) {
  26525. super(collisionGroup, canCollideWith);
  26526. this._isTrigger = false;
  26527. }
  26528. get isTrigger() {
  26529. return this._isTrigger;
  26530. }
  26531. set isTrigger(value) {
  26532. this._isTrigger = value;
  26533. var bt = Physics3D._bullet;
  26534. if (this._btColliderObject) {
  26535. var flags = bt.btCollisionObject_getCollisionFlags(this._btColliderObject);
  26536. if (value) {
  26537. if ((flags & PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE) === 0)
  26538. bt.btCollisionObject_setCollisionFlags(this._btColliderObject, flags | PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE);
  26539. }
  26540. else {
  26541. if ((flags & PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE) !== 0)
  26542. bt.btCollisionObject_setCollisionFlags(this._btColliderObject, flags ^ PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE);
  26543. }
  26544. }
  26545. }
  26546. _onAdded() {
  26547. super._onAdded();
  26548. this.isTrigger = this._isTrigger;
  26549. }
  26550. _cloneTo(dest) {
  26551. super._cloneTo(dest);
  26552. dest.isTrigger = this._isTrigger;
  26553. }
  26554. }
  26555. class PhysicsCollider extends PhysicsTriggerComponent {
  26556. constructor(collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  26557. super(collisionGroup, canCollideWith);
  26558. this._enableProcessCollisions = false;
  26559. }
  26560. _addToSimulation() {
  26561. this._simulation._addPhysicsCollider(this, this._collisionGroup, this._canCollideWith);
  26562. }
  26563. _removeFromSimulation() {
  26564. this._simulation._removePhysicsCollider(this);
  26565. }
  26566. _onTransformChanged(flag) {
  26567. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  26568. if (flag) {
  26569. this._transformFlag |= flag;
  26570. if (this._isValid() && this._inPhysicUpdateListIndex === -1)
  26571. this._simulation._physicsUpdateList.add(this);
  26572. }
  26573. }
  26574. _parse(data) {
  26575. (data.friction != null) && (this.friction = data.friction);
  26576. (data.rollingFriction != null) && (this.rollingFriction = data.rollingFriction);
  26577. (data.restitution != null) && (this.restitution = data.restitution);
  26578. (data.isTrigger != null) && (this.isTrigger = data.isTrigger);
  26579. super._parse(data);
  26580. this._parseShape(data.shapes);
  26581. }
  26582. _onAdded() {
  26583. var bt = Physics3D._bullet;
  26584. var btColObj = bt.btCollisionObject_create();
  26585. bt.btCollisionObject_setUserIndex(btColObj, this.id);
  26586. bt.btCollisionObject_forceActivationState(btColObj, PhysicsComponent.ACTIVATIONSTATE_DISABLE_SIMULATION);
  26587. var flags = bt.btCollisionObject_getCollisionFlags(btColObj);
  26588. if (this.owner.isStatic) {
  26589. if ((flags & PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT) > 0)
  26590. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  26591. flags = flags | PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT;
  26592. }
  26593. else {
  26594. if ((flags & PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT) > 0)
  26595. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT;
  26596. flags = flags | PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  26597. }
  26598. bt.btCollisionObject_setCollisionFlags(btColObj, flags);
  26599. this._btColliderObject = btColObj;
  26600. super._onAdded();
  26601. }
  26602. }
  26603. class Rigidbody3D extends PhysicsTriggerComponent {
  26604. constructor(collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  26605. super(collisionGroup, canCollideWith);
  26606. this._isKinematic = false;
  26607. this._mass = 1.0;
  26608. this._gravity = new Vector3(0, -10, 0);
  26609. this._angularDamping = 0.0;
  26610. this._linearDamping = 0.0;
  26611. this._overrideGravity = false;
  26612. this._totalTorque = new Vector3(0, 0, 0);
  26613. this._totalForce = new Vector3(0, 0, 0);
  26614. this._linearVelocity = new Vector3();
  26615. this._angularVelocity = new Vector3();
  26616. this._linearFactor = new Vector3(1, 1, 1);
  26617. this._angularFactor = new Vector3(1, 1, 1);
  26618. this._detectCollisions = true;
  26619. }
  26620. static __init__() {
  26621. var bt = Physics3D._bullet;
  26622. Rigidbody3D._btTempVector30 = bt.btVector3_create(0, 0, 0);
  26623. Rigidbody3D._btTempVector31 = bt.btVector3_create(0, 0, 0);
  26624. Rigidbody3D._btVector3Zero = bt.btVector3_create(0, 0, 0);
  26625. Rigidbody3D._btInertia = bt.btVector3_create(0, 0, 0);
  26626. Rigidbody3D._btImpulse = bt.btVector3_create(0, 0, 0);
  26627. Rigidbody3D._btImpulseOffset = bt.btVector3_create(0, 0, 0);
  26628. Rigidbody3D._btGravity = bt.btVector3_create(0, 0, 0);
  26629. }
  26630. get mass() {
  26631. return this._mass;
  26632. }
  26633. set mass(value) {
  26634. value = Math.max(value, 1e-07);
  26635. this._mass = value;
  26636. (this._isKinematic) || (this._updateMass(value));
  26637. }
  26638. get isKinematic() {
  26639. return this._isKinematic;
  26640. }
  26641. set isKinematic(value) {
  26642. this._isKinematic = value;
  26643. var bt = Physics3D._bullet;
  26644. var canInSimulation = !!(this._simulation && this._enabled && this._colliderShape);
  26645. canInSimulation && this._removeFromSimulation();
  26646. var natColObj = this._btColliderObject;
  26647. var flags = bt.btCollisionObject_getCollisionFlags(natColObj);
  26648. if (value) {
  26649. flags = flags | PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  26650. bt.btCollisionObject_setCollisionFlags(natColObj, flags);
  26651. bt.btCollisionObject_forceActivationState(this._btColliderObject, PhysicsComponent.ACTIVATIONSTATE_DISABLE_DEACTIVATION);
  26652. this._enableProcessCollisions = false;
  26653. this._updateMass(0);
  26654. }
  26655. else {
  26656. if ((flags & PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT) > 0)
  26657. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  26658. bt.btCollisionObject_setCollisionFlags(natColObj, flags);
  26659. bt.btCollisionObject_setActivationState(this._btColliderObject, PhysicsComponent.ACTIVATIONSTATE_ACTIVE_TAG);
  26660. this._enableProcessCollisions = true;
  26661. this._updateMass(this._mass);
  26662. }
  26663. var btZero = Rigidbody3D._btVector3Zero;
  26664. bt.btCollisionObject_setInterpolationLinearVelocity(natColObj, btZero);
  26665. bt.btRigidBody_setLinearVelocity(natColObj, btZero);
  26666. bt.btCollisionObject_setInterpolationAngularVelocity(natColObj, btZero);
  26667. bt.btRigidBody_setAngularVelocity(natColObj, btZero);
  26668. canInSimulation && this._addToSimulation();
  26669. }
  26670. get linearDamping() {
  26671. return this._linearDamping;
  26672. }
  26673. set linearDamping(value) {
  26674. this._linearDamping = value;
  26675. if (this._btColliderObject)
  26676. Physics3D._bullet.btRigidBody_setDamping(this._btColliderObject, value, this._angularDamping);
  26677. }
  26678. get angularDamping() {
  26679. return this._angularDamping;
  26680. }
  26681. set angularDamping(value) {
  26682. this._angularDamping = value;
  26683. if (this._btColliderObject)
  26684. Physics3D._bullet.btRigidBody_setDamping(this._btColliderObject, this._linearDamping, value);
  26685. }
  26686. get overrideGravity() {
  26687. return this._overrideGravity;
  26688. }
  26689. set overrideGravity(value) {
  26690. this._overrideGravity = value;
  26691. var bt = Physics3D._bullet;
  26692. if (this._btColliderObject) {
  26693. var flag = bt.btRigidBody_getFlags(this._btColliderObject);
  26694. if (value) {
  26695. if ((flag & Rigidbody3D._BT_DISABLE_WORLD_GRAVITY) === 0)
  26696. bt.btRigidBody_setFlags(this._btColliderObject, flag | Rigidbody3D._BT_DISABLE_WORLD_GRAVITY);
  26697. }
  26698. else {
  26699. if ((flag & Rigidbody3D._BT_DISABLE_WORLD_GRAVITY) > 0)
  26700. bt.btRigidBody_setFlags(this._btColliderObject, flag ^ Rigidbody3D._BT_DISABLE_WORLD_GRAVITY);
  26701. }
  26702. }
  26703. }
  26704. get gravity() {
  26705. return this._gravity;
  26706. }
  26707. set gravity(value) {
  26708. this._gravity = value;
  26709. var bt = Physics3D._bullet;
  26710. bt.btVector3_setValue(Rigidbody3D._btGravity, -value.x, value.y, value.z);
  26711. bt.btRigidBody_setGravity(this._btColliderObject, Rigidbody3D._btGravity);
  26712. }
  26713. get totalForce() {
  26714. if (this._btColliderObject) {
  26715. var btTotalForce = Physics3D._bullet.btRigidBody_getTotalForce(this._btColliderObject);
  26716. Utils3D._convertToLayaVec3(btTotalForce, this._totalForce, true);
  26717. return this._totalForce;
  26718. }
  26719. return null;
  26720. }
  26721. get linearFactor() {
  26722. if (this._btColliderObject)
  26723. return this._linearFactor;
  26724. return null;
  26725. }
  26726. set linearFactor(value) {
  26727. this._linearFactor = value;
  26728. if (this._btColliderObject) {
  26729. var btValue = Rigidbody3D._btTempVector30;
  26730. Utils3D._convertToBulletVec3(value, btValue, false);
  26731. Physics3D._bullet.btRigidBody_setLinearFactor(this._btColliderObject, btValue);
  26732. }
  26733. }
  26734. get linearVelocity() {
  26735. if (this._btColliderObject)
  26736. Utils3D._convertToLayaVec3(Physics3D._bullet.btRigidBody_getLinearVelocity(this._btColliderObject), this._linearVelocity, true);
  26737. return this._linearVelocity;
  26738. }
  26739. set linearVelocity(value) {
  26740. this._linearVelocity = value;
  26741. if (this._btColliderObject) {
  26742. var btValue = Rigidbody3D._btTempVector30;
  26743. Utils3D._convertToBulletVec3(value, btValue, true);
  26744. (this.isSleeping) && (this.wakeUp());
  26745. Physics3D._bullet.btRigidBody_setLinearVelocity(this._btColliderObject, btValue);
  26746. }
  26747. }
  26748. get angularFactor() {
  26749. if (this._btColliderObject)
  26750. return this._angularFactor;
  26751. return null;
  26752. }
  26753. set angularFactor(value) {
  26754. this._angularFactor = value;
  26755. if (this._btColliderObject) {
  26756. var btValue = Rigidbody3D._btTempVector30;
  26757. Utils3D._convertToBulletVec3(value, btValue, false);
  26758. Physics3D._bullet.btRigidBody_setAngularFactor(this._btColliderObject, btValue);
  26759. }
  26760. }
  26761. get angularVelocity() {
  26762. if (this._btColliderObject)
  26763. Utils3D._convertToLayaVec3(Physics3D._bullet.btRigidBody_getAngularVelocity(this._btColliderObject), this._angularVelocity, true);
  26764. return this._angularVelocity;
  26765. }
  26766. set angularVelocity(value) {
  26767. this._angularVelocity = value;
  26768. if (this._btColliderObject) {
  26769. var btValue = Rigidbody3D._btTempVector30;
  26770. Utils3D._convertToBulletVec3(value, btValue, true);
  26771. (this.isSleeping) && (this.wakeUp());
  26772. Physics3D._bullet.btRigidBody_setAngularVelocity(this._btColliderObject, btValue);
  26773. }
  26774. }
  26775. get totalTorque() {
  26776. if (this._btColliderObject) {
  26777. var btTotalTorque = Physics3D._bullet.btRigidBody_getTotalTorque(this._btColliderObject);
  26778. Utils3D._convertToLayaVec3(btTotalTorque, this._totalTorque, true);
  26779. return this._totalTorque;
  26780. }
  26781. return null;
  26782. }
  26783. get detectCollisions() {
  26784. return this._detectCollisions;
  26785. }
  26786. set detectCollisions(value) {
  26787. if (this._detectCollisions !== value) {
  26788. this._detectCollisions = value;
  26789. if (this._colliderShape && this._enabled && this._simulation) {
  26790. this._simulation._removeRigidBody(this);
  26791. this._simulation._addRigidBody(this, this._collisionGroup, value ? this._canCollideWith : 0);
  26792. }
  26793. }
  26794. }
  26795. get isSleeping() {
  26796. if (this._btColliderObject)
  26797. return Physics3D._bullet.btCollisionObject_getActivationState(this._btColliderObject) === PhysicsComponent.ACTIVATIONSTATE_ISLAND_SLEEPING;
  26798. return false;
  26799. }
  26800. get sleepLinearVelocity() {
  26801. return Physics3D._bullet.btRigidBody_getLinearSleepingThreshold(this._btColliderObject);
  26802. }
  26803. set sleepLinearVelocity(value) {
  26804. var bt = Physics3D._bullet;
  26805. bt.btRigidBody_setSleepingThresholds(this._btColliderObject, value, bt.btRigidBody_getAngularSleepingThreshold(this._btColliderObject));
  26806. }
  26807. get sleepAngularVelocity() {
  26808. return Physics3D._bullet.btRigidBody_getAngularSleepingThreshold(this._btColliderObject);
  26809. }
  26810. set sleepAngularVelocity(value) {
  26811. var bt = Physics3D._bullet;
  26812. bt.btRigidBody_setSleepingThresholds(this._btColliderObject, bt.btRigidBody_getLinearSleepingThreshold(this._btColliderObject), value);
  26813. }
  26814. _updateMass(mass) {
  26815. if (this._btColliderObject && this._colliderShape) {
  26816. var bt = Physics3D._bullet;
  26817. bt.btCollisionShape_calculateLocalInertia(this._colliderShape._btShape, mass, Rigidbody3D._btInertia);
  26818. bt.btRigidBody_setMassProps(this._btColliderObject, mass, Rigidbody3D._btInertia);
  26819. bt.btRigidBody_updateInertiaTensor(this._btColliderObject);
  26820. }
  26821. }
  26822. _onScaleChange(scale) {
  26823. super._onScaleChange(scale);
  26824. this._updateMass(this._isKinematic ? 0 : this._mass);
  26825. }
  26826. _onAdded() {
  26827. var bt = Physics3D._bullet;
  26828. var motionState = bt.layaMotionState_create();
  26829. bt.layaMotionState_set_rigidBodyID(motionState, this._id);
  26830. this._btLayaMotionState = motionState;
  26831. var constructInfo = bt.btRigidBodyConstructionInfo_create(0.0, motionState, null, Rigidbody3D._btVector3Zero);
  26832. var btRigid = bt.btRigidBody_create(constructInfo);
  26833. bt.btCollisionObject_setUserIndex(btRigid, this.id);
  26834. this._btColliderObject = btRigid;
  26835. super._onAdded();
  26836. this.mass = this._mass;
  26837. this.linearFactor = this._linearFactor;
  26838. this.angularFactor = this._angularFactor;
  26839. this.linearDamping = this._linearDamping;
  26840. this.angularDamping = this._angularDamping;
  26841. this.overrideGravity = this._overrideGravity;
  26842. this.gravity = this._gravity;
  26843. this.isKinematic = this._isKinematic;
  26844. bt.btRigidBodyConstructionInfo_destroy(constructInfo);
  26845. }
  26846. _onShapeChange(colShape) {
  26847. super._onShapeChange(colShape);
  26848. if (this._isKinematic) {
  26849. this._updateMass(0);
  26850. }
  26851. else {
  26852. var bt = Physics3D._bullet;
  26853. bt.btRigidBody_setCenterOfMassTransform(this._btColliderObject, bt.btCollisionObject_getWorldTransform(this._btColliderObject));
  26854. this._updateMass(this._mass);
  26855. }
  26856. }
  26857. _parse(data) {
  26858. (data.friction != null) && (this.friction = data.friction);
  26859. (data.rollingFriction != null) && (this.rollingFriction = data.rollingFriction);
  26860. (data.restitution != null) && (this.restitution = data.restitution);
  26861. (data.isTrigger != null) && (this.isTrigger = data.isTrigger);
  26862. (data.mass != null) && (this.mass = data.mass);
  26863. (data.isKinematic != null) && (this.isKinematic = data.isKinematic);
  26864. (data.linearDamping != null) && (this.linearDamping = data.linearDamping);
  26865. (data.angularDamping != null) && (this.angularDamping = data.angularDamping);
  26866. (data.overrideGravity != null) && (this.overrideGravity = data.overrideGravity);
  26867. if (data.gravity) {
  26868. this.gravity.fromArray(data.gravity);
  26869. this.gravity = this.gravity;
  26870. }
  26871. super._parse(data);
  26872. this._parseShape(data.shapes);
  26873. }
  26874. _onDestroy() {
  26875. Physics3D._bullet.btMotionState_destroy(this._btLayaMotionState);
  26876. super._onDestroy();
  26877. this._btLayaMotionState = null;
  26878. this._gravity = null;
  26879. this._totalTorque = null;
  26880. this._linearVelocity = null;
  26881. this._angularVelocity = null;
  26882. this._linearFactor = null;
  26883. this._angularFactor = null;
  26884. }
  26885. _addToSimulation() {
  26886. this._simulation._addRigidBody(this, this._collisionGroup, this._detectCollisions ? this._canCollideWith : 0);
  26887. }
  26888. _removeFromSimulation() {
  26889. this._simulation._removeRigidBody(this);
  26890. }
  26891. _cloneTo(dest) {
  26892. super._cloneTo(dest);
  26893. var destRigidbody3D = dest;
  26894. destRigidbody3D.isKinematic = this._isKinematic;
  26895. destRigidbody3D.mass = this._mass;
  26896. destRigidbody3D.gravity = this._gravity;
  26897. destRigidbody3D.angularDamping = this._angularDamping;
  26898. destRigidbody3D.linearDamping = this._linearDamping;
  26899. destRigidbody3D.overrideGravity = this._overrideGravity;
  26900. destRigidbody3D.linearVelocity = this._linearVelocity;
  26901. destRigidbody3D.angularVelocity = this._angularVelocity;
  26902. destRigidbody3D.linearFactor = this._linearFactor;
  26903. destRigidbody3D.angularFactor = this._angularFactor;
  26904. destRigidbody3D.detectCollisions = this._detectCollisions;
  26905. }
  26906. applyForce(force, localOffset = null) {
  26907. if (this._btColliderObject == null)
  26908. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26909. var bt = Physics3D._bullet;
  26910. var btForce = Rigidbody3D._btTempVector30;
  26911. bt.btVector3_setValue(btForce, -force.x, force.y, force.z);
  26912. if (localOffset) {
  26913. var btOffset = Rigidbody3D._btTempVector31;
  26914. bt.btVector3_setValue(btOffset, -localOffset.x, localOffset.y, localOffset.z);
  26915. bt.btRigidBody_applyForce(this._btColliderObject, btForce, btOffset);
  26916. }
  26917. else {
  26918. bt.btRigidBody_applyCentralForce(this._btColliderObject, btForce);
  26919. }
  26920. }
  26921. applyTorque(torque) {
  26922. if (this._btColliderObject == null)
  26923. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26924. var bullet = Physics3D._bullet;
  26925. var btTorque = Rigidbody3D._btTempVector30;
  26926. bullet.btVector3_setValue(btTorque, -torque.x, torque.y, torque.z);
  26927. bullet.btRigidBody_applyTorque(this._btColliderObject, btTorque);
  26928. }
  26929. applyImpulse(impulse, localOffset = null) {
  26930. if (this._btColliderObject == null)
  26931. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26932. var bt = Physics3D._bullet;
  26933. bt.btVector3_setValue(Rigidbody3D._btImpulse, -impulse.x, impulse.y, impulse.z);
  26934. if (localOffset) {
  26935. bt.btVector3_setValue(Rigidbody3D._btImpulseOffset, -localOffset.x, localOffset.y, localOffset.z);
  26936. bt.btRigidBody_applyImpulse(this._btColliderObject, Rigidbody3D._btImpulse, Rigidbody3D._btImpulseOffset);
  26937. }
  26938. else {
  26939. bt.btRigidBody_applyCentralImpulse(this._btColliderObject, Rigidbody3D._btImpulse);
  26940. }
  26941. }
  26942. applyTorqueImpulse(torqueImpulse) {
  26943. if (this._btColliderObject == null)
  26944. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26945. var bt = Physics3D._bullet;
  26946. var btTorqueImpulse = Rigidbody3D._btTempVector30;
  26947. bt.btVector3_setValue(btTorqueImpulse, -torqueImpulse.x, torqueImpulse.y, torqueImpulse.z);
  26948. bt.btRigidBody_applyTorqueImpulse(this._btColliderObject, btTorqueImpulse);
  26949. }
  26950. wakeUp() {
  26951. this._btColliderObject && (Physics3D._bullet.btCollisionObject_activate(this._btColliderObject, false));
  26952. }
  26953. clearForces() {
  26954. var rigidBody = this._btColliderObject;
  26955. if (rigidBody == null)
  26956. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  26957. var bt = Physics3D._bullet;
  26958. bt.btRigidBody_clearForces(rigidBody);
  26959. var btZero = Rigidbody3D._btVector3Zero;
  26960. bt.btCollisionObject_setInterpolationLinearVelocity(rigidBody, btZero);
  26961. bt.btRigidBody_setLinearVelocity(rigidBody, btZero);
  26962. bt.btCollisionObject_setInterpolationAngularVelocity(rigidBody, btZero);
  26963. bt.btRigidBody_setAngularVelocity(rigidBody, btZero);
  26964. }
  26965. }
  26966. Rigidbody3D.TYPE_STATIC = 0;
  26967. Rigidbody3D.TYPE_DYNAMIC = 1;
  26968. Rigidbody3D.TYPE_KINEMATIC = 2;
  26969. Rigidbody3D._BT_DISABLE_WORLD_GRAVITY = 1;
  26970. Rigidbody3D._BT_ENABLE_GYROPSCOPIC_FORCE = 2;
  26971. class StaticPlaneColliderShape extends ColliderShape {
  26972. static __init__() {
  26973. StaticPlaneColliderShape._btNormal = Physics3D._bullet.btVector3_create(0, 0, 0);
  26974. }
  26975. constructor(normal, offset) {
  26976. super();
  26977. this._normal = normal;
  26978. this._offset = offset;
  26979. this._type = ColliderShape.SHAPETYPES_STATICPLANE;
  26980. var bt = Physics3D._bullet;
  26981. bt.btVector3_setValue(StaticPlaneColliderShape._btNormal, -normal.x, normal.y, normal.z);
  26982. this._btShape = bt.btStaticPlaneShape_create(StaticPlaneColliderShape._btNormal, offset);
  26983. }
  26984. clone() {
  26985. var dest = new StaticPlaneColliderShape(this._normal, this._offset);
  26986. this.cloneTo(dest);
  26987. return dest;
  26988. }
  26989. }
  26990. class SubMesh extends GeometryElement {
  26991. constructor(mesh) {
  26992. super();
  26993. this._id = ++SubMesh._uniqueIDCounter;
  26994. this._mesh = mesh;
  26995. this._boneIndicesList = [];
  26996. this._subIndexBufferStart = [];
  26997. this._subIndexBufferCount = [];
  26998. }
  26999. get indexCount() {
  27000. return this._indexCount;
  27001. }
  27002. _setIndexRange(indexStart, indexCount) {
  27003. this._indexStart = indexStart;
  27004. this._indexCount = indexCount;
  27005. this._indices = new Uint16Array(this._indexBuffer.getData().buffer, indexStart * 2, indexCount);
  27006. }
  27007. _getType() {
  27008. return SubMesh._type;
  27009. }
  27010. _prepareRender(state) {
  27011. this._mesh._uploadVerticesData();
  27012. return true;
  27013. }
  27014. _render(state) {
  27015. var mesh = this._mesh;
  27016. if (mesh.indexFormat === exports.IndexFormat.UInt32 && !Laya.LayaGL.layaGPUInstance.supportElementIndexUint32()) {
  27017. console.warn("SubMesh:this device do not support IndexFormat.UInt32.");
  27018. return;
  27019. }
  27020. var gl = Laya.LayaGL.instance;
  27021. var skinnedDatas = state.renderElement.render._skinnedData;
  27022. var glIndexFormat;
  27023. switch (mesh.indexFormat) {
  27024. case exports.IndexFormat.UInt32:
  27025. glIndexFormat = gl.UNSIGNED_INT;
  27026. break;
  27027. case exports.IndexFormat.UInt16:
  27028. glIndexFormat = gl.UNSIGNED_SHORT;
  27029. break;
  27030. case exports.IndexFormat.UInt8:
  27031. glIndexFormat = gl.UNSIGNED_BYTE;
  27032. break;
  27033. }
  27034. mesh._bufferState.bind();
  27035. if (skinnedDatas) {
  27036. var subSkinnedDatas = skinnedDatas[this._indexInMesh];
  27037. for (var i = 0, n = this._boneIndicesList.length; i < n; i++) {
  27038. state.shader.uploadCustomUniform(SkinnedMeshSprite3D.BONES, subSkinnedDatas[i]);
  27039. gl.drawElements(gl.TRIANGLES, this._subIndexBufferCount[i], glIndexFormat, this._subIndexBufferStart[i] * 2);
  27040. }
  27041. }
  27042. else {
  27043. gl.drawElements(gl.TRIANGLES, this._indexCount, glIndexFormat, this._indexStart * 2);
  27044. }
  27045. Laya.Stat.trianglesFaces += this._indexCount / 3;
  27046. Laya.Stat.renderBatches++;
  27047. }
  27048. getIndices() {
  27049. if (this._mesh._isReadable)
  27050. return this._indices.slice();
  27051. else
  27052. throw "SubMesh:can't get indices on subMesh,mesh's isReadable must be true.";
  27053. }
  27054. setIndices(indices) {
  27055. this._indexBuffer.setData(indices, this._indexStart, 0, this._indexCount);
  27056. }
  27057. destroy() {
  27058. if (this._destroyed)
  27059. return;
  27060. super.destroy();
  27061. this._indexBuffer.destroy();
  27062. this._indexBuffer = null;
  27063. this._mesh = null;
  27064. this._boneIndicesList = null;
  27065. this._subIndexBufferStart = null;
  27066. this._subIndexBufferCount = null;
  27067. this._skinAnimationDatas = null;
  27068. }
  27069. }
  27070. SubMesh._uniqueIDCounter = 0;
  27071. SubMesh._type = GeometryElement._typeCounter++;
  27072. class LoadModelV04 {
  27073. static parse(readData, version, mesh, subMeshes) {
  27074. LoadModelV04._mesh = mesh;
  27075. LoadModelV04._subMeshes = subMeshes;
  27076. LoadModelV04._version = version;
  27077. LoadModelV04._readData = readData;
  27078. LoadModelV04.READ_DATA();
  27079. LoadModelV04.READ_BLOCK();
  27080. LoadModelV04.READ_STRINGS();
  27081. for (var i = 0, n = LoadModelV04._BLOCK.count; i < n; i++) {
  27082. LoadModelV04._readData.pos = LoadModelV04._BLOCK.blockStarts[i];
  27083. var index = LoadModelV04._readData.getUint16();
  27084. var blockName = LoadModelV04._strings[index];
  27085. var fn = LoadModelV04["READ_" + blockName];
  27086. if (fn == null)
  27087. throw new Error("model file err,no this function:" + index + " " + blockName);
  27088. else
  27089. fn.call(null);
  27090. }
  27091. LoadModelV04._mesh._bindPoseIndices = new Uint16Array(LoadModelV04._bindPoseIndices);
  27092. LoadModelV04._bindPoseIndices.length = 0;
  27093. LoadModelV04._strings.length = 0;
  27094. LoadModelV04._readData = null;
  27095. LoadModelV04._version = null;
  27096. LoadModelV04._mesh = null;
  27097. LoadModelV04._subMeshes = null;
  27098. }
  27099. static _readString() {
  27100. return LoadModelV04._strings[LoadModelV04._readData.getUint16()];
  27101. }
  27102. static READ_DATA() {
  27103. LoadModelV04._DATA.offset = LoadModelV04._readData.getUint32();
  27104. LoadModelV04._DATA.size = LoadModelV04._readData.getUint32();
  27105. }
  27106. static READ_BLOCK() {
  27107. var count = LoadModelV04._BLOCK.count = LoadModelV04._readData.getUint16();
  27108. var blockStarts = LoadModelV04._BLOCK.blockStarts = [];
  27109. var blockLengths = LoadModelV04._BLOCK.blockLengths = [];
  27110. for (var i = 0; i < count; i++) {
  27111. blockStarts.push(LoadModelV04._readData.getUint32());
  27112. blockLengths.push(LoadModelV04._readData.getUint32());
  27113. }
  27114. }
  27115. static READ_STRINGS() {
  27116. var offset = LoadModelV04._readData.getUint32();
  27117. var count = LoadModelV04._readData.getUint16();
  27118. var prePos = LoadModelV04._readData.pos;
  27119. LoadModelV04._readData.pos = offset + LoadModelV04._DATA.offset;
  27120. for (var i = 0; i < count; i++)
  27121. LoadModelV04._strings[i] = LoadModelV04._readData.readUTFString();
  27122. LoadModelV04._readData.pos = prePos;
  27123. }
  27124. static READ_MESH() {
  27125. var gl = Laya.LayaGL.instance;
  27126. var name = LoadModelV04._readString();
  27127. var arrayBuffer = LoadModelV04._readData.__getBuffer();
  27128. var i;
  27129. var memorySize = 0;
  27130. var vertexBufferCount = LoadModelV04._readData.getInt16();
  27131. var offset = LoadModelV04._DATA.offset;
  27132. for (i = 0; i < vertexBufferCount; i++) {
  27133. var vbStart = offset + LoadModelV04._readData.getUint32();
  27134. var vbLength = LoadModelV04._readData.getUint32();
  27135. var vbArrayBuffer = arrayBuffer.slice(vbStart, vbStart + vbLength);
  27136. var vbDatas = new Float32Array(vbArrayBuffer);
  27137. var bufferAttribute = LoadModelV04._readString();
  27138. var vertexDeclaration;
  27139. switch (LoadModelV04._version) {
  27140. case "LAYAMODEL:0301":
  27141. case "LAYAMODEL:0400":
  27142. vertexDeclaration = VertexMesh.getVertexDeclaration(bufferAttribute);
  27143. break;
  27144. case "LAYAMODEL:0401":
  27145. vertexDeclaration = VertexMesh.getVertexDeclaration(bufferAttribute, false);
  27146. break;
  27147. default:
  27148. throw new Error("LoadModelV03: unknown version.");
  27149. }
  27150. if (!vertexDeclaration)
  27151. throw new Error("LoadModelV03: unknown vertexDeclaration.");
  27152. var vertexBuffer = new VertexBuffer3D(vbDatas.length * 4, gl.STATIC_DRAW, true);
  27153. vertexBuffer.vertexDeclaration = vertexDeclaration;
  27154. vertexBuffer.setData(vbDatas.buffer);
  27155. LoadModelV04._mesh._vertexBuffer = vertexBuffer;
  27156. LoadModelV04._mesh._vertexCount += vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  27157. memorySize += vbDatas.length * 4;
  27158. }
  27159. var ibStart = offset + LoadModelV04._readData.getUint32();
  27160. var ibLength = LoadModelV04._readData.getUint32();
  27161. var ibDatas = new Uint16Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  27162. var indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, ibLength / 2, gl.STATIC_DRAW, true);
  27163. indexBuffer.setData(ibDatas);
  27164. LoadModelV04._mesh._indexBuffer = indexBuffer;
  27165. memorySize += indexBuffer.indexCount * 2;
  27166. LoadModelV04._mesh._setBuffer(LoadModelV04._mesh._vertexBuffer, indexBuffer);
  27167. LoadModelV04._mesh._setCPUMemory(memorySize);
  27168. LoadModelV04._mesh._setGPUMemory(memorySize);
  27169. var boneNames = LoadModelV04._mesh._boneNames = [];
  27170. var boneCount = LoadModelV04._readData.getUint16();
  27171. boneNames.length = boneCount;
  27172. for (i = 0; i < boneCount; i++)
  27173. boneNames[i] = LoadModelV04._strings[LoadModelV04._readData.getUint16()];
  27174. LoadModelV04._readData.pos += 8;
  27175. var bindPoseDataStart = LoadModelV04._readData.getUint32();
  27176. var bindPoseDataLength = LoadModelV04._readData.getUint32();
  27177. var bindPoseDatas = new Float32Array(arrayBuffer.slice(offset + bindPoseDataStart, offset + bindPoseDataStart + bindPoseDataLength));
  27178. var bindPoseFloatCount = bindPoseDatas.length;
  27179. var bindPoseBuffer = LoadModelV04._mesh._inverseBindPosesBuffer = new ArrayBuffer(bindPoseFloatCount * 4);
  27180. LoadModelV04._mesh._inverseBindPoses = [];
  27181. for (i = 0; i < bindPoseFloatCount; i += 16) {
  27182. var inverseGlobalBindPose = new Matrix4x4(bindPoseDatas[i + 0], bindPoseDatas[i + 1], bindPoseDatas[i + 2], bindPoseDatas[i + 3], bindPoseDatas[i + 4], bindPoseDatas[i + 5], bindPoseDatas[i + 6], bindPoseDatas[i + 7], bindPoseDatas[i + 8], bindPoseDatas[i + 9], bindPoseDatas[i + 10], bindPoseDatas[i + 11], bindPoseDatas[i + 12], bindPoseDatas[i + 13], bindPoseDatas[i + 14], bindPoseDatas[i + 15], new Float32Array(bindPoseBuffer, i * 4, 16));
  27183. LoadModelV04._mesh._inverseBindPoses[i / 16] = inverseGlobalBindPose;
  27184. }
  27185. return true;
  27186. }
  27187. static READ_SUBMESH() {
  27188. var arrayBuffer = LoadModelV04._readData.__getBuffer();
  27189. var subMesh = new SubMesh(LoadModelV04._mesh);
  27190. LoadModelV04._readData.getInt16();
  27191. LoadModelV04._readData.getUint32();
  27192. LoadModelV04._readData.getUint32();
  27193. var ibStart = LoadModelV04._readData.getUint32();
  27194. var ibCount = LoadModelV04._readData.getUint32();
  27195. var indexBuffer = LoadModelV04._mesh._indexBuffer;
  27196. subMesh._indexBuffer = indexBuffer;
  27197. subMesh._setIndexRange(ibStart, ibCount);
  27198. var vertexBuffer = LoadModelV04._mesh._vertexBuffer;
  27199. subMesh._vertexBuffer = vertexBuffer;
  27200. var offset = LoadModelV04._DATA.offset;
  27201. var subIndexBufferStart = subMesh._subIndexBufferStart;
  27202. var subIndexBufferCount = subMesh._subIndexBufferCount;
  27203. var boneIndicesList = subMesh._boneIndicesList;
  27204. var drawCount = LoadModelV04._readData.getUint16();
  27205. subIndexBufferStart.length = drawCount;
  27206. subIndexBufferCount.length = drawCount;
  27207. boneIndicesList.length = drawCount;
  27208. var pathMarks = LoadModelV04._mesh._skinDataPathMarks;
  27209. var bindPoseIndices = LoadModelV04._bindPoseIndices;
  27210. var subMeshIndex = LoadModelV04._subMeshes.length;
  27211. for (var i = 0; i < drawCount; i++) {
  27212. subIndexBufferStart[i] = LoadModelV04._readData.getUint32();
  27213. subIndexBufferCount[i] = LoadModelV04._readData.getUint32();
  27214. var boneDicofs = LoadModelV04._readData.getUint32();
  27215. var boneDicCount = LoadModelV04._readData.getUint32();
  27216. var boneIndices = boneIndicesList[i] = new Uint16Array(arrayBuffer.slice(offset + boneDicofs, offset + boneDicofs + boneDicCount));
  27217. for (var j = 0, m = boneIndices.length; j < m; j++) {
  27218. var index = boneIndices[j];
  27219. var combineIndex = bindPoseIndices.indexOf(index);
  27220. if (combineIndex === -1) {
  27221. boneIndices[j] = bindPoseIndices.length;
  27222. bindPoseIndices.push(index);
  27223. pathMarks.push([subMeshIndex, i, j]);
  27224. }
  27225. else {
  27226. boneIndices[j] = combineIndex;
  27227. }
  27228. }
  27229. }
  27230. LoadModelV04._subMeshes.push(subMesh);
  27231. return true;
  27232. }
  27233. }
  27234. LoadModelV04._BLOCK = { count: 0 };
  27235. LoadModelV04._DATA = { offset: 0, size: 0 };
  27236. LoadModelV04._strings = [];
  27237. LoadModelV04._bindPoseIndices = [];
  27238. class LoadModelV05 {
  27239. static parse(readData, version, mesh, subMeshes) {
  27240. LoadModelV05._mesh = mesh;
  27241. LoadModelV05._subMeshes = subMeshes;
  27242. LoadModelV05._version = version;
  27243. LoadModelV05._readData = readData;
  27244. LoadModelV05.READ_DATA();
  27245. LoadModelV05.READ_BLOCK();
  27246. LoadModelV05.READ_STRINGS();
  27247. for (var i = 0, n = LoadModelV05._BLOCK.count; i < n; i++) {
  27248. LoadModelV05._readData.pos = LoadModelV05._BLOCK.blockStarts[i];
  27249. var index = LoadModelV05._readData.getUint16();
  27250. var blockName = LoadModelV05._strings[index];
  27251. var fn = LoadModelV05["READ_" + blockName];
  27252. if (fn == null)
  27253. throw new Error("model file err,no this function:" + index + " " + blockName);
  27254. else
  27255. fn.call(null);
  27256. }
  27257. LoadModelV05._mesh._bindPoseIndices = new Uint16Array(LoadModelV05._bindPoseIndices);
  27258. LoadModelV05._bindPoseIndices.length = 0;
  27259. LoadModelV05._strings.length = 0;
  27260. LoadModelV05._readData = null;
  27261. LoadModelV05._version = null;
  27262. LoadModelV05._mesh = null;
  27263. LoadModelV05._subMeshes = null;
  27264. }
  27265. static _readString() {
  27266. return LoadModelV05._strings[LoadModelV05._readData.getUint16()];
  27267. }
  27268. static READ_DATA() {
  27269. LoadModelV05._DATA.offset = LoadModelV05._readData.getUint32();
  27270. LoadModelV05._DATA.size = LoadModelV05._readData.getUint32();
  27271. }
  27272. static READ_BLOCK() {
  27273. var count = LoadModelV05._BLOCK.count = LoadModelV05._readData.getUint16();
  27274. var blockStarts = LoadModelV05._BLOCK.blockStarts = [];
  27275. var blockLengths = LoadModelV05._BLOCK.blockLengths = [];
  27276. for (var i = 0; i < count; i++) {
  27277. blockStarts.push(LoadModelV05._readData.getUint32());
  27278. blockLengths.push(LoadModelV05._readData.getUint32());
  27279. }
  27280. }
  27281. static READ_STRINGS() {
  27282. var offset = LoadModelV05._readData.getUint32();
  27283. var count = LoadModelV05._readData.getUint16();
  27284. var prePos = LoadModelV05._readData.pos;
  27285. LoadModelV05._readData.pos = offset + LoadModelV05._DATA.offset;
  27286. for (var i = 0; i < count; i++)
  27287. LoadModelV05._strings[i] = LoadModelV05._readData.readUTFString();
  27288. LoadModelV05._readData.pos = prePos;
  27289. }
  27290. static READ_MESH() {
  27291. var gl = Laya.LayaGL.instance;
  27292. var i;
  27293. var memorySize = 0;
  27294. var name = LoadModelV05._readString();
  27295. var reader = LoadModelV05._readData;
  27296. var arrayBuffer = reader.__getBuffer();
  27297. var vertexBufferCount = reader.getInt16();
  27298. var offset = LoadModelV05._DATA.offset;
  27299. for (i = 0; i < vertexBufferCount; i++) {
  27300. var vbStart = offset + reader.getUint32();
  27301. var vertexCount = reader.getUint32();
  27302. var vertexFlag = LoadModelV05._readString();
  27303. var vertexDeclaration = VertexMesh.getVertexDeclaration(vertexFlag, false);
  27304. var vertexStride = vertexDeclaration.vertexStride;
  27305. var vertexData;
  27306. var floatData;
  27307. var uint8Data;
  27308. var subVertexFlags = vertexFlag.split(",");
  27309. var subVertexCount = subVertexFlags.length;
  27310. var mesh = LoadModelV05._mesh;
  27311. switch (LoadModelV05._version) {
  27312. case "LAYAMODEL:05":
  27313. vertexData = arrayBuffer.slice(vbStart, vbStart + vertexCount * vertexStride);
  27314. floatData = new Float32Array(vertexData);
  27315. uint8Data = new Uint8Array(vertexData);
  27316. break;
  27317. case "LAYAMODEL:COMPRESSION_05":
  27318. vertexData = new ArrayBuffer(vertexStride * vertexCount);
  27319. floatData = new Float32Array(vertexData);
  27320. uint8Data = new Uint8Array(vertexData);
  27321. var lastPosition = reader.pos;
  27322. reader.pos = vbStart;
  27323. for (var j = 0; j < vertexCount; j++) {
  27324. var subOffset;
  27325. var verOffset = j * vertexStride;
  27326. for (var k = 0; k < subVertexCount; k++) {
  27327. switch (subVertexFlags[k]) {
  27328. case "POSITION":
  27329. subOffset = verOffset / 4;
  27330. floatData[subOffset] = HalfFloatUtils.convertToNumber(reader.getUint16());
  27331. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(reader.getUint16());
  27332. floatData[subOffset + 2] = HalfFloatUtils.convertToNumber(reader.getUint16());
  27333. verOffset += 12;
  27334. break;
  27335. case "NORMAL":
  27336. subOffset = verOffset / 4;
  27337. floatData[subOffset] = reader.getUint8() / 127.5 - 1;
  27338. floatData[subOffset + 1] = reader.getUint8() / 127.5 - 1;
  27339. floatData[subOffset + 2] = reader.getUint8() / 127.5 - 1;
  27340. verOffset += 12;
  27341. break;
  27342. case "COLOR":
  27343. subOffset = verOffset / 4;
  27344. floatData[subOffset] = reader.getUint8() / 255;
  27345. floatData[subOffset + 1] = reader.getUint8() / 255;
  27346. floatData[subOffset + 2] = reader.getUint8() / 255;
  27347. floatData[subOffset + 3] = reader.getUint8() / 255;
  27348. verOffset += 16;
  27349. break;
  27350. case "UV":
  27351. subOffset = verOffset / 4;
  27352. floatData[subOffset] = HalfFloatUtils.convertToNumber(reader.getUint16());
  27353. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(reader.getUint16());
  27354. verOffset += 8;
  27355. break;
  27356. case "UV1":
  27357. subOffset = verOffset / 4;
  27358. floatData[subOffset] = HalfFloatUtils.convertToNumber(reader.getUint16());
  27359. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(reader.getUint16());
  27360. verOffset += 8;
  27361. break;
  27362. case "BLENDWEIGHT":
  27363. subOffset = verOffset / 4;
  27364. floatData[subOffset] = reader.getUint8() / 255;
  27365. floatData[subOffset + 1] = reader.getUint8() / 255;
  27366. floatData[subOffset + 2] = reader.getUint8() / 255;
  27367. floatData[subOffset + 3] = reader.getUint8() / 255;
  27368. verOffset += 16;
  27369. break;
  27370. case "BLENDINDICES":
  27371. uint8Data[verOffset] = reader.getUint8();
  27372. uint8Data[verOffset + 1] = reader.getUint8();
  27373. uint8Data[verOffset + 2] = reader.getUint8();
  27374. uint8Data[verOffset + 3] = reader.getUint8();
  27375. verOffset += 4;
  27376. break;
  27377. case "TANGENT":
  27378. subOffset = verOffset / 4;
  27379. floatData[subOffset] = reader.getUint8() / 127.5 - 1;
  27380. floatData[subOffset + 1] = reader.getUint8() / 127.5 - 1;
  27381. floatData[subOffset + 2] = reader.getUint8() / 127.5 - 1;
  27382. floatData[subOffset + 3] = reader.getUint8() / 127.5 - 1;
  27383. verOffset += 16;
  27384. break;
  27385. }
  27386. }
  27387. }
  27388. reader.pos = lastPosition;
  27389. break;
  27390. }
  27391. var vertexBuffer = new VertexBuffer3D(vertexData.byteLength, gl.STATIC_DRAW, true);
  27392. vertexBuffer.vertexDeclaration = vertexDeclaration;
  27393. vertexBuffer.setData(vertexData);
  27394. var vertexCount = vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  27395. if (vertexCount > 65535)
  27396. mesh._indexFormat = exports.IndexFormat.UInt32;
  27397. else
  27398. mesh._indexFormat = exports.IndexFormat.UInt16;
  27399. mesh._vertexBuffer = vertexBuffer;
  27400. mesh._vertexCount += vertexCount;
  27401. memorySize += floatData.length * 4;
  27402. }
  27403. var ibStart = offset + reader.getUint32();
  27404. var ibLength = reader.getUint32();
  27405. var ibDatas;
  27406. if (mesh.indexFormat == exports.IndexFormat.UInt32)
  27407. ibDatas = new Uint32Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  27408. else
  27409. ibDatas = new Uint16Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  27410. var indexBuffer = new IndexBuffer3D(mesh.indexFormat, ibDatas.length, gl.STATIC_DRAW, true);
  27411. indexBuffer.setData(ibDatas);
  27412. mesh._indexBuffer = indexBuffer;
  27413. mesh._setBuffer(mesh._vertexBuffer, indexBuffer);
  27414. memorySize += indexBuffer.indexCount * 2;
  27415. mesh._setCPUMemory(memorySize);
  27416. mesh._setGPUMemory(memorySize);
  27417. var boneNames = mesh._boneNames = [];
  27418. var boneCount = reader.getUint16();
  27419. boneNames.length = boneCount;
  27420. for (i = 0; i < boneCount; i++)
  27421. boneNames[i] = LoadModelV05._strings[reader.getUint16()];
  27422. var bindPoseDataStart = reader.getUint32();
  27423. var bindPoseDataLength = reader.getUint32();
  27424. var bindPoseDatas = new Float32Array(arrayBuffer.slice(offset + bindPoseDataStart, offset + bindPoseDataStart + bindPoseDataLength));
  27425. var bindPoseFloatCount = bindPoseDatas.length;
  27426. var bindPoseBuffer = mesh._inverseBindPosesBuffer = new ArrayBuffer(bindPoseFloatCount * 4);
  27427. mesh._inverseBindPoses = [];
  27428. for (i = 0; i < bindPoseFloatCount; i += 16) {
  27429. var inverseGlobalBindPose = new Matrix4x4(bindPoseDatas[i + 0], bindPoseDatas[i + 1], bindPoseDatas[i + 2], bindPoseDatas[i + 3], bindPoseDatas[i + 4], bindPoseDatas[i + 5], bindPoseDatas[i + 6], bindPoseDatas[i + 7], bindPoseDatas[i + 8], bindPoseDatas[i + 9], bindPoseDatas[i + 10], bindPoseDatas[i + 11], bindPoseDatas[i + 12], bindPoseDatas[i + 13], bindPoseDatas[i + 14], bindPoseDatas[i + 15], new Float32Array(bindPoseBuffer, i * 4, 16));
  27430. mesh._inverseBindPoses[i / 16] = inverseGlobalBindPose;
  27431. }
  27432. return true;
  27433. }
  27434. static READ_SUBMESH() {
  27435. var reader = LoadModelV05._readData;
  27436. var arrayBuffer = reader.__getBuffer();
  27437. var subMesh = new SubMesh(LoadModelV05._mesh);
  27438. reader.getInt16();
  27439. var ibStart = reader.getUint32();
  27440. var ibCount = reader.getUint32();
  27441. var indexBuffer = LoadModelV05._mesh._indexBuffer;
  27442. subMesh._indexBuffer = indexBuffer;
  27443. subMesh._setIndexRange(ibStart, ibCount);
  27444. var vertexBuffer = LoadModelV05._mesh._vertexBuffer;
  27445. subMesh._vertexBuffer = vertexBuffer;
  27446. var offset = LoadModelV05._DATA.offset;
  27447. var subIndexBufferStart = subMesh._subIndexBufferStart;
  27448. var subIndexBufferCount = subMesh._subIndexBufferCount;
  27449. var boneIndicesList = subMesh._boneIndicesList;
  27450. var drawCount = reader.getUint16();
  27451. subIndexBufferStart.length = drawCount;
  27452. subIndexBufferCount.length = drawCount;
  27453. boneIndicesList.length = drawCount;
  27454. var pathMarks = LoadModelV05._mesh._skinDataPathMarks;
  27455. var bindPoseIndices = LoadModelV05._bindPoseIndices;
  27456. var subMeshIndex = LoadModelV05._subMeshes.length;
  27457. for (var i = 0; i < drawCount; i++) {
  27458. subIndexBufferStart[i] = reader.getUint32();
  27459. subIndexBufferCount[i] = reader.getUint32();
  27460. var boneDicofs = reader.getUint32();
  27461. var boneDicCount = reader.getUint32();
  27462. var boneIndices = boneIndicesList[i] = new Uint16Array(arrayBuffer.slice(offset + boneDicofs, offset + boneDicofs + boneDicCount));
  27463. for (var j = 0, m = boneIndices.length; j < m; j++) {
  27464. var index = boneIndices[j];
  27465. var combineIndex = bindPoseIndices.indexOf(index);
  27466. if (combineIndex === -1) {
  27467. boneIndices[j] = bindPoseIndices.length;
  27468. bindPoseIndices.push(index);
  27469. pathMarks.push([subMeshIndex, i, j]);
  27470. }
  27471. else {
  27472. boneIndices[j] = combineIndex;
  27473. }
  27474. }
  27475. }
  27476. LoadModelV05._subMeshes.push(subMesh);
  27477. return true;
  27478. }
  27479. }
  27480. LoadModelV05._BLOCK = { count: 0 };
  27481. LoadModelV05._DATA = { offset: 0, size: 0 };
  27482. LoadModelV05._strings = [];
  27483. LoadModelV05._bindPoseIndices = [];
  27484. class MeshReader {
  27485. constructor() {
  27486. }
  27487. static read(data, mesh, subMeshes) {
  27488. var readData = new Laya.Byte(data);
  27489. readData.pos = 0;
  27490. var version = readData.readUTFString();
  27491. switch (version) {
  27492. case "LAYAMODEL:0301":
  27493. case "LAYAMODEL:0400":
  27494. case "LAYAMODEL:0401":
  27495. LoadModelV04.parse(readData, version, mesh, subMeshes);
  27496. break;
  27497. case "LAYAMODEL:05":
  27498. case "LAYAMODEL:COMPRESSION_05":
  27499. LoadModelV05.parse(readData, version, mesh, subMeshes);
  27500. break;
  27501. default:
  27502. throw new Error("MeshReader: unknown mesh version.");
  27503. }
  27504. mesh._setSubMeshes(subMeshes);
  27505. }
  27506. }
  27507. class Mesh extends Laya.Resource {
  27508. constructor(isReadable = true) {
  27509. super();
  27510. this._tempVector30 = new Vector3();
  27511. this._tempVector31 = new Vector3();
  27512. this._tempVector32 = new Vector3();
  27513. this._minVerticesUpdate = -1;
  27514. this._maxVerticesUpdate = -1;
  27515. this._needUpdateBounds = true;
  27516. this._bounds = new Bounds(new Vector3(), new Vector3());
  27517. this._bufferState = new BufferState();
  27518. this._instanceBufferState = new BufferState();
  27519. this._vertexBuffer = null;
  27520. this._indexBuffer = null;
  27521. this._vertexCount = 0;
  27522. this._indexFormat = exports.IndexFormat.UInt16;
  27523. this._isReadable = isReadable;
  27524. this._subMeshes = [];
  27525. this._skinDataPathMarks = [];
  27526. }
  27527. static __init__() {
  27528. var physics3D = Physics3D._bullet;
  27529. if (physics3D) {
  27530. Mesh._nativeTempVector30 = physics3D.btVector3_create(0, 0, 0);
  27531. Mesh._nativeTempVector31 = physics3D.btVector3_create(0, 0, 0);
  27532. Mesh._nativeTempVector32 = physics3D.btVector3_create(0, 0, 0);
  27533. }
  27534. }
  27535. static _parse(data, propertyParams = null, constructParams = null) {
  27536. var mesh = new Mesh();
  27537. MeshReader.read(data, mesh, mesh._subMeshes);
  27538. return mesh;
  27539. }
  27540. static load(url, complete) {
  27541. Laya.ILaya.loader.create(url, complete, null, Mesh.MESH);
  27542. }
  27543. get inverseAbsoluteBindPoses() {
  27544. return this._inverseBindPoses;
  27545. }
  27546. get vertexCount() {
  27547. return this._vertexCount;
  27548. }
  27549. get indexCount() {
  27550. return this._indexBuffer.indexCount;
  27551. }
  27552. get subMeshCount() {
  27553. return this._subMeshes.length;
  27554. }
  27555. get bounds() {
  27556. return this._bounds;
  27557. }
  27558. set bounds(value) {
  27559. if (this._bounds !== value)
  27560. value.cloneTo(this._bounds);
  27561. }
  27562. get indexFormat() {
  27563. return this._indexFormat;
  27564. }
  27565. _getPositionElement(vertexBuffer) {
  27566. var vertexElements = vertexBuffer.vertexDeclaration._vertexElements;
  27567. for (var i = 0, n = vertexElements.length; i < n; i++) {
  27568. var vertexElement = vertexElements[i];
  27569. if (vertexElement._elementFormat === VertexElementFormat.Vector3 && vertexElement._elementUsage === VertexMesh.MESH_POSITION0)
  27570. return vertexElement;
  27571. }
  27572. return null;
  27573. }
  27574. _getVerticeElementData(data, elementUsage) {
  27575. data.length = this._vertexCount;
  27576. var verDec = this._vertexBuffer.vertexDeclaration;
  27577. var element = verDec.getVertexElementByUsage(elementUsage);
  27578. if (element) {
  27579. var uint8Vertices = this._vertexBuffer.getUint8Data();
  27580. var floatVertices = this._vertexBuffer.getFloat32Data();
  27581. var uint8VerStr = verDec.vertexStride;
  27582. var floatVerStr = uint8VerStr / 4;
  27583. var uint8EleOffset = element._offset;
  27584. var floatEleOffset = uint8EleOffset / 4;
  27585. switch (elementUsage) {
  27586. case VertexMesh.MESH_TEXTURECOORDINATE0:
  27587. case VertexMesh.MESH_TEXTURECOORDINATE1:
  27588. for (var i = 0; i < this._vertexCount; i++) {
  27589. var offset = floatVerStr * i + floatEleOffset;
  27590. data[i] = new Vector2(floatVertices[offset], floatVertices[offset + 1]);
  27591. }
  27592. break;
  27593. case VertexMesh.MESH_POSITION0:
  27594. case VertexMesh.MESH_NORMAL0:
  27595. for (var i = 0; i < this._vertexCount; i++) {
  27596. var offset = floatVerStr * i + floatEleOffset;
  27597. data[i] = new Vector3(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2]);
  27598. }
  27599. break;
  27600. case VertexMesh.MESH_TANGENT0:
  27601. case VertexMesh.MESH_BLENDWEIGHT0:
  27602. for (var i = 0; i < this._vertexCount; i++) {
  27603. var offset = floatVerStr * i + floatEleOffset;
  27604. data[i] = new Vector4(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2], floatVertices[offset + 3]);
  27605. }
  27606. break;
  27607. case VertexMesh.MESH_COLOR0:
  27608. for (var i = 0; i < this._vertexCount; i++) {
  27609. var offset = floatVerStr * i + floatEleOffset;
  27610. data[i] = new Color(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2], floatVertices[offset + 3]);
  27611. }
  27612. break;
  27613. case VertexMesh.MESH_BLENDINDICES0:
  27614. for (var i = 0; i < this._vertexCount; i++) {
  27615. var offset = uint8VerStr * i + uint8EleOffset;
  27616. data[i] = new Vector4(uint8Vertices[offset], uint8Vertices[offset + 1], uint8Vertices[offset + 2], uint8Vertices[offset + 3]);
  27617. }
  27618. break;
  27619. default:
  27620. throw "Mesh:Unknown elementUsage.";
  27621. }
  27622. }
  27623. }
  27624. _setVerticeElementData(data, elementUsage) {
  27625. var verDec = this._vertexBuffer.vertexDeclaration;
  27626. var element = verDec.getVertexElementByUsage(elementUsage);
  27627. if (element) {
  27628. var uint8Vertices = this._vertexBuffer.getUint8Data();
  27629. var floatVertices = this._vertexBuffer.getFloat32Data();
  27630. var uint8VerStr = verDec.vertexStride;
  27631. var float8VerStr = uint8VerStr / 4;
  27632. var uint8EleOffset = element._offset;
  27633. var floatEleOffset = uint8EleOffset / 4;
  27634. switch (elementUsage) {
  27635. case VertexMesh.MESH_TEXTURECOORDINATE0:
  27636. case VertexMesh.MESH_TEXTURECOORDINATE1:
  27637. for (var i = 0, n = data.length; i < n; i++) {
  27638. var offset = float8VerStr * i + floatEleOffset;
  27639. var vec2 = data[i];
  27640. floatVertices[offset] = vec2.x;
  27641. floatVertices[offset + 1] = vec2.y;
  27642. }
  27643. break;
  27644. case VertexMesh.MESH_POSITION0:
  27645. case VertexMesh.MESH_NORMAL0:
  27646. for (var i = 0, n = data.length; i < n; i++) {
  27647. var offset = float8VerStr * i + floatEleOffset;
  27648. var vec3 = data[i];
  27649. floatVertices[offset] = vec3.x;
  27650. floatVertices[offset + 1] = vec3.y;
  27651. floatVertices[offset + 2] = vec3.z;
  27652. }
  27653. break;
  27654. case VertexMesh.MESH_TANGENT0:
  27655. case VertexMesh.MESH_BLENDWEIGHT0:
  27656. for (var i = 0, n = data.length; i < n; i++) {
  27657. var offset = float8VerStr * i + floatEleOffset;
  27658. var vec4 = data[i];
  27659. floatVertices[offset] = vec4.x;
  27660. floatVertices[offset + 1] = vec4.y;
  27661. floatVertices[offset + 2] = vec4.z;
  27662. floatVertices[offset + 3] = vec4.w;
  27663. }
  27664. break;
  27665. case VertexMesh.MESH_COLOR0:
  27666. for (var i = 0, n = data.length; i < n; i++) {
  27667. var offset = float8VerStr * i + floatEleOffset;
  27668. var cor = data[i];
  27669. floatVertices[offset] = cor.r;
  27670. floatVertices[offset + 1] = cor.g;
  27671. floatVertices[offset + 2] = cor.b;
  27672. floatVertices[offset + 2] = cor.a;
  27673. }
  27674. break;
  27675. case VertexMesh.MESH_BLENDINDICES0:
  27676. for (var i = 0, n = data.length; i < n; i++) {
  27677. var offset = uint8VerStr * i + uint8EleOffset;
  27678. var vec4 = data[i];
  27679. uint8Vertices[offset] = vec4.x;
  27680. uint8Vertices[offset + 1] = vec4.y;
  27681. uint8Vertices[offset + 2] = vec4.z;
  27682. uint8Vertices[offset + 3] = vec4.w;
  27683. }
  27684. break;
  27685. default:
  27686. throw "Mesh:Unknown elementUsage.";
  27687. }
  27688. this._minVerticesUpdate = 0;
  27689. this._maxVerticesUpdate = Number.MAX_SAFE_INTEGER;
  27690. }
  27691. else {
  27692. console.warn("Mesh: the mesh don't have this VertexElement.");
  27693. }
  27694. }
  27695. _disposeResource() {
  27696. for (var i = 0, n = this._subMeshes.length; i < n; i++)
  27697. this._subMeshes[i].destroy();
  27698. this._btTriangleMesh && Physics3D._bullet.btStridingMeshInterface_destroy(this._btTriangleMesh);
  27699. this._vertexBuffer.destroy();
  27700. this._indexBuffer.destroy();
  27701. this._bufferState.destroy();
  27702. this._instanceBufferState.destroy();
  27703. this._setCPUMemory(0);
  27704. this._setGPUMemory(0);
  27705. this._bufferState = null;
  27706. this._instanceBufferState = null;
  27707. this._vertexBuffer = null;
  27708. this._indexBuffer = null;
  27709. this._subMeshes = null;
  27710. this._btTriangleMesh = null;
  27711. this._indexBuffer = null;
  27712. this._boneNames = null;
  27713. this._inverseBindPoses = null;
  27714. }
  27715. _setSubMeshes(subMeshes) {
  27716. this._subMeshes = subMeshes;
  27717. for (var i = 0, n = subMeshes.length; i < n; i++)
  27718. subMeshes[i]._indexInMesh = i;
  27719. this.calculateBounds();
  27720. }
  27721. _setBuffer(vertexBuffer, indexBuffer) {
  27722. var bufferState = this._bufferState;
  27723. bufferState.bind();
  27724. bufferState.applyVertexBuffer(vertexBuffer);
  27725. bufferState.applyIndexBuffer(indexBuffer);
  27726. bufferState.unBind();
  27727. var instanceBufferState = this._instanceBufferState;
  27728. instanceBufferState.bind();
  27729. instanceBufferState.applyVertexBuffer(vertexBuffer);
  27730. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer);
  27731. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer);
  27732. instanceBufferState.applyIndexBuffer(indexBuffer);
  27733. instanceBufferState.unBind();
  27734. }
  27735. _getPhysicMesh() {
  27736. if (!this._btTriangleMesh) {
  27737. var bt = Physics3D._bullet;
  27738. var triangleMesh = bt.btTriangleMesh_create();
  27739. var nativePositio0 = Mesh._nativeTempVector30;
  27740. var nativePositio1 = Mesh._nativeTempVector31;
  27741. var nativePositio2 = Mesh._nativeTempVector32;
  27742. var position0 = this._tempVector30;
  27743. var position1 = this._tempVector31;
  27744. var position2 = this._tempVector32;
  27745. var vertexBuffer = this._vertexBuffer;
  27746. var positionElement = this._getPositionElement(vertexBuffer);
  27747. var verticesData = vertexBuffer.getFloat32Data();
  27748. var floatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  27749. var posOffset = positionElement._offset / 4;
  27750. var indices = this._indexBuffer.getData();
  27751. for (var i = 0, n = indices.length; i < n; i += 3) {
  27752. var p0Index = indices[i] * floatCount + posOffset;
  27753. var p1Index = indices[i + 1] * floatCount + posOffset;
  27754. var p2Index = indices[i + 2] * floatCount + posOffset;
  27755. position0.setValue(verticesData[p0Index], verticesData[p0Index + 1], verticesData[p0Index + 2]);
  27756. position1.setValue(verticesData[p1Index], verticesData[p1Index + 1], verticesData[p1Index + 2]);
  27757. position2.setValue(verticesData[p2Index], verticesData[p2Index + 1], verticesData[p2Index + 2]);
  27758. Utils3D._convertToBulletVec3(position0, nativePositio0, true);
  27759. Utils3D._convertToBulletVec3(position1, nativePositio1, true);
  27760. Utils3D._convertToBulletVec3(position2, nativePositio2, true);
  27761. bt.btTriangleMesh_addTriangle(triangleMesh, nativePositio0, nativePositio1, nativePositio2, true);
  27762. }
  27763. this._btTriangleMesh = triangleMesh;
  27764. }
  27765. return this._btTriangleMesh;
  27766. }
  27767. _uploadVerticesData() {
  27768. var min = this._minVerticesUpdate;
  27769. var max = this._maxVerticesUpdate;
  27770. if (min !== -1 && max !== -1) {
  27771. var offset = min;
  27772. this._vertexBuffer.setData(this._vertexBuffer.getUint8Data().buffer, offset, offset, max - min);
  27773. this._minVerticesUpdate = -1;
  27774. this._maxVerticesUpdate = -1;
  27775. }
  27776. }
  27777. getSubMesh(index) {
  27778. return this._subMeshes[index];
  27779. }
  27780. getPositions(positions) {
  27781. if (this._isReadable)
  27782. this._getVerticeElementData(positions, VertexMesh.MESH_POSITION0);
  27783. else
  27784. throw "Mesh:can't get positions on mesh,isReadable must be true.";
  27785. }
  27786. setPositions(positions) {
  27787. if (this._isReadable) {
  27788. this._setVerticeElementData(positions, VertexMesh.MESH_POSITION0);
  27789. this._needUpdateBounds = true;
  27790. }
  27791. else {
  27792. throw "Mesh:setPosition() need isReadable must be true or use setVertices().";
  27793. }
  27794. }
  27795. getColors(colors) {
  27796. if (this._isReadable)
  27797. this._getVerticeElementData(colors, VertexMesh.MESH_COLOR0);
  27798. else
  27799. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  27800. }
  27801. setColors(colors) {
  27802. if (this._isReadable)
  27803. this._setVerticeElementData(colors, VertexMesh.MESH_COLOR0);
  27804. else
  27805. throw "Mesh:setColors() need isReadable must be true or use setVertices().";
  27806. }
  27807. getUVs(uvs, channel = 0) {
  27808. if (this._isReadable) {
  27809. switch (channel) {
  27810. case 0:
  27811. this._getVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE0);
  27812. break;
  27813. case 1:
  27814. this._getVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE1);
  27815. break;
  27816. default:
  27817. throw "Mesh:Invalid channel.";
  27818. }
  27819. }
  27820. else {
  27821. throw "Mesh:can't get uvs on mesh,isReadable must be true.";
  27822. }
  27823. }
  27824. setUVs(uvs, channel = 0) {
  27825. if (this._isReadable) {
  27826. switch (channel) {
  27827. case 0:
  27828. this._setVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE0);
  27829. break;
  27830. case 1:
  27831. this._setVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE1);
  27832. break;
  27833. default:
  27834. throw "Mesh:Invalid channel.";
  27835. }
  27836. }
  27837. else {
  27838. throw "Mesh:setUVs() need isReadable must be true or use setVertices().";
  27839. }
  27840. }
  27841. getNormals(normals) {
  27842. if (this._isReadable)
  27843. this._getVerticeElementData(normals, VertexMesh.MESH_NORMAL0);
  27844. else
  27845. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  27846. }
  27847. setNormals(normals) {
  27848. if (this._isReadable)
  27849. this._setVerticeElementData(normals, VertexMesh.MESH_NORMAL0);
  27850. else
  27851. throw "Mesh:setNormals() need must be true or use setVertices().";
  27852. }
  27853. getTangents(tangents) {
  27854. if (this._isReadable)
  27855. this._getVerticeElementData(tangents, VertexMesh.MESH_TANGENT0);
  27856. else
  27857. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  27858. }
  27859. setTangents(tangents) {
  27860. if (this._isReadable)
  27861. this._setVerticeElementData(tangents, VertexMesh.MESH_TANGENT0);
  27862. else
  27863. throw "Mesh:setTangents() need isReadable must be true or use setVertices().";
  27864. }
  27865. getBoneWeights(boneWeights) {
  27866. if (this._isReadable)
  27867. this._getVerticeElementData(boneWeights, VertexMesh.MESH_BLENDWEIGHT0);
  27868. else
  27869. throw "Mesh:can't get boneWeights on mesh,isReadable must be true.";
  27870. }
  27871. setBoneWeights(boneWeights) {
  27872. if (this._isReadable)
  27873. this._setVerticeElementData(boneWeights, VertexMesh.MESH_BLENDWEIGHT0);
  27874. else
  27875. throw "Mesh:setBoneWeights() need isReadable must be true or use setVertices().";
  27876. }
  27877. getBoneIndices(boneIndices) {
  27878. if (this._isReadable)
  27879. this._getVerticeElementData(boneIndices, VertexMesh.MESH_BLENDINDICES0);
  27880. else
  27881. throw "Mesh:can't get boneIndices on mesh,isReadable must be true.";
  27882. }
  27883. setBoneIndices(boneIndices) {
  27884. if (this._isReadable)
  27885. this._setVerticeElementData(boneIndices, VertexMesh.MESH_BLENDINDICES0);
  27886. else
  27887. throw "Mesh:setBoneIndices() need isReadable must be true or use setVertices().";
  27888. }
  27889. markAsUnreadbale() {
  27890. this._uploadVerticesData();
  27891. this._vertexBuffer.markAsUnreadbale();
  27892. this._isReadable = false;
  27893. }
  27894. getVertexDeclaration() {
  27895. return this._vertexBuffer._vertexDeclaration;
  27896. }
  27897. getVertices() {
  27898. if (this._isReadable)
  27899. return this._vertexBuffer.getUint8Data().buffer.slice(0);
  27900. else
  27901. throw "Mesh:can't get vertices on mesh,isReadable must be true.";
  27902. }
  27903. setVertices(vertices) {
  27904. this._vertexBuffer.setData(vertices);
  27905. this._needUpdateBounds = true;
  27906. }
  27907. getIndices() {
  27908. if (this._isReadable)
  27909. return this._indexBuffer.getData().slice();
  27910. else
  27911. throw "Mesh:can't get indices on subMesh,mesh's isReadable must be true.";
  27912. }
  27913. setIndices(indices) {
  27914. var format;
  27915. if (indices instanceof Uint32Array)
  27916. format = exports.IndexFormat.UInt32;
  27917. else if (indices instanceof Uint16Array)
  27918. format = exports.IndexFormat.UInt16;
  27919. else if (indices instanceof Uint8Array)
  27920. format = exports.IndexFormat.UInt8;
  27921. var indexBuffer = this._indexBuffer;
  27922. if (this._indexFormat !== format || indexBuffer.indexCount !== indices.length) {
  27923. indexBuffer.destroy();
  27924. this._indexBuffer = indexBuffer = new IndexBuffer3D(format, indices.length, Laya.LayaGL.instance.STATIC_DRAW, this._isReadable);
  27925. }
  27926. indexBuffer.setData(indices);
  27927. this._indexFormat = format;
  27928. }
  27929. calculateBounds() {
  27930. if (this._isReadable) {
  27931. if (this._needUpdateBounds) {
  27932. var min = this._tempVector30;
  27933. var max = this._tempVector31;
  27934. min.x = min.y = min.z = Number.MAX_VALUE;
  27935. max.x = max.y = max.z = -Number.MAX_VALUE;
  27936. var vertexBuffer = this._vertexBuffer;
  27937. var positionElement = this._getPositionElement(vertexBuffer);
  27938. var verticesData = vertexBuffer.getFloat32Data();
  27939. var floatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  27940. var posOffset = positionElement._offset / 4;
  27941. for (var j = 0, m = verticesData.length; j < m; j += floatCount) {
  27942. var ofset = j + posOffset;
  27943. var pX = verticesData[ofset];
  27944. var pY = verticesData[ofset + 1];
  27945. var pZ = verticesData[ofset + 2];
  27946. min.x = Math.min(min.x, pX);
  27947. min.y = Math.min(min.y, pY);
  27948. min.z = Math.min(min.z, pZ);
  27949. max.x = Math.max(max.x, pX);
  27950. max.y = Math.max(max.y, pY);
  27951. max.z = Math.max(max.z, pZ);
  27952. }
  27953. this._bounds.setMin(min);
  27954. this._bounds.setMax(max);
  27955. this._needUpdateBounds = false;
  27956. }
  27957. }
  27958. else {
  27959. throw "Mesh:can't calculate bounds on subMesh,mesh's isReadable must be true.";
  27960. }
  27961. }
  27962. cloneTo(destObject) {
  27963. var destMesh = destObject;
  27964. var vb = this._vertexBuffer;
  27965. var destVB = new VertexBuffer3D(vb._byteLength, vb.bufferUsage, vb.canRead);
  27966. destVB.vertexDeclaration = vb.vertexDeclaration;
  27967. destVB.setData(vb.getUint8Data().slice().buffer);
  27968. destMesh._vertexBuffer = destVB;
  27969. destMesh._vertexCount = this._vertexCount;
  27970. var ib = this._indexBuffer;
  27971. var destIB = new IndexBuffer3D(exports.IndexFormat.UInt16, ib.indexCount, ib.bufferUsage, ib.canRead);
  27972. destIB.setData(ib.getData().slice());
  27973. destMesh._indexBuffer = destIB;
  27974. destMesh._setBuffer(destMesh._vertexBuffer, destIB);
  27975. destMesh._setCPUMemory(this.cpuMemory);
  27976. destMesh._setGPUMemory(this.gpuMemory);
  27977. var i;
  27978. var boneNames = this._boneNames;
  27979. var destBoneNames = destMesh._boneNames = [];
  27980. for (i = 0; i < boneNames.length; i++)
  27981. destBoneNames[i] = boneNames[i];
  27982. var inverseBindPoses = this._inverseBindPoses;
  27983. var destInverseBindPoses = destMesh._inverseBindPoses = [];
  27984. for (i = 0; i < inverseBindPoses.length; i++)
  27985. destInverseBindPoses[i] = inverseBindPoses[i];
  27986. destMesh._bindPoseIndices = new Uint16Array(this._bindPoseIndices);
  27987. for (i = 0; i < this._skinDataPathMarks.length; i++)
  27988. destMesh._skinDataPathMarks[i] = this._skinDataPathMarks[i].slice();
  27989. for (i = 0; i < this.subMeshCount; i++) {
  27990. var subMesh = this._subMeshes[i];
  27991. var subIndexBufferStart = subMesh._subIndexBufferStart;
  27992. var subIndexBufferCount = subMesh._subIndexBufferCount;
  27993. var boneIndicesList = subMesh._boneIndicesList;
  27994. var destSubmesh = new SubMesh(destMesh);
  27995. destSubmesh._subIndexBufferStart.length = subIndexBufferStart.length;
  27996. destSubmesh._subIndexBufferCount.length = subIndexBufferCount.length;
  27997. destSubmesh._boneIndicesList.length = boneIndicesList.length;
  27998. for (var j = 0; j < subIndexBufferStart.length; j++)
  27999. destSubmesh._subIndexBufferStart[j] = subIndexBufferStart[j];
  28000. for (j = 0; j < subIndexBufferCount.length; j++)
  28001. destSubmesh._subIndexBufferCount[j] = subIndexBufferCount[j];
  28002. for (j = 0; j < boneIndicesList.length; j++)
  28003. destSubmesh._boneIndicesList[j] = new Uint16Array(boneIndicesList[j]);
  28004. destSubmesh._indexBuffer = destIB;
  28005. destSubmesh._indexStart = subMesh._indexStart;
  28006. destSubmesh._indexCount = subMesh._indexCount;
  28007. destSubmesh._indices = new Uint16Array(destIB.getData().buffer, subMesh._indexStart * 2, subMesh._indexCount);
  28008. var vertexBuffer = destMesh._vertexBuffer;
  28009. destSubmesh._vertexBuffer = vertexBuffer;
  28010. destMesh._subMeshes.push(destSubmesh);
  28011. }
  28012. destMesh._setSubMeshes(destMesh._subMeshes);
  28013. }
  28014. clone() {
  28015. var dest = new Mesh();
  28016. this.cloneTo(dest);
  28017. return dest;
  28018. }
  28019. }
  28020. Mesh.MESH = "MESH";
  28021. class PrimitiveMesh {
  28022. static __init__() {
  28023. }
  28024. static _createMesh(vertexDeclaration, vertices, indices) {
  28025. var gl = Laya.LayaGL.instance;
  28026. var mesh = new Mesh();
  28027. var subMesh = new SubMesh(mesh);
  28028. var vertexBuffer = new VertexBuffer3D(vertices.length * 4, gl.STATIC_DRAW, true);
  28029. vertexBuffer.vertexDeclaration = vertexDeclaration;
  28030. vertexBuffer.setData(vertices.buffer);
  28031. mesh._vertexBuffer = vertexBuffer;
  28032. mesh._vertexCount = vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  28033. var indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indices.length, gl.STATIC_DRAW, true);
  28034. indexBuffer.setData(indices);
  28035. mesh._indexBuffer = indexBuffer;
  28036. mesh._setBuffer(vertexBuffer, indexBuffer);
  28037. subMesh._vertexBuffer = vertexBuffer;
  28038. subMesh._indexBuffer = indexBuffer;
  28039. subMesh._setIndexRange(0, indexBuffer.indexCount);
  28040. var subIndexBufferStart = subMesh._subIndexBufferStart;
  28041. var subIndexBufferCount = subMesh._subIndexBufferCount;
  28042. var boneIndicesList = subMesh._boneIndicesList;
  28043. subIndexBufferStart.length = 1;
  28044. subIndexBufferCount.length = 1;
  28045. boneIndicesList.length = 1;
  28046. subIndexBufferStart[0] = 0;
  28047. subIndexBufferCount[0] = indexBuffer.indexCount;
  28048. var subMeshes = [];
  28049. subMeshes.push(subMesh);
  28050. mesh._setSubMeshes(subMeshes);
  28051. var memorySize = vertexBuffer._byteLength + indexBuffer._byteLength;
  28052. mesh._setCPUMemory(memorySize);
  28053. mesh._setGPUMemory(memorySize);
  28054. return mesh;
  28055. }
  28056. static createBox(long = 1, height = 1, width = 1) {
  28057. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  28058. var halfLong = long / 2;
  28059. var halfHeight = height / 2;
  28060. var halfWidth = width / 2;
  28061. var vertices = new Float32Array([
  28062. -halfLong, halfHeight, -halfWidth, 0, 1, 0, 0, 0, halfLong, halfHeight, -halfWidth, 0, 1, 0, 1, 0, halfLong, halfHeight, halfWidth, 0, 1, 0, 1, 1, -halfLong, halfHeight, halfWidth, 0, 1, 0, 0, 1,
  28063. -halfLong, -halfHeight, -halfWidth, 0, -1, 0, 0, 1, halfLong, -halfHeight, -halfWidth, 0, -1, 0, 1, 1, halfLong, -halfHeight, halfWidth, 0, -1, 0, 1, 0, -halfLong, -halfHeight, halfWidth, 0, -1, 0, 0, 0,
  28064. -halfLong, halfHeight, -halfWidth, -1, 0, 0, 0, 0, -halfLong, halfHeight, halfWidth, -1, 0, 0, 1, 0, -halfLong, -halfHeight, halfWidth, -1, 0, 0, 1, 1, -halfLong, -halfHeight, -halfWidth, -1, 0, 0, 0, 1,
  28065. halfLong, halfHeight, -halfWidth, 1, 0, 0, 1, 0, halfLong, halfHeight, halfWidth, 1, 0, 0, 0, 0, halfLong, -halfHeight, halfWidth, 1, 0, 0, 0, 1, halfLong, -halfHeight, -halfWidth, 1, 0, 0, 1, 1,
  28066. -halfLong, halfHeight, halfWidth, 0, 0, 1, 0, 0, halfLong, halfHeight, halfWidth, 0, 0, 1, 1, 0, halfLong, -halfHeight, halfWidth, 0, 0, 1, 1, 1, -halfLong, -halfHeight, halfWidth, 0, 0, 1, 0, 1,
  28067. -halfLong, halfHeight, -halfWidth, 0, 0, -1, 1, 0, halfLong, halfHeight, -halfWidth, 0, 0, -1, 0, 0, halfLong, -halfHeight, -halfWidth, 0, 0, -1, 0, 1, -halfLong, -halfHeight, -halfWidth, 0, 0, -1, 1, 1
  28068. ]);
  28069. var indices = new Uint16Array([
  28070. 0, 1, 2, 2, 3, 0,
  28071. 4, 7, 6, 6, 5, 4,
  28072. 8, 9, 10, 10, 11, 8,
  28073. 12, 15, 14, 14, 13, 12,
  28074. 16, 17, 18, 18, 19, 16,
  28075. 20, 23, 22, 22, 21, 20
  28076. ]);
  28077. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  28078. }
  28079. static createCapsule(radius = 0.5, height = 2, stacks = 16, slices = 32) {
  28080. var vertexCount = (stacks + 1) * (slices + 1) * 2 + (slices + 1) * 2;
  28081. var indexCount = (3 * stacks * (slices + 1)) * 2 * 2 + 2 * slices * 3;
  28082. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  28083. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  28084. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  28085. var indices = new Uint16Array(indexCount);
  28086. var stackAngle = (Math.PI / 2.0) / stacks;
  28087. var sliceAngle = (Math.PI * 2.0) / slices;
  28088. var hcHeight = height / 2 - radius;
  28089. var posX = 0;
  28090. var posY = 0;
  28091. var posZ = 0;
  28092. var vc = 0;
  28093. var ic = 0;
  28094. var verticeCount = 0;
  28095. var stack, slice;
  28096. for (stack = 0; stack <= stacks; stack++) {
  28097. for (slice = 0; slice <= slices; slice++) {
  28098. posX = radius * Math.cos(stack * stackAngle) * Math.cos(slice * sliceAngle + Math.PI);
  28099. posY = radius * Math.sin(stack * stackAngle);
  28100. posZ = radius * Math.cos(stack * stackAngle) * Math.sin(slice * sliceAngle + Math.PI);
  28101. vertices[vc++] = posX;
  28102. vertices[vc++] = posY + hcHeight;
  28103. vertices[vc++] = posZ;
  28104. vertices[vc++] = posX;
  28105. vertices[vc++] = posY;
  28106. vertices[vc++] = posZ;
  28107. vertices[vc++] = 1 - slice / slices;
  28108. vertices[vc++] = (1 - stack / stacks) * ((Math.PI * radius / 2) / (height + Math.PI * radius));
  28109. if (stack < stacks) {
  28110. indices[ic++] = (stack * (slices + 1)) + slice + (slices + 1);
  28111. indices[ic++] = (stack * (slices + 1)) + slice;
  28112. indices[ic++] = (stack * (slices + 1)) + slice + 1;
  28113. indices[ic++] = (stack * (slices + 1)) + slice + (slices);
  28114. indices[ic++] = (stack * (slices + 1)) + slice;
  28115. indices[ic++] = (stack * (slices + 1)) + slice + (slices + 1);
  28116. }
  28117. }
  28118. }
  28119. verticeCount += (stacks + 1) * (slices + 1);
  28120. for (stack = 0; stack <= stacks; stack++) {
  28121. for (slice = 0; slice <= slices; slice++) {
  28122. posX = radius * Math.cos(stack * stackAngle) * Math.cos(slice * sliceAngle + Math.PI);
  28123. posY = radius * Math.sin(-stack * stackAngle);
  28124. posZ = radius * Math.cos(stack * stackAngle) * Math.sin(slice * sliceAngle + Math.PI);
  28125. vertices[vc++] = posX;
  28126. vertices[vc++] = posY - hcHeight;
  28127. vertices[vc++] = posZ;
  28128. vertices[vc++] = posX;
  28129. vertices[vc++] = posY;
  28130. vertices[vc++] = posZ;
  28131. vertices[vc++] = 1 - slice / slices;
  28132. vertices[vc++] = ((stack / stacks) * (Math.PI * radius / 2) + (height + Math.PI * radius / 2)) / (height + Math.PI * radius);
  28133. if (stack < stacks) {
  28134. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice;
  28135. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices + 1);
  28136. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + 1;
  28137. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice;
  28138. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices);
  28139. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices + 1);
  28140. }
  28141. }
  28142. }
  28143. verticeCount += (stacks + 1) * (slices + 1);
  28144. for (slice = 0; slice <= slices; slice++) {
  28145. posX = radius * Math.cos(slice * sliceAngle + Math.PI);
  28146. posY = hcHeight;
  28147. posZ = radius * Math.sin(slice * sliceAngle + Math.PI);
  28148. vertices[vc++] = posX;
  28149. vertices[vc + (slices + 1) * 8 - 1] = posX;
  28150. vertices[vc++] = posY;
  28151. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  28152. vertices[vc++] = posZ;
  28153. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  28154. vertices[vc++] = posX;
  28155. vertices[vc + (slices + 1) * 8 - 1] = posX;
  28156. vertices[vc++] = 0;
  28157. vertices[vc + (slices + 1) * 8 - 1] = 0;
  28158. vertices[vc++] = posZ;
  28159. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  28160. vertices[vc++] = 1 - slice * 1 / slices;
  28161. vertices[vc + (slices + 1) * 8 - 1] = 1 - slice * 1 / slices;
  28162. vertices[vc++] = (Math.PI * radius / 2) / (height + Math.PI * radius);
  28163. vertices[vc + (slices + 1) * 8 - 1] = (Math.PI * radius / 2 + height) / (height + Math.PI * radius);
  28164. }
  28165. for (slice = 0; slice < slices; slice++) {
  28166. indices[ic++] = slice + verticeCount + (slices + 1);
  28167. indices[ic++] = slice + verticeCount + 1;
  28168. indices[ic++] = slice + verticeCount;
  28169. indices[ic++] = slice + verticeCount + (slices + 1);
  28170. indices[ic++] = slice + verticeCount + (slices + 1) + 1;
  28171. indices[ic++] = slice + verticeCount + 1;
  28172. }
  28173. verticeCount += 2 * (slices + 1);
  28174. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  28175. }
  28176. static createCone(radius = 0.5, height = 1, slices = 32) {
  28177. var vertexCount = (slices + 1 + 1) + (slices + 1) * 2;
  28178. var indexCount = 6 * slices + 3 * slices;
  28179. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  28180. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  28181. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  28182. var indices = new Uint16Array(indexCount);
  28183. var sliceAngle = (Math.PI * 2.0) / slices;
  28184. var halfHeight = height / 2;
  28185. var curAngle = 0;
  28186. var verticeCount = 0;
  28187. var posX = 0;
  28188. var posY = 0;
  28189. var posZ = 0;
  28190. var normal = new Vector3();
  28191. var downV3 = new Vector3(0, -1, 0);
  28192. var upPoint = new Vector3(0, halfHeight, 0);
  28193. var downPoint = new Vector3();
  28194. var v3 = new Vector3();
  28195. var q4 = new Quaternion();
  28196. var rotateAxis = new Vector3();
  28197. var rotateRadius;
  28198. var vc = 0;
  28199. var ic = 0;
  28200. for (var rv = 0; rv <= slices; rv++) {
  28201. curAngle = rv * sliceAngle;
  28202. posX = Math.cos(curAngle + Math.PI) * radius;
  28203. posY = halfHeight;
  28204. posZ = Math.sin(curAngle + Math.PI) * radius;
  28205. vertices[vc++] = 0;
  28206. vertices[vc + (slices + 1) * 8 - 1] = posX;
  28207. vertices[vc++] = posY;
  28208. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  28209. vertices[vc++] = 0;
  28210. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  28211. normal.x = posX;
  28212. normal.y = 0;
  28213. normal.z = posZ;
  28214. downPoint.x = posX;
  28215. downPoint.y = -posY;
  28216. downPoint.z = posZ;
  28217. Vector3.subtract(downPoint, upPoint, v3);
  28218. Vector3.normalize(v3, v3);
  28219. rotateRadius = Math.acos(Vector3.dot(downV3, v3));
  28220. Vector3.cross(downV3, v3, rotateAxis);
  28221. Vector3.normalize(rotateAxis, rotateAxis);
  28222. Quaternion.createFromAxisAngle(rotateAxis, rotateRadius, q4);
  28223. Vector3.normalize(normal, normal);
  28224. Vector3.transformQuat(normal, q4, normal);
  28225. Vector3.normalize(normal, normal);
  28226. vertices[vc++] = normal.x;
  28227. vertices[vc + (slices + 1) * 8 - 1] = normal.x;
  28228. vertices[vc++] = normal.y;
  28229. vertices[vc + (slices + 1) * 8 - 1] = normal.y;
  28230. vertices[vc++] = normal.z;
  28231. vertices[vc + (slices + 1) * 8 - 1] = normal.z;
  28232. vertices[vc++] = 1 - rv * 1 / slices;
  28233. vertices[vc + (slices + 1) * 8 - 1] = 1 - rv * 1 / slices;
  28234. vertices[vc++] = 0;
  28235. vertices[vc + (slices + 1) * 8 - 1] = 1;
  28236. }
  28237. vc += (slices + 1) * 8;
  28238. for (var ri = 0; ri < slices; ri++) {
  28239. indices[ic++] = ri + verticeCount + (slices + 1);
  28240. indices[ic++] = ri + verticeCount + 1;
  28241. indices[ic++] = ri + verticeCount;
  28242. indices[ic++] = ri + verticeCount + (slices + 1);
  28243. indices[ic++] = ri + verticeCount + (slices + 1) + 1;
  28244. indices[ic++] = ri + verticeCount + 1;
  28245. }
  28246. verticeCount += 2 * (slices + 1);
  28247. for (var bv = 0; bv <= slices; bv++) {
  28248. if (bv === 0) {
  28249. vertices[vc++] = 0;
  28250. vertices[vc++] = -halfHeight;
  28251. vertices[vc++] = 0;
  28252. vertices[vc++] = 0;
  28253. vertices[vc++] = -1;
  28254. vertices[vc++] = 0;
  28255. vertices[vc++] = 0.5;
  28256. vertices[vc++] = 0.5;
  28257. }
  28258. curAngle = bv * sliceAngle;
  28259. posX = Math.cos(curAngle + Math.PI) * radius;
  28260. posY = -halfHeight;
  28261. posZ = Math.sin(curAngle + Math.PI) * radius;
  28262. vertices[vc++] = posX;
  28263. vertices[vc++] = posY;
  28264. vertices[vc++] = posZ;
  28265. vertices[vc++] = 0;
  28266. vertices[vc++] = -1;
  28267. vertices[vc++] = 0;
  28268. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  28269. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  28270. }
  28271. for (var bi = 0; bi < slices; bi++) {
  28272. indices[ic++] = 0 + verticeCount;
  28273. indices[ic++] = bi + 2 + verticeCount;
  28274. indices[ic++] = bi + 1 + verticeCount;
  28275. }
  28276. verticeCount += slices + 1 + 1;
  28277. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  28278. }
  28279. static createCylinder(radius = 0.5, height = 2, slices = 32) {
  28280. var vertexCount = (slices + 1 + 1) + (slices + 1) * 2 + (slices + 1 + 1);
  28281. var indexCount = 3 * slices + 6 * slices + 3 * slices;
  28282. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  28283. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  28284. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  28285. var indices = new Uint16Array(indexCount);
  28286. var sliceAngle = (Math.PI * 2.0) / slices;
  28287. var halfHeight = height / 2;
  28288. var curAngle = 0;
  28289. var verticeCount = 0;
  28290. var posX = 0;
  28291. var posY = 0;
  28292. var posZ = 0;
  28293. var vc = 0;
  28294. var ic = 0;
  28295. for (var tv = 0; tv <= slices; tv++) {
  28296. if (tv === 0) {
  28297. vertices[vc++] = 0;
  28298. vertices[vc++] = halfHeight;
  28299. vertices[vc++] = 0;
  28300. vertices[vc++] = 0;
  28301. vertices[vc++] = 1;
  28302. vertices[vc++] = 0;
  28303. vertices[vc++] = 0.5;
  28304. vertices[vc++] = 0.5;
  28305. }
  28306. curAngle = tv * sliceAngle;
  28307. posX = Math.cos(curAngle) * radius;
  28308. posY = halfHeight;
  28309. posZ = Math.sin(curAngle) * radius;
  28310. vertices[vc++] = posX;
  28311. vertices[vc++] = posY;
  28312. vertices[vc++] = posZ;
  28313. vertices[vc++] = 0;
  28314. vertices[vc++] = 1;
  28315. vertices[vc++] = 0;
  28316. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  28317. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  28318. }
  28319. for (var ti = 0; ti < slices; ti++) {
  28320. indices[ic++] = 0;
  28321. indices[ic++] = ti + 1;
  28322. indices[ic++] = ti + 2;
  28323. }
  28324. verticeCount += slices + 1 + 1;
  28325. for (var rv = 0; rv <= slices; rv++) {
  28326. curAngle = rv * sliceAngle;
  28327. posX = Math.cos(curAngle + Math.PI) * radius;
  28328. posY = halfHeight;
  28329. posZ = Math.sin(curAngle + Math.PI) * radius;
  28330. vertices[vc++] = posX;
  28331. vertices[vc + (slices + 1) * 8 - 1] = posX;
  28332. vertices[vc++] = posY;
  28333. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  28334. vertices[vc++] = posZ;
  28335. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  28336. vertices[vc++] = posX;
  28337. vertices[vc + (slices + 1) * 8 - 1] = posX;
  28338. vertices[vc++] = 0;
  28339. vertices[vc + (slices + 1) * 8 - 1] = 0;
  28340. vertices[vc++] = posZ;
  28341. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  28342. vertices[vc++] = 1 - rv * 1 / slices;
  28343. vertices[vc + (slices + 1) * 8 - 1] = 1 - rv * 1 / slices;
  28344. vertices[vc++] = 0;
  28345. vertices[vc + (slices + 1) * 8 - 1] = 1;
  28346. }
  28347. vc += (slices + 1) * 8;
  28348. for (var ri = 0; ri < slices; ri++) {
  28349. indices[ic++] = ri + verticeCount + (slices + 1);
  28350. indices[ic++] = ri + verticeCount + 1;
  28351. indices[ic++] = ri + verticeCount;
  28352. indices[ic++] = ri + verticeCount + (slices + 1);
  28353. indices[ic++] = ri + verticeCount + (slices + 1) + 1;
  28354. indices[ic++] = ri + verticeCount + 1;
  28355. }
  28356. verticeCount += 2 * (slices + 1);
  28357. for (var bv = 0; bv <= slices; bv++) {
  28358. if (bv === 0) {
  28359. vertices[vc++] = 0;
  28360. vertices[vc++] = -halfHeight;
  28361. vertices[vc++] = 0;
  28362. vertices[vc++] = 0;
  28363. vertices[vc++] = -1;
  28364. vertices[vc++] = 0;
  28365. vertices[vc++] = 0.5;
  28366. vertices[vc++] = 0.5;
  28367. }
  28368. curAngle = bv * sliceAngle;
  28369. posX = Math.cos(curAngle + Math.PI) * radius;
  28370. posY = -halfHeight;
  28371. posZ = Math.sin(curAngle + Math.PI) * radius;
  28372. vertices[vc++] = posX;
  28373. vertices[vc++] = posY;
  28374. vertices[vc++] = posZ;
  28375. vertices[vc++] = 0;
  28376. vertices[vc++] = -1;
  28377. vertices[vc++] = 0;
  28378. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  28379. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  28380. }
  28381. for (var bi = 0; bi < slices; bi++) {
  28382. indices[ic++] = 0 + verticeCount;
  28383. indices[ic++] = bi + 2 + verticeCount;
  28384. indices[ic++] = bi + 1 + verticeCount;
  28385. }
  28386. verticeCount += slices + 1 + 1;
  28387. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  28388. }
  28389. static createPlane(long = 10, width = 10, stacks = 10, slices = 10) {
  28390. var vertexCount = (stacks + 1) * (slices + 1);
  28391. var indexCount = stacks * slices * 2 * 3;
  28392. var indices = new Uint16Array(indexCount);
  28393. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  28394. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  28395. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  28396. var halfLong = long / 2;
  28397. var halfWidth = width / 2;
  28398. var stacksLong = long / stacks;
  28399. var slicesWidth = width / slices;
  28400. var verticeCount = 0;
  28401. for (var i = 0; i <= slices; i++) {
  28402. for (var j = 0; j <= stacks; j++) {
  28403. vertices[verticeCount++] = j * stacksLong - halfLong;
  28404. vertices[verticeCount++] = 0;
  28405. vertices[verticeCount++] = i * slicesWidth - halfWidth;
  28406. vertices[verticeCount++] = 0;
  28407. vertices[verticeCount++] = 1;
  28408. vertices[verticeCount++] = 0;
  28409. vertices[verticeCount++] = j * 1 / stacks;
  28410. vertices[verticeCount++] = i * 1 / slices;
  28411. }
  28412. }
  28413. var indiceIndex = 0;
  28414. for (i = 0; i < slices; i++) {
  28415. for (j = 0; j < stacks; j++) {
  28416. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j;
  28417. indices[indiceIndex++] = i * (stacks + 1) + j;
  28418. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j + 1;
  28419. indices[indiceIndex++] = i * (stacks + 1) + j;
  28420. indices[indiceIndex++] = i * (stacks + 1) + j + 1;
  28421. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j + 1;
  28422. }
  28423. }
  28424. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  28425. }
  28426. static createQuad(long = 1, width = 1) {
  28427. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  28428. var halfLong = long / 2;
  28429. var halfWidth = width / 2;
  28430. var vertices = new Float32Array([-halfLong, halfWidth, 0, 0, 0, 1, 0, 0, halfLong, halfWidth, 0, 0, 0, 1, 1, 0, -halfLong, -halfWidth, 0, 0, 0, 1, 0, 1, halfLong, -halfWidth, 0, 0, 0, 1, 1, 1]);
  28431. var indices = new Uint16Array([0, 1, 2, 3, 2, 1]);
  28432. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  28433. }
  28434. static createSphere(radius = 0.5, stacks = 32, slices = 32) {
  28435. var vertexCount = (stacks + 1) * (slices + 1);
  28436. var indexCount = (3 * stacks * (slices + 1)) * 2;
  28437. var indices = new Uint16Array(indexCount);
  28438. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  28439. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  28440. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  28441. var stackAngle = Math.PI / stacks;
  28442. var sliceAngle = (Math.PI * 2.0) / slices;
  28443. var vertexIndex = 0;
  28444. vertexCount = 0;
  28445. indexCount = 0;
  28446. for (var stack = 0; stack < (stacks + 1); stack++) {
  28447. var r = Math.sin(stack * stackAngle);
  28448. var y = Math.cos(stack * stackAngle);
  28449. for (var slice = 0; slice < (slices + 1); slice++) {
  28450. var x = r * Math.sin(slice * sliceAngle + Math.PI * 1 / 2);
  28451. var z = r * Math.cos(slice * sliceAngle + Math.PI * 1 / 2);
  28452. vertices[vertexCount + 0] = x * radius;
  28453. vertices[vertexCount + 1] = y * radius;
  28454. vertices[vertexCount + 2] = z * radius;
  28455. vertices[vertexCount + 3] = x;
  28456. vertices[vertexCount + 4] = y;
  28457. vertices[vertexCount + 5] = z;
  28458. vertices[vertexCount + 6] = slice / slices;
  28459. vertices[vertexCount + 7] = stack / stacks;
  28460. vertexCount += vertexFloatStride;
  28461. if (stack != (stacks - 1)) {
  28462. indices[indexCount++] = vertexIndex + (slices + 1);
  28463. indices[indexCount++] = vertexIndex;
  28464. indices[indexCount++] = vertexIndex + 1;
  28465. indices[indexCount++] = vertexIndex + (slices);
  28466. indices[indexCount++] = vertexIndex;
  28467. indices[indexCount++] = vertexIndex + (slices + 1);
  28468. vertexIndex++;
  28469. }
  28470. }
  28471. }
  28472. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  28473. }
  28474. }
  28475. class TextureCube extends Laya.BaseTexture {
  28476. constructor(size, format = Laya.TextureFormat.R8G8B8, mipmap = false) {
  28477. super(format, mipmap);
  28478. this._glTextureType = Laya.LayaGL.instance.TEXTURE_CUBE_MAP;
  28479. this._width = size;
  28480. this._height = size;
  28481. var gl = Laya.LayaGL.instance;
  28482. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  28483. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  28484. this._setFilterMode(this._filterMode);
  28485. this._setAnisotropy(this._anisoLevel);
  28486. if (this._mipmap) {
  28487. this._mipmapCount = Math.ceil(Math.log2(size));
  28488. for (var i = 0; i < this._mipmapCount; i++)
  28489. this._setPixels([], i, Math.max(size >> i, 1), Math.max(size >> i, 1));
  28490. this._setGPUMemory(size * size * 4 * (1 + 1 / 3) * 6);
  28491. }
  28492. else {
  28493. this._mipmapCount = 1;
  28494. this._setGPUMemory(size * size * 4 * 6);
  28495. }
  28496. }
  28497. static __init__() {
  28498. var pixels = new Uint8Array(3);
  28499. pixels[0] = 128;
  28500. pixels[1] = 128;
  28501. pixels[2] = 128;
  28502. TextureCube.grayTexture = new TextureCube(1, Laya.TextureFormat.R8G8B8, false);
  28503. TextureCube.grayTexture.setSixSidePixels([pixels, pixels, pixels, pixels, pixels, pixels]);
  28504. TextureCube.grayTexture.lock = true;
  28505. }
  28506. static _parse(data, propertyParams = null, constructParams = null) {
  28507. var texture = constructParams ? new TextureCube(0, constructParams[0], constructParams[1]) : new TextureCube(0);
  28508. texture.setSixSideImageSources(data);
  28509. return texture;
  28510. }
  28511. static load(url, complete) {
  28512. Laya.ILaya.loader.create(url, complete, null, TextureCube.TEXTURECUBE);
  28513. }
  28514. get defaulteTexture() {
  28515. return TextureCube.grayTexture;
  28516. }
  28517. _setPixels(pixels, miplevel, width, height) {
  28518. var gl = Laya.LayaGL.instance;
  28519. var glFormat = this._getGLFormat();
  28520. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  28521. if (this.format === Laya.TextureFormat.R8G8B8) {
  28522. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  28523. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[0]);
  28524. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[1]);
  28525. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[2]);
  28526. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[3]);
  28527. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[4]);
  28528. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[5]);
  28529. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
  28530. }
  28531. else {
  28532. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[0]);
  28533. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[1]);
  28534. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[2]);
  28535. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[3]);
  28536. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[4]);
  28537. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[5]);
  28538. }
  28539. }
  28540. setSixSideImageSources(source, premultiplyAlpha = false) {
  28541. var width;
  28542. var height;
  28543. for (var i = 0; i < 6; i++) {
  28544. var img = source[i];
  28545. if (!img) {
  28546. console.log("TextureCube: image Source can't be null.");
  28547. return;
  28548. }
  28549. var nextWidth = img.width;
  28550. var nextHeight = img.height;
  28551. if (i > 0) {
  28552. if (width !== nextWidth) {
  28553. console.log("TextureCube: each side image's width and height must same.");
  28554. return;
  28555. }
  28556. }
  28557. width = nextWidth;
  28558. height = nextHeight;
  28559. if (width !== height) {
  28560. console.log("TextureCube: each side image's width and height must same.");
  28561. return;
  28562. }
  28563. }
  28564. this._width = width;
  28565. this._height = height;
  28566. var gl = Laya.LayaGL.instance;
  28567. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  28568. var glFormat = this._getGLFormat();
  28569. if (!Laya.Render.isConchApp) {
  28570. (premultiplyAlpha) && (gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true));
  28571. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[0]);
  28572. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[1]);
  28573. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[2]);
  28574. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[3]);
  28575. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[4]);
  28576. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[5]);
  28577. (premultiplyAlpha) && (gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false));
  28578. }
  28579. else {
  28580. if (premultiplyAlpha == true) {
  28581. for (var j = 0; j < 6; j++)
  28582. source[j].setPremultiplyAlpha(premultiplyAlpha);
  28583. }
  28584. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[0]);
  28585. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[1]);
  28586. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[2]);
  28587. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[3]);
  28588. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[4]);
  28589. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[5]);
  28590. }
  28591. if (this._mipmap && this._isPot(width) && this._isPot(height)) {
  28592. gl.generateMipmap(this._glTextureType);
  28593. this._setGPUMemory(width * height * 4 * (1 + 1 / 3) * 6);
  28594. }
  28595. else {
  28596. this._setGPUMemory(width * height * 4 * 6);
  28597. }
  28598. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  28599. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  28600. this._setFilterMode(this._filterMode);
  28601. this._readyed = true;
  28602. this._activeResource();
  28603. }
  28604. setSixSidePixels(pixels, miplevel = 0) {
  28605. if (!pixels)
  28606. throw new Error("TextureCube:pixels can't be null.");
  28607. var width = Math.max(this._width >> miplevel, 1);
  28608. var height = Math.max(this._height >> miplevel, 1);
  28609. var pixelsCount = width * height * this._getFormatByteCount();
  28610. if (pixels[0].length < pixelsCount)
  28611. throw "TextureCube:pixels length should at least " + pixelsCount + ".";
  28612. this._setPixels(pixels, miplevel, width, height);
  28613. if (miplevel === 0) {
  28614. var gl = Laya.LayaGL.instance;
  28615. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  28616. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  28617. }
  28618. this._readyed = true;
  28619. this._activeResource();
  28620. }
  28621. _recoverResource() {
  28622. }
  28623. }
  28624. TextureCube.TEXTURECUBE = "TEXTURECUBE";
  28625. var BlitScreenPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\nuniform sampler2D u_MainTex;\r\nvarying vec2 v_Texcoord0;\r\n\r\nvoid main() {\r\n\tgl_FragColor = texture2D(u_MainTex, v_Texcoord0);\r\n}\r\n\r\n";
  28626. var BlitScreenVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_PositionTexcoord;\r\nuniform vec4 u_OffsetScale;\r\nvarying vec2 v_Texcoord0;\r\n\r\nvoid main() {\t\r\n\tgl_Position = vec4(u_OffsetScale.x*2.0-1.0+(a_PositionTexcoord.x+1.0)*u_OffsetScale.z,(1.0-((u_OffsetScale.y*2.0-1.0+(-a_PositionTexcoord.y+1.0)*u_OffsetScale.w)+1.0)/2.0)*2.0-1.0, 0.0, 1.0);\t\r\n\tv_Texcoord0 = a_PositionTexcoord.zw;\r\n\tgl_Position = remapGLPositionZ(gl_Position);\r\n}";
  28627. var EffectPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#ifdef COLOR\r\n\tvarying vec4 v_Color;\r\n#endif\r\nvarying vec2 v_Texcoord0;\r\n\r\n#ifdef MAINTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n#endif\r\n\r\nuniform vec4 u_AlbedoColor;\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\t#ifdef ADDTIVEFOG\r\n\t#else\r\n\t\tuniform vec3 u_FogColor;\r\n\t#endif\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tvec4 color = 2.0 * u_AlbedoColor;\r\n\t#ifdef COLOR\r\n\t\tcolor *= v_Color;\r\n\t#endif\r\n\t#ifdef MAINTEXTURE\r\n\t\tcolor *= texture2D(u_AlbedoTexture, v_Texcoord0);\r\n\t#endif\r\n\t\r\n\tgl_FragColor = color;\r\n\t\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact = clamp((1.0 / gl_FragCoord.w - u_FogStart) / u_FogRange, 0.0, 1.0);\r\n\t\t#ifdef ADDTIVEFOG\r\n\t\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0.0), lerpFact);\r\n\t\t#else\r\n\t\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, u_FogColor, lerpFact);\r\n\t\t#endif\r\n\t#endif\r\n}\r\n\r\n";
  28628. var EffectVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec4 a_Color;\r\nattribute vec2 a_Texcoord0;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n#endif\r\n\r\n#ifdef COLOR\r\n\tvarying vec4 v_Color;\r\n#endif\r\nvarying vec2 v_Texcoord0;\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\tposition=skinTransform*a_Position;\r\n\t#else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t\r\n\t#ifdef TILINGOFFSET\r\n\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t#else\r\n\t\tv_Texcoord0=a_Texcoord0;\r\n\t#endif\r\n\t\t\r\n\t#ifdef COLOR\r\n\t\tv_Color = a_Color;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  28629. var extendTerrainPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)\r\n\tuniform vec3 u_CameraPos;\r\n\tvarying vec3 v_Normal;\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\tuniform vec3 u_FogColor;\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tuniform DirectionLight u_DirectionLight;\r\n\t\t#endif\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tuniform PointLight u_PointLight;\r\n\t\t#endif\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tuniform SpotLight u_SpotLight;\r\n\t\t#endif\r\n\t#else\r\n\t\tuniform mat4 u_View;\r\n\t\tuniform vec4 u_ProjectionParams;\r\n\t\tuniform vec4 u_Viewport;\r\n\t\tuniform int u_DirationLightCount;\r\n\t\tuniform sampler2D u_LightBuffer;\r\n\t\tuniform sampler2D u_LightClusterBuffer;\r\n\t#endif\r\n#endif\r\n\r\n#include \"ShadowHelper.glsl\"\r\n#ifdef RECEIVESHADOW\r\n\t#if defined(SHADOWMAP_PSSM2)||defined(SHADOWMAP_PSSM3)\r\n\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\tvarying vec4 v_lightMVPPos;\r\n\t#endif\r\n#endif\r\nvarying float v_posViewZ;\r\n\r\nuniform vec3 u_AmbientColor;\r\n\r\nuniform sampler2D u_SplatAlphaTexture;\r\n\r\nuniform sampler2D u_DiffuseTexture1;\r\nuniform sampler2D u_DiffuseTexture2;\r\nuniform sampler2D u_DiffuseTexture3;\r\nuniform sampler2D u_DiffuseTexture4;\r\nuniform sampler2D u_DiffuseTexture5;\r\n\r\nuniform vec4 u_DiffuseScaleOffset1;\r\nuniform vec4 u_DiffuseScaleOffset2;\r\nuniform vec4 u_DiffuseScaleOffset3;\r\nuniform vec4 u_DiffuseScaleOffset4;\r\nuniform vec4 u_DiffuseScaleOffset5;\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\n#ifdef LIGHTMAP\r\n\tuniform sampler2D u_LightMap;\r\n\tvarying vec2 v_LightMapUV;\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tvec4 splatAlpha = vec4(1.0);\r\n\t#ifdef ExtendTerrain_DETAIL_NUM1\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r;\r\n\t#endif\r\n\t#ifdef ExtendTerrain_DETAIL_NUM2\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tvec4 color2 = texture2D(u_DiffuseTexture2, v_Texcoord0 * u_DiffuseScaleOffset2.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r + color2.xyz * (1.0 - splatAlpha.r);\r\n\t#endif\r\n\t#ifdef ExtendTerrain_DETAIL_NUM3\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tvec4 color2 = texture2D(u_DiffuseTexture2, v_Texcoord0 * u_DiffuseScaleOffset2.xy);\r\n\t\tvec4 color3 = texture2D(u_DiffuseTexture3, v_Texcoord0 * u_DiffuseScaleOffset3.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r + color2.xyz * splatAlpha.g + color3.xyz * (1.0 - splatAlpha.r - splatAlpha.g);\r\n\t#endif\r\n\t#ifdef ExtendTerrain_DETAIL_NUM4\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tvec4 color2 = texture2D(u_DiffuseTexture2, v_Texcoord0 * u_DiffuseScaleOffset2.xy);\r\n\t\tvec4 color3 = texture2D(u_DiffuseTexture3, v_Texcoord0 * u_DiffuseScaleOffset3.xy);\r\n\t\tvec4 color4 = texture2D(u_DiffuseTexture4, v_Texcoord0 * u_DiffuseScaleOffset4.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r + color2.xyz * splatAlpha.g + color3.xyz * splatAlpha.b + color4.xyz * (1.0 - splatAlpha.r - splatAlpha.g - splatAlpha.b);\r\n\t#endif\r\n\t#ifdef ExtendTerrain_DETAIL_NUM5\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tvec4 color2 = texture2D(u_DiffuseTexture2, v_Texcoord0 * u_DiffuseScaleOffset2.xy);\r\n\t\tvec4 color3 = texture2D(u_DiffuseTexture3, v_Texcoord0 * u_DiffuseScaleOffset3.xy);\r\n\t\tvec4 color4 = texture2D(u_DiffuseTexture4, v_Texcoord0 * u_DiffuseScaleOffset4.xy);\r\n\t\tvec4 color5 = texture2D(u_DiffuseTexture5, v_Texcoord0 * u_DiffuseScaleOffset5.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r + color2.xyz * splatAlpha.g + color3.xyz * splatAlpha.b + color4.xyz * splatAlpha.a + color5.xyz * (1.0 - splatAlpha.r - splatAlpha.g - splatAlpha.b - splatAlpha.a);\r\n\t#endif\r\n\t\tgl_FragColor.w = splatAlpha.a;\r\n\t\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tvec3 normal = v_Normal;\r\n\t\tvec3 dif, spe;\r\n\t#endif\r\n\r\n\tvec3 diffuse = vec3(0.0);\r\n\tvec3 specular= vec3(0.0);\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)\r\n\t\tvec3 toEye;\r\n\t\t#ifdef FOG\r\n\t\t\ttoEye=u_CameraPos-v_PositionWorld;\r\n\t\t\tfloat toEyeLength=length(toEye);\r\n\t\t\ttoEye/=toEyeLength;\r\n\t\t#else\r\n\t\t\ttoEye=normalize(u_CameraPos-v_PositionWorld);\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tLayaAirBlinnPhongDiectionLight(vec3(0.0),1.0,normal,vec3(1.0),toEye,u_DirectionLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tLayaAirBlinnPhongPointLight(v_PositionWorld,vec3(0.0),1.0,normal,vec3(1.0),toEye,u_PointLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tLayaAirBlinnPhongSpotLight(v_PositionWorld,vec3(0.0),1.0,normal,vec3(1.0),toEye,u_SpotLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t{\r\n\t\t\t\tif(i >= u_DirationLightCount)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tDirectionLight directionLight = getDirectionLight(u_LightBuffer,i);\r\n\t\t\t\tLayaAirBlinnPhongDiectionLight(vec3(0.0),1.0,normal,vec3(1.0),toEye,directionLight,dif,spe);\r\n\t\t\t\tdiffuse+=dif;\r\n\t\t\t\tspecular+=spe;\r\n\t\t\t}\r\n\t\t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tivec4 clusterInfo =getClusterInfo(u_LightClusterBuffer,u_View,u_Viewport, v_PositionWorld,gl_FragCoord,u_ProjectionParams);\r\n\t\t\t#ifdef POINTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.x)//PointLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tPointLight pointLight = getPointLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaAirBlinnPhongPointLight(v_PositionWorld,vec3(0.0),1.0,normal,vec3(1.0),toEye,pointLight,dif,spe);\r\n\t\t\t\t\tdiffuse+=dif;\r\n\t\t\t\t\tspecular+=spe;\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#ifdef SPOTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.y)//SpotLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tSpotLight spotLight = getSpotLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaAirBlinnPhongSpotLight(v_PositionWorld,vec3(0.0),1.0,normal,vec3(1.0),toEye\t,spotLight,dif,spe);\r\n\t\t\t\t\tdiffuse+=dif;\r\n\t\t\t\t\tspecular+=spe;\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\r\nvec3 globalDiffuse = u_AmbientColor;\r\n#ifdef LIGHTMAP\r\n\tglobalDiffuse += DecodeLightmap(texture2D(u_LightMap, v_LightMapUV));\r\n#endif\r\n\r\n#ifdef RECEIVESHADOW\r\n\tfloat shadowValue = 1.0;\r\n\t#ifdef SHADOWMAP_PSSM3\r\n\t\tshadowValue = getShadowPSSM3( u_shadowMap1,u_shadowMap2,u_shadowMap3,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM2\r\n\t\tshadowValue = getShadowPSSM2( u_shadowMap1,u_shadowMap2,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t#endif \r\n\t#ifdef SHADOWMAP_PSSM1\r\n\t\tshadowValue = getShadowPSSM1( u_shadowMap1,v_lightMVPPos,u_shadowPSSMDistance,u_shadowPCFoffset,v_posViewZ,0.001);\r\n\t#endif\r\n\tgl_FragColor = vec4(gl_FragColor.rgb * (globalDiffuse + diffuse) * shadowValue, gl_FragColor.a);\r\n#else\r\n\tgl_FragColor = vec4(gl_FragColor.rgb * (globalDiffuse + diffuse), gl_FragColor.a);\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t#ifdef RECEIVESHADOW\r\n\t\tgl_FragColor.rgb += specular * shadowValue;\r\n\t#else\r\n\t\tgl_FragColor.rgb += specular;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat lerpFact=clamp((toEyeLength-u_FogStart)/u_FogRange,0.0,1.0);\r\n\tgl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\r\n#endif\r\n}\r\n\r\n\r\n\r\n\r\n\r\n";
  28630. var extendTerrainVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec2 a_Texcoord0;\r\n\r\nuniform mat4 u_MvpMatrix;\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(LIGHTMAP)\r\n\tattribute vec3 a_Normal;\r\n\tvarying vec3 v_Normal;\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)||(defined(RECEIVESHADOW)&&defined(SHADOWMAP_PSSM1))\r\n\tuniform mat4 u_WorldMat;\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvarying vec2 v_LightMapUV;\r\n\tuniform vec4 u_LightmapScaleOffset;\r\n#endif\r\n\r\n#ifdef RECEIVESHADOW\r\n\tvarying float v_posViewZ;\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\t\tvarying vec4 v_lightMVPPos;\r\n\t\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tgl_Position = u_MvpMatrix * a_Position;\r\n \r\n\tv_Texcoord0 = a_Texcoord0;\r\n \r\n\t#ifdef LIGHTMAP\r\n\t\tv_LightMapUV = vec2(a_Texcoord0.x, 1.0 - a_Texcoord0.y) * u_LightmapScaleOffset.xy + u_LightmapScaleOffset.zw;\r\n\t\tv_LightMapUV.y = 1.0 - v_LightMapUV.y;\r\n\t#endif\r\n \r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tv_Normal = a_Normal;\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)||(defined(RECEIVESHADOW)&&defined(SHADOWMAP_PSSM1))\r\n\t\tv_PositionWorld=(u_WorldMat*a_Position).xyz;\r\n\t#endif\r\n\r\n\t#ifdef RECEIVESHADOW\r\n\t\tv_posViewZ = gl_Position.w;\r\n\t\t#ifdef SHADOWMAP_PSSM1\r\n\t\t\tv_lightMVPPos = u_lightShadowVP[0] * vec4(v_PositionWorld,1.0);\r\n\t\t#endif\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  28631. var LightingGLSL = "struct DirectionLight {\r\n\tvec3 color;\r\n\tvec3 direction;\r\n};\r\n\r\nstruct PointLight {\r\n\tvec3 color;\r\n\tvec3 position;\r\n\tfloat range;\r\n};\r\n\r\nstruct SpotLight {\r\n\tvec3 color;\r\n\tvec3 position;\r\n\tfloat range;\r\n\tvec3 direction;\r\n\tfloat spot;\r\n};\r\n\r\n\r\n\r\nconst int c_ClusterBufferWidth = CLUSTER_X_COUNT*CLUSTER_Y_COUNT;\r\nconst int c_ClusterBufferHeight = CLUSTER_Z_COUNT*(1+int(ceil(float(MAX_LIGHT_COUNT_PER_CLUSTER)/4.0)));\r\nconst int c_ClusterBufferFloatWidth = c_ClusterBufferWidth*4;\r\n\r\nivec4 getClusterInfo(sampler2D clusterBuffer,mat4 viewMatrix,vec4 viewport,vec3 position,vec4 fragCoord,vec4 projectParams)\r\n{\r\n\tvec3 viewPos = vec3(viewMatrix*vec4(position, 1.0)); //position in viewspace\r\n\r\n\tint clusterXIndex = int(floor(fragCoord.x/ (float(viewport.z)/float(CLUSTER_X_COUNT))));\r\n int clusterYIndex = int(floor((viewport.w * (projectParams.z <0.0? 0.0 : 1.0) - fragCoord.y * projectParams.z)/ (float(viewport.w)/float(CLUSTER_Y_COUNT))));//Maybe Flipped ProjectMatrix\r\n\tfloat zSliceParam =float(CLUSTER_Z_COUNT)/log2(projectParams.y / projectParams.x);\r\n \tint clusterZIndex = int(floor(log2(-viewPos.z) * zSliceParam- log2(projectParams.x) * zSliceParam));//projectParams x:cameraNear y:cameraFar\r\n\r\n\tvec2 uv= vec2((float(clusterXIndex + clusterYIndex * CLUSTER_X_COUNT)+0.5)/float(c_ClusterBufferWidth),\r\n\t\t\t\t(float(clusterZIndex)+0.5)/float(c_ClusterBufferHeight));\r\n\tvec4 clusterPixel=texture2D(clusterBuffer, uv);\r\n\treturn ivec4(clusterPixel);//X:Point Count Y:Spot Count Z、W:Light Offset\r\n}\r\n\r\n\r\nint getLightIndex(sampler2D clusterBuffer,int offset,int index) \r\n{\r\n\tint totalOffset=offset+index;\r\n\tint row=totalOffset/c_ClusterBufferFloatWidth;\r\n\tint lastRowFloat=totalOffset-row*c_ClusterBufferFloatWidth;\r\n\tint col=lastRowFloat/4;\r\n\tvec2 uv=vec2((float(col)+0.5)/float(c_ClusterBufferWidth),\r\n\t\t\t\t(float(row)+0.5)/float(c_ClusterBufferHeight));\r\n\tvec4 texel = texture2D(clusterBuffer, uv);\r\n int pixelComponent = lastRowFloat-col*4;\r\n if (pixelComponent == 0) \r\n return int(texel.x);\r\n else if (pixelComponent == 1) \r\n return int(texel.y);\r\n else if (pixelComponent == 2) \r\n return int(texel.z);\r\n else if (pixelComponent == 3) \r\n return int(texel.w);\r\n}\r\n\r\nDirectionLight getDirectionLight(sampler2D lightBuffer,int index) \r\n{\r\n DirectionLight light;\r\n float v = (float(index)+0.5)/ float(MAX_LIGHT_COUNT);\r\n vec4 p1 = texture2D(lightBuffer, vec2(0.125,v));\r\n vec4 p2 = texture2D(lightBuffer, vec2(0.375,v));\r\n\tlight.color=p1.rgb;\r\n light.direction = p2.rgb;\r\n return light;\r\n}\r\n\r\nPointLight getPointLight(sampler2D lightBuffer,sampler2D clusterBuffer,ivec4 clusterInfo,int index) \r\n{\r\n PointLight light;\r\n\tint pointIndex=getLightIndex(clusterBuffer,clusterInfo.z*c_ClusterBufferFloatWidth+clusterInfo.w,index);\r\n float v = (float(pointIndex)+0.5)/ float(MAX_LIGHT_COUNT);\r\n vec4 p1 = texture2D(lightBuffer, vec2(0.125,v));\r\n vec4 p2 = texture2D(lightBuffer, vec2(0.375,v));\r\n\tlight.color=p1.rgb;\r\n\tlight.range = p1.a;\r\n light.position = p2.rgb;\r\n return light;\r\n}\r\n\r\nSpotLight getSpotLight(sampler2D lightBuffer,sampler2D clusterBuffer,ivec4 clusterInfo,int index) \r\n{\r\n SpotLight light;\r\n\tint spoIndex=getLightIndex(clusterBuffer,clusterInfo.z*c_ClusterBufferFloatWidth+clusterInfo.w,clusterInfo.x+index);\r\n float v = (float(spoIndex)+0.5)/ float(MAX_LIGHT_COUNT);\r\n vec4 p1 = texture2D(lightBuffer, vec2(0.125,v));\r\n vec4 p2 = texture2D(lightBuffer, vec2(0.375,v));\r\n\tvec4 p3 = texture2D(lightBuffer, vec2(0.625,v));\r\n light.color = p1.rgb;\r\n\tlight.range=p1.a;\r\n light.position = p2.rgb;\r\n\tlight.spot = p2.a;\r\n\tlight.direction = p3.rgb;\r\n return light;\r\n}\r\n\r\n\r\n\r\n// Laya中使用衰减纹理\r\nfloat LayaAttenuation(in vec3 L,in float invLightRadius) {\r\n\tfloat fRatio = clamp(length(L) * invLightRadius,0.0,1.0);\r\n\tfRatio *= fRatio;\r\n\treturn 1.0 / (1.0 + 25.0 * fRatio)* clamp(4.0*(1.0 - fRatio),0.0,1.0); //fade to black as if 4 pixel texture\r\n}\r\n\r\n// Same as Just Cause 2 and Crysis 2 (you can read GPU Pro 1 book for more information)\r\nfloat BasicAttenuation(in vec3 L,in float invLightRadius) {\r\n\tvec3 distance = L * invLightRadius;\r\n\tfloat attenuation = clamp(1.0 - dot(distance, distance),0.0,1.0); // Equals float attenuation = saturate(1.0f - dot(L, L) / (lightRadius * lightRadius));\r\n\treturn attenuation * attenuation;\r\n}\r\n\r\n// Inspired on http://fools.slindev.com/viewtopic.php?f=11&t=21&view=unread#unread\r\nfloat NaturalAttenuation(in vec3 L,in float invLightRadius) {\r\n\tfloat attenuationFactor = 30.0;\r\n\tvec3 distance = L * invLightRadius;\r\n\tfloat attenuation = dot(distance, distance); // Equals float attenuation = dot(L, L) / (lightRadius * lightRadius);\r\n\tattenuation = 1.0 / (attenuation * attenuationFactor + 1.0);\r\n\t// Second we move down the function therewith it reaches zero at abscissa 1:\r\n\tattenuationFactor = 1.0 / (attenuationFactor + 1.0); //attenuationFactor contains now the value we have to subtract\r\n\tattenuation = max(attenuation - attenuationFactor, 0.0); // The max fixes a bug.\r\n\t// Finally we expand the equation along the y-axis so that it starts with a function value of 1 again.\r\n\tattenuation /= 1.0 - attenuationFactor;\r\n\treturn attenuation;\r\n}\r\n\r\nvoid LayaAirBlinnPhongLight (in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir,in vec3 lightColor, in vec3 lightVec,out vec3 diffuseColor,out vec3 specularColor) {\r\n\tmediump vec3 h = normalize(viewDir-lightVec);\r\n\tlowp float ln = max (0.0, dot (-lightVec,normal));\r\n\tfloat nh = max (0.0, dot (h,normal));\r\n\tdiffuseColor=lightColor * ln;\r\n\tspecularColor=lightColor *specColor*pow (nh, specColorIntensity*128.0) * gloss;\r\n}\r\n\r\nvoid LayaAirBlinnPhongDiectionLight (in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in DirectionLight light,out vec3 diffuseColor,out vec3 specularColor) {\r\n\tvec3 lightVec=normalize(light.direction);\r\n\tLayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.color,lightVec,diffuseColor,specularColor);\r\n}\r\n\r\nvoid LayaAirBlinnPhongPointLight (in vec3 pos,in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in PointLight light,out vec3 diffuseColor,out vec3 specularColor) {\r\n\tvec3 lightVec = pos-light.position;\r\n\tLayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.color,lightVec/length(lightVec),diffuseColor,specularColor);\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range);\r\n\tdiffuseColor *= attenuate;\r\n\tspecularColor*= attenuate;\r\n}\r\n\r\nvoid LayaAirBlinnPhongSpotLight (in vec3 pos,in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in SpotLight light,out vec3 diffuseColor,out vec3 specularColor) {\r\n\tvec3 lightVec = pos-light.position;\r\n\tvec3 normalLightVec=lightVec/length(lightVec);\r\n\tLayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.color,normalLightVec,diffuseColor,specularColor);\r\n\tvec2 cosAngles=cos(vec2(light.spot,light.spot*0.5)*0.5);//ConeAttenuation\r\n\tfloat dl=dot(normalize(light.direction),normalLightVec);\r\n\tdl*=smoothstep(cosAngles[0],cosAngles[1],dl);\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range)*dl;\r\n\tdiffuseColor *=attenuate;\r\n\tspecularColor *=attenuate;\r\n}\r\n\r\nvec3 NormalSampleToWorldSpace(vec3 normalMapSample, vec3 unitNormal, vec3 tangent,vec3 binormal) {\r\n\tvec3 normalT =vec3(2.0*normalMapSample.x - 1.0,1.0-2.0*normalMapSample.y,2.0*normalMapSample.z - 1.0);\r\n\r\n\t// Build orthonormal basis.\r\n\tvec3 N = normalize(unitNormal);\r\n\tvec3 T = normalize(tangent);\r\n\tvec3 B = normalize(binormal);\r\n\tmat3 TBN = mat3(T, B, N);\r\n\r\n\t// Transform from tangent space to world space.\r\n\tvec3 bumpedNormal = TBN*normalT;\r\n\r\n\treturn bumpedNormal;\r\n}\r\n\r\nvec3 NormalSampleToWorldSpace1(vec4 normalMapSample, vec3 tangent, vec3 binormal, vec3 unitNormal) {\r\n\tvec3 normalT;\r\n\tnormalT.x = 2.0 * normalMapSample.x - 1.0;\r\n\tnormalT.y = 1.0 - 2.0 * normalMapSample.y;\r\n\tnormalT.z = sqrt(1.0 - clamp(dot(normalT.xy, normalT.xy), 0.0, 1.0));\r\n\r\n\tvec3 T = normalize(tangent);\r\n\tvec3 B = normalize(binormal);\r\n\tvec3 N = normalize(unitNormal);\r\n\tmat3 TBN = mat3(T, B, N);\r\n\r\n\t// Transform from tangent space to world space.\r\n\tvec3 bumpedNormal = TBN * normalize(normalT);\r\n\r\n\treturn bumpedNormal;\r\n}\r\n\r\nvec3 DecodeLightmap(vec4 color) {\r\n\treturn color.rgb*color.a*5.0;\r\n}\r\n\r\nvec2 TransformUV(vec2 texcoord,vec4 tilingOffset) {\r\n\tvec2 transTexcoord=vec2(texcoord.x,texcoord.y-1.0)*tilingOffset.xy+vec2(tilingOffset.z,-tilingOffset.w);\r\n\ttransTexcoord.y+=1.0;\r\n\treturn transTexcoord;\r\n}\r\n\r\nvec4 remapGLPositionZ(vec4 position) {\r\n\tposition.z=position.z * 2.0 - position.w;\r\n\treturn position;\r\n}\r\n\r\nmat3 inverse(mat3 m) {\r\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\r\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\r\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\r\n\r\n float b01 = a22 * a11 - a12 * a21;\r\n float b11 = -a22 * a10 + a12 * a20;\r\n float b21 = a21 * a10 - a11 * a20;\r\n\r\n float det = a00 * b01 + a01 * b11 + a02 * b21;\r\n\r\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\r\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\r\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\r\n}\r\n\r\n";
  28632. var linePS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\nprecision highp float;\r\n#else\r\nprecision mediump float;\r\n#endif\r\n\r\nvarying vec4 v_Color;\r\nuniform vec4 u_Color;\r\n\r\nvoid main()\r\n{\r\n gl_FragColor = v_Color * u_Color; \r\n}\r\n\r\n";
  28633. var lineVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nuniform mat4 u_MvpMatrix;\r\nuniform vec4 u_Color;\r\nattribute vec4 a_Color;\r\nvarying vec4 v_Color;\r\n\r\n\r\nvoid main()\r\n{\r\n\tgl_Position = u_MvpMatrix * a_Position;\r\n\tv_Color=a_Color*u_Color;\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  28634. var MeshBlinnPhongPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\nuniform vec4 u_DiffuseColor;\r\n\r\n#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\tvarying vec4 v_Color;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tuniform float u_AlphaTestValue;\r\n#endif\r\n\r\n#ifdef DIFFUSEMAP\r\n\tuniform sampler2D u_DiffuseTexture;\r\n#endif\r\n\r\n\r\n#if defined(DIFFUSEMAP)||((defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&(defined(SPECULARMAP)||defined(NORMALMAP)))\r\n\tvarying vec2 v_Texcoord0;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvarying vec2 v_LightMapUV;\r\n\tuniform sampler2D u_LightMap;\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\tvarying vec3 v_Normal;\r\n\tvarying vec3 v_ViewDir; \r\n\r\n\tuniform vec3 u_MaterialSpecular;\r\n\tuniform float u_Shininess;\r\n\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tuniform DirectionLight u_DirectionLight;\r\n\t\t#endif\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tuniform PointLight u_PointLight;\r\n\t\t#endif\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tuniform SpotLight u_SpotLight;\r\n\t\t#endif\r\n\t#else\r\n\t\tuniform mat4 u_View;\r\n\t\tuniform vec4 u_ProjectionParams;\r\n\t\tuniform vec4 u_Viewport;\r\n\t\tuniform int u_DirationLightCount;\r\n\t\tuniform sampler2D u_LightBuffer;\r\n\t\tuniform sampler2D u_LightClusterBuffer;\r\n\t#endif\r\n\r\n\t#ifdef SPECULARMAP \r\n\t\tuniform sampler2D u_SpecularTexture;\r\n\t#endif\r\n\t#ifdef NORMALMAP \r\n\t\tuniform sampler2D u_NormalTexture;\r\n\t\tvarying vec3 v_Tangent;\r\n\t\tvarying vec3 v_Binormal;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\tuniform vec3 u_FogColor;\r\n#endif\r\n\r\n\r\nuniform vec3 u_AmbientColor;\r\n\r\n#if defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n#include \"ShadowHelper.glsl\"\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n\t#if defined(SHADOWMAP_PSSM2)||defined(SHADOWMAP_PSSM3)\r\n\t\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\t\tvarying vec4 v_lightMVPPos;\r\n\t#endif\r\n#endif\r\n\r\nvoid main_castShadow()\r\n{\r\n\t//gl_FragColor=vec4(v_posViewZ,0.0,0.0,1.0);\r\n\tgl_FragColor=packDepth(v_posViewZ);\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tfloat alpha = texture2D(u_DiffuseTexture,v_Texcoord0).w;\r\n\t\tif( alpha < u_AlphaTestValue )\r\n\t\t{\r\n\t\t\tdiscard;\r\n\t\t}\r\n\t#endif\r\n}\r\nvoid main_normal()\r\n{\r\n\tvec3 globalDiffuse=u_AmbientColor;\r\n\t#ifdef LIGHTMAP\t\r\n\t\tglobalDiffuse += DecodeLightmap(texture2D(u_LightMap, v_LightMapUV));\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tvec3 normal;\r\n\t\t#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&defined(NORMALMAP)\r\n\t\t\tvec3 normalMapSample = texture2D(u_NormalTexture, v_Texcoord0).rgb;\r\n\t\t\tnormal = normalize(NormalSampleToWorldSpace(normalMapSample, v_Normal, v_Tangent,v_Binormal));\r\n\t\t#else\r\n\t\t\tnormal = normalize(v_Normal);\r\n\t\t#endif\r\n\t\tvec3 viewDir= normalize(v_ViewDir);\r\n\t#endif\r\n\t\r\n\tvec4 mainColor=u_DiffuseColor;\r\n\t#ifdef DIFFUSEMAP\r\n\t\tvec4 difTexColor=texture2D(u_DiffuseTexture, v_Texcoord0);\r\n\t\tmainColor=mainColor*difTexColor;\r\n\t#endif \r\n\t#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\t\tmainColor=mainColor*v_Color;\r\n\t#endif \r\n \r\n\t#ifdef ALPHATEST\r\n\t\tif(mainColor.a<u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n \r\n\t\r\n\tvec3 diffuse = vec3(0.0);\r\n\tvec3 specular= vec3(0.0);\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tvec3 dif,spe;\r\n\t\t#ifdef SPECULARMAP\r\n\t\t\tvec3 gloss=texture2D(u_SpecularTexture, v_Texcoord0).rgb;\r\n\t\t#else\r\n\t\t\t#ifdef DIFFUSEMAP\r\n\t\t\t\tvec3 gloss=vec3(difTexColor.a);\r\n\t\t\t#else\r\n\t\t\t\tvec3 gloss=vec3(1.0);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tLayaAirBlinnPhongDiectionLight(u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,u_DirectionLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tLayaAirBlinnPhongPointLight(v_PositionWorld,u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,u_PointLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tLayaAirBlinnPhongSpotLight(v_PositionWorld,u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,u_SpotLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t{\r\n\t\t\t\tif(i >= u_DirationLightCount)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tDirectionLight directionLight = getDirectionLight(u_LightBuffer,i);\r\n\t\t\t\tLayaAirBlinnPhongDiectionLight(u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,directionLight,dif,spe);\r\n\t\t\t\tdiffuse+=dif;\r\n\t\t\t\tspecular+=spe;\r\n\t\t\t}\r\n\t\t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tivec4 clusterInfo =getClusterInfo(u_LightClusterBuffer,u_View,u_Viewport, v_PositionWorld,gl_FragCoord,u_ProjectionParams);\r\n\t\t\t#ifdef POINTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.x)//PointLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tPointLight pointLight = getPointLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaAirBlinnPhongPointLight(v_PositionWorld,u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,pointLight,dif,spe);\r\n\t\t\t\t\tdiffuse+=dif;\r\n\t\t\t\t\tspecular+=spe;\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#ifdef SPOTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.y)//SpotLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tSpotLight spotLight = getSpotLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaAirBlinnPhongSpotLight(v_PositionWorld,u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,spotLight,dif,spe);\r\n\t\t\t\t\tdiffuse+=dif;\r\n\t\t\t\t\tspecular+=spe;\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#ifdef RECEIVESHADOW\r\n\t\tfloat shadowValue = 1.0;\r\n\t\t#ifdef SHADOWMAP_PSSM3\r\n\t\t\tshadowValue = getShadowPSSM3(u_shadowMap1,u_shadowMap2,u_shadowMap3,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\t#ifdef SHADOWMAP_PSSM2\r\n\t\t\tshadowValue = getShadowPSSM2(u_shadowMap1,u_shadowMap2,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif \r\n\t\t#ifdef SHADOWMAP_PSSM1\r\n\t\t\tshadowValue = getShadowPSSM1(u_shadowMap1,v_lightMVPPos,u_shadowPSSMDistance,u_shadowPCFoffset,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\tgl_FragColor =vec4(mainColor.rgb*(globalDiffuse + diffuse*shadowValue),mainColor.a);\r\n\t#else\r\n\t\tgl_FragColor =vec4(mainColor.rgb*(globalDiffuse + diffuse),mainColor.a);\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t#ifdef RECEIVESHADOW\r\n\t\t\tgl_FragColor.rgb+=specular*shadowValue;\r\n\t\t#else\r\n\t\t\tgl_FragColor.rgb+=specular;\r\n\t\t#endif\r\n\t#endif\r\n\t \r\n\t#ifdef FOG\r\n\t\tfloat lerpFact=clamp((1.0/gl_FragCoord.w-u_FogStart)/u_FogRange,0.0,1.0);\r\n\t\tgl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\r\n\t#endif\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\t\t\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif \r\n}\r\n\r\n";
  28635. var MeshBlinnPhongVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n#endif\r\n\r\n\r\n#if defined(DIFFUSEMAP)||((defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&(defined(SPECULARMAP)||defined(NORMALMAP)))||(defined(LIGHTMAP)&&defined(UV))\r\n\tattribute vec2 a_Texcoord0;\r\n\tvarying vec2 v_Texcoord0;\r\n#endif\r\n\r\n#if defined(LIGHTMAP)&&defined(UV1)\r\n\tattribute vec2 a_Texcoord1;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tuniform vec4 u_LightmapScaleOffset;\r\n\tvarying vec2 v_LightMapUV;\r\n#endif\r\n\r\n#ifdef COLOR\r\n\tattribute vec4 a_Color;\r\n\tvarying vec4 v_Color;\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\tattribute vec3 a_Normal;\r\n\tvarying vec3 v_Normal; \r\n\tuniform vec3 u_CameraPos;\r\n\tvarying vec3 v_ViewDir; \r\n#endif\r\n\r\n#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&defined(NORMALMAP)\r\n\tattribute vec4 a_Tangent0;\r\n\tvarying vec3 v_Tangent;\r\n\tvarying vec3 v_Binormal;\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)\r\n\t#ifdef GPU_INSTANCE\r\n\t\tattribute mat4 a_WorldMat;\r\n\t#else\r\n\t\tuniform mat4 u_WorldMat;\r\n\t#endif\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n #ifdef SHADOWMAP_PSSM1 \r\n varying vec4 v_lightMVPPos;\r\n uniform mat4 u_lightShadowVP[4];\r\n #endif\r\n#endif\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\nvoid main_castShadow()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\tposition=skinTransform*a_Position;\r\n\t#else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t\r\n\t//TODO没考虑UV动画呢\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tv_Texcoord0=a_Texcoord0;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n\tv_posViewZ = gl_Position.z;\r\n}\r\n\r\nvoid main_normal()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\tposition=skinTransform*a_Position;\r\n\t#else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)\r\n\t\tmat4 worldMat;\r\n\t\t#ifdef GPU_INSTANCE\r\n\t\t\tworldMat = a_WorldMat;\r\n\t\t#else\r\n\t\t\tworldMat = u_WorldMat;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tmat3 worldInvMat;\r\n\t\t#ifdef BONE\r\n\t\t\tworldInvMat=inverse(mat3(worldMat*skinTransform));\r\n\t\t#else\r\n\t\t\tworldInvMat=inverse(mat3(worldMat));\r\n\t\t#endif \r\n\t\tv_Normal=a_Normal*worldInvMat;\r\n\t\t#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&defined(NORMALMAP)\r\n\t\t\tv_Tangent=a_Tangent0.xyz*worldInvMat;\r\n\t\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)\r\n\t\tv_PositionWorld=(worldMat*position).xyz;\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tv_ViewDir=u_CameraPos-v_PositionWorld;\r\n\t#endif\r\n\r\n\t#if defined(DIFFUSEMAP)||((defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&(defined(SPECULARMAP)||defined(NORMALMAP)))\r\n\t\t#ifdef TILINGOFFSET\r\n\t\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t\t#else\r\n\t\t\tv_Texcoord0=a_Texcoord0;\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#ifdef LIGHTMAP\r\n\t\t#ifdef SCALEOFFSETLIGHTINGMAPUV\r\n\t\t\t#ifdef UV1\r\n\t\t\t\tv_LightMapUV=vec2(a_Texcoord1.x,1.0-a_Texcoord1.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;\r\n\t\t\t#else\r\n\t\t\t\tv_LightMapUV=vec2(a_Texcoord0.x,1.0-a_Texcoord0.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;\r\n\t\t\t#endif \r\n\t\t\tv_LightMapUV.y=1.0-v_LightMapUV.y;\r\n\t\t#else\r\n\t\t\t#ifdef UV1\r\n\t\t\t\tv_LightMapUV=a_Texcoord1;\r\n\t\t\t#else\r\n\t\t\t\tv_LightMapUV=a_Texcoord0;\r\n\t\t\t#endif \r\n\t\t#endif \r\n\t#endif\r\n\r\n\t#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\t\tv_Color=a_Color;\r\n\t#endif\r\n\r\n\t#ifdef RECEIVESHADOW\r\n\t\tv_posViewZ = gl_Position.w;\r\n\t\t#ifdef SHADOWMAP_PSSM1 \r\n\t\t\tv_lightMVPPos = u_lightShadowVP[0] * vec4(v_PositionWorld,1.0);\r\n\t\t#endif\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif\r\n}";
  28636. var ParticleShuriKenPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n precision highp float;\r\n#else\r\n precision mediump float;\r\n#endif\r\n\r\nvarying vec4 v_Color;\r\nvarying vec2 v_TextureCoordinate;\r\nuniform sampler2D u_texture;\r\nuniform vec4 u_Tintcolor;\r\n\r\n#ifdef RENDERMODE_MESH\r\n\tvarying vec4 v_MeshColor;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\t#ifdef ADDTIVEFOG\r\n\t#else\r\n\t\tuniform vec3 u_FogColor;\r\n\t#endif\r\n#endif\r\n\r\n\r\nvoid main()\r\n{\t\r\n\t#ifdef RENDERMODE_MESH\r\n\t\tgl_FragColor=v_MeshColor;\r\n\t#else\r\n\t\tgl_FragColor=vec4(1.0);\t\r\n\t#endif\r\n\t\t\r\n\t#ifdef DIFFUSEMAP\r\n\t\t#ifdef TINTCOLOR\r\n\t\t\tgl_FragColor*=texture2D(u_texture,v_TextureCoordinate)*u_Tintcolor*2.0*v_Color;\r\n\t\t#else\r\n\t\t\tgl_FragColor*=texture2D(u_texture,v_TextureCoordinate)*v_Color;\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef TINTCOLOR\r\n\t\t\tgl_FragColor*=u_Tintcolor*2.0*v_Color;\r\n\t\t#else\r\n\t\t\tgl_FragColor*=v_Color;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact=clamp((1.0/gl_FragCoord.w-u_FogStart)/u_FogRange,0.0,1.0);\r\n\t\t#ifdef ADDTIVEFOG\r\n\t\t\tgl_FragColor.rgb=mix(gl_FragColor.rgb,vec3(0.0,0.0,0.0),lerpFact);\r\n\t\t#else\r\n\t\t\tgl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\r\n\t\t#endif\r\n\t#endif\r\n}";
  28637. var ParticleShuriKenVS = "#include \"Lighting.glsl\";\r\n\r\n#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n precision highp float;\r\n#else\r\n precision mediump float;\r\n#endif\r\n\r\n#if defined(SPHERHBILLBOARD)||defined(STRETCHEDBILLBOARD)||defined(HORIZONTALBILLBOARD)||defined(VERTICALBILLBOARD)\r\n\tattribute vec4 a_CornerTextureCoordinate;\r\n#endif\r\n#ifdef RENDERMODE_MESH\r\n\tattribute vec3 a_MeshPosition;\r\n\tattribute vec4 a_MeshColor;\r\n\tattribute vec2 a_MeshTextureCoordinate;\r\n\tvarying vec4 v_MeshColor;\r\n#endif\r\n\r\nattribute vec4 a_ShapePositionStartLifeTime;\r\nattribute vec4 a_DirectionTime;\r\nattribute vec4 a_StartColor;\r\nattribute vec3 a_StartSize;\r\nattribute vec3 a_StartRotation0;\r\nattribute float a_StartSpeed;\r\n#if defined(COLOROVERLIFETIME)||defined(RANDOMCOLOROVERLIFETIME)||defined(SIZEOVERLIFETIMERANDOMCURVES)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\r\n attribute vec4 a_Random0;\r\n#endif\r\n#if defined(TEXTURESHEETANIMATIONRANDOMCURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n attribute vec4 a_Random1;\r\n#endif\r\nattribute vec3 a_SimulationWorldPostion;\r\nattribute vec4 a_SimulationWorldRotation;\r\n\r\nvarying vec4 v_Color;\r\n#ifdef DIFFUSEMAP\r\n\tvarying vec2 v_TextureCoordinate;\r\n#endif\r\n\r\nuniform float u_CurrentTime;\r\nuniform vec3 u_Gravity;\r\n\r\nuniform vec3 u_WorldPosition;\r\nuniform vec4 u_WorldRotation;\r\nuniform bool u_ThreeDStartRotation;\r\nuniform int u_ScalingMode;\r\nuniform vec3 u_PositionScale;\r\nuniform vec3 u_SizeScale;\r\nuniform mat4 u_View;\r\nuniform mat4 u_Projection;\r\n\r\n#ifdef STRETCHEDBILLBOARD\r\n\tuniform vec3 u_CameraPos;\r\n#endif\r\nuniform vec3 u_CameraDirection;//TODO:只有几种广告牌模式需要用\r\nuniform vec3 u_CameraUp;\r\n\r\nuniform float u_StretchedBillboardLengthScale;\r\nuniform float u_StretchedBillboardSpeedScale;\r\nuniform int u_SimulationSpace;\r\n\r\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n uniform int u_VOLSpaceType;\r\n#endif\r\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)\r\n uniform vec3 u_VOLVelocityConst;\r\n#endif\r\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n uniform vec2 u_VOLVelocityGradientX[4];//x为key,y为速度\r\n uniform vec2 u_VOLVelocityGradientY[4];//x为key,y为速度\r\n uniform vec2 u_VOLVelocityGradientZ[4];//x为key,y为速度\r\n#endif\r\n#ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\r\n uniform vec3 u_VOLVelocityConstMax;\r\n#endif\r\n#ifdef VELOCITYOVERLIFETIMERANDOMCURVE\r\n uniform vec2 u_VOLVelocityGradientMaxX[4];//x为key,y为速度\r\n uniform vec2 u_VOLVelocityGradientMaxY[4];//x为key,y为速度\r\n uniform vec2 u_VOLVelocityGradientMaxZ[4];//x为key,y为速度\r\n#endif\r\n\r\n#ifdef COLOROVERLIFETIME\r\n uniform vec4 u_ColorOverLifeGradientColors[4];//x为key,yzw为Color\r\n uniform vec2 u_ColorOverLifeGradientAlphas[4];//x为key,y为Alpha\r\n#endif\r\n#ifdef RANDOMCOLOROVERLIFETIME\r\n uniform vec4 u_ColorOverLifeGradientColors[4];//x为key,yzw为Color\r\n uniform vec2 u_ColorOverLifeGradientAlphas[4];//x为key,y为Alpha\r\n uniform vec4 u_MaxColorOverLifeGradientColors[4];//x为key,yzw为Color\r\n uniform vec2 u_MaxColorOverLifeGradientAlphas[4];//x为key,y为Alpha\r\n#endif\r\n\r\n\r\n#if defined(SIZEOVERLIFETIMECURVE)||defined(SIZEOVERLIFETIMERANDOMCURVES)\r\n uniform vec2 u_SOLSizeGradient[4];//x为key,y为尺寸\r\n#endif\r\n#ifdef SIZEOVERLIFETIMERANDOMCURVES\r\n uniform vec2 u_SOLSizeGradientMax[4];//x为key,y为尺寸\r\n#endif\r\n#if defined(SIZEOVERLIFETIMECURVESEPERATE)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)\r\n uniform vec2 u_SOLSizeGradientX[4];//x为key,y为尺寸\r\n uniform vec2 u_SOLSizeGradientY[4];//x为key,y为尺寸\r\n uniform vec2 u_SOLSizeGradientZ[4];//x为key,y为尺寸\r\n#endif\r\n#ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\r\n uniform vec2 u_SOLSizeGradientMaxX[4];//x为key,y为尺寸\r\n uniform vec2 u_SOLSizeGradientMaxY[4];//x为key,y为尺寸\r\n uniform vec2 u_SOLSizeGradientMaxZ[4];//x为key,y为尺寸\r\n#endif\r\n\r\n\r\n#ifdef ROTATIONOVERLIFETIME\r\n #if defined(ROTATIONOVERLIFETIMECONSTANT)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)\r\n uniform float u_ROLAngularVelocityConst;\r\n #endif\r\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n uniform float u_ROLAngularVelocityConstMax;\r\n #endif\r\n #if defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\r\n uniform vec2 u_ROLAngularVelocityGradient[4];//x为key,y为旋转\r\n #endif\r\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n uniform vec2 u_ROLAngularVelocityGradientMax[4];//x为key,y为旋转\r\n #endif\r\n#endif\r\n#ifdef ROTATIONOVERLIFETIMESEPERATE\r\n #if defined(ROTATIONOVERLIFETIMECONSTANT)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)\r\n uniform vec3 u_ROLAngularVelocityConstSeprarate;\r\n #endif\r\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n uniform vec3 u_ROLAngularVelocityConstMaxSeprarate;\r\n #endif\r\n #if defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\r\n uniform vec2 u_ROLAngularVelocityGradientX[4];\r\n uniform vec2 u_ROLAngularVelocityGradientY[4];\r\n uniform vec2 u_ROLAngularVelocityGradientZ[4];\r\n #endif\r\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n uniform vec2 u_ROLAngularVelocityGradientMaxX[4];\r\n uniform vec2 u_ROLAngularVelocityGradientMaxY[4];\r\n uniform vec2 u_ROLAngularVelocityGradientMaxZ[4];\r\n\tuniform vec2 u_ROLAngularVelocityGradientMaxW[4];\r\n #endif\r\n#endif\r\n\r\n#if defined(TEXTURESHEETANIMATIONCURVE)||defined(TEXTURESHEETANIMATIONRANDOMCURVE)\r\n uniform float u_TSACycles;\r\n uniform vec2 u_TSASubUVLength;\r\n uniform vec2 u_TSAGradientUVs[4];//x为key,y为frame\r\n#endif\r\n#ifdef TEXTURESHEETANIMATIONRANDOMCURVE\r\n uniform vec2 u_TSAMaxGradientUVs[4];//x为key,y为frame\r\n#endif\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\nvec3 rotationByEuler(in vec3 vector,in vec3 rot)\r\n{\r\n\tfloat halfRoll = rot.z * 0.5;\r\n float halfPitch = rot.x * 0.5;\r\n\tfloat halfYaw = rot.y * 0.5;\r\n\r\n\tfloat sinRoll = sin(halfRoll);\r\n\tfloat cosRoll = cos(halfRoll);\r\n\tfloat sinPitch = sin(halfPitch);\r\n\tfloat cosPitch = cos(halfPitch);\r\n\tfloat sinYaw = sin(halfYaw);\r\n\tfloat cosYaw = cos(halfYaw);\r\n\r\n\tfloat quaX = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);\r\n\tfloat quaY = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);\r\n\tfloat quaZ = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);\r\n\tfloat quaW = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);\r\n\t\r\n\t//vec4 q=vec4(quaX,quaY,quaZ,quaW);\r\n\t//vec3 temp = cross(q.xyz, vector) + q.w * vector;\r\n\t//return (cross(temp, -q.xyz) + dot(q.xyz,vector) * q.xyz + q.w * temp);\r\n\t\r\n\tfloat x = quaX + quaX;\r\n float y = quaY + quaY;\r\n float z = quaZ + quaZ;\r\n float wx = quaW * x;\r\n float wy = quaW * y;\r\n float wz = quaW * z;\r\n\tfloat xx = quaX * x;\r\n float xy = quaX * y;\r\n\tfloat xz = quaX * z;\r\n float yy = quaY * y;\r\n float yz = quaY * z;\r\n float zz = quaZ * z;\r\n\r\n return vec3(((vector.x * ((1.0 - yy) - zz)) + (vector.y * (xy - wz))) + (vector.z * (xz + wy)),\r\n ((vector.x * (xy + wz)) + (vector.y * ((1.0 - xx) - zz))) + (vector.z * (yz - wx)),\r\n ((vector.x * (xz - wy)) + (vector.y * (yz + wx))) + (vector.z * ((1.0 - xx) - yy)));\r\n\t\r\n}\r\n\r\n//假定axis已经归一化\r\nvec3 rotationByAxis(in vec3 vector,in vec3 axis, in float angle)\r\n{\r\n\tfloat halfAngle = angle * 0.5;\r\n\tfloat sin = sin(halfAngle);\r\n\t\r\n\tfloat quaX = axis.x * sin;\r\n\tfloat quaY = axis.y * sin;\r\n\tfloat quaZ = axis.z * sin;\r\n\tfloat quaW = cos(halfAngle);\r\n\t\r\n\t//vec4 q=vec4(quaX,quaY,quaZ,quaW);\r\n\t//vec3 temp = cross(q.xyz, vector) + q.w * vector;\r\n\t//return (cross(temp, -q.xyz) + dot(q.xyz,vector) * q.xyz + q.w * temp);\r\n\t\r\n\tfloat x = quaX + quaX;\r\n float y = quaY + quaY;\r\n float z = quaZ + quaZ;\r\n float wx = quaW * x;\r\n float wy = quaW * y;\r\n float wz = quaW * z;\r\n\tfloat xx = quaX * x;\r\n float xy = quaX * y;\r\n\tfloat xz = quaX * z;\r\n float yy = quaY * y;\r\n float yz = quaY * z;\r\n float zz = quaZ * z;\r\n\r\n return vec3(((vector.x * ((1.0 - yy) - zz)) + (vector.y * (xy - wz))) + (vector.z * (xz + wy)),\r\n ((vector.x * (xy + wz)) + (vector.y * ((1.0 - xx) - zz))) + (vector.z * (yz - wx)),\r\n ((vector.x * (xz - wy)) + (vector.y * (yz + wx))) + (vector.z * ((1.0 - xx) - yy)));\r\n\t\r\n}\r\n\r\nvec3 rotationByQuaternions(in vec3 v,in vec4 q) \r\n{\r\n\treturn v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);\r\n}\r\n\r\n \r\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)||defined(SIZEOVERLIFETIMECURVE)||defined(SIZEOVERLIFETIMECURVESEPERATE)||defined(SIZEOVERLIFETIMERANDOMCURVES)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)\r\nfloat getCurValueFromGradientFloat(in vec2 gradientNumbers[4],in float normalizedAge)\r\n{\r\n\tfloat curValue;\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec2 gradientNumber=gradientNumbers[i];\r\n\t\tfloat key=gradientNumber.x;\r\n\t\tif(key>=normalizedAge)\r\n\t\t{\r\n\t\t\tvec2 lastGradientNumber=gradientNumbers[i-1];\r\n\t\t\tfloat lastKey=lastGradientNumber.x;\r\n\t\t\tfloat age=(normalizedAge-lastKey)/(key-lastKey);\r\n\t\t\tcurValue=mix(lastGradientNumber.y,gradientNumber.y,age);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn curValue;\r\n}\r\n#endif\r\n\r\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)||defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\r\nfloat getTotalValueFromGradientFloat(in vec2 gradientNumbers[4],in float normalizedAge)\r\n{\r\n\tfloat totalValue=0.0;\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec2 gradientNumber=gradientNumbers[i];\r\n\t\tfloat key=gradientNumber.x;\r\n\t\tvec2 lastGradientNumber=gradientNumbers[i-1];\r\n\t\tfloat lastValue=lastGradientNumber.y;\r\n\t\t\r\n\t\tif(key>=normalizedAge){\r\n\t\t\tfloat lastKey=lastGradientNumber.x;\r\n\t\t\tfloat age=(normalizedAge-lastKey)/(key-lastKey);\r\n\t\t\ttotalValue+=(lastValue+mix(lastValue,gradientNumber.y,age))/2.0*a_ShapePositionStartLifeTime.w*(normalizedAge-lastKey);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\telse{\r\n\t\t\ttotalValue+=(lastValue+gradientNumber.y)/2.0*a_ShapePositionStartLifeTime.w*(key-lastGradientNumber.x);\r\n\t\t}\r\n\t}\r\n\treturn totalValue;\r\n}\r\n#endif\r\n\r\n#if defined(COLOROVERLIFETIME)||defined(RANDOMCOLOROVERLIFETIME)\r\nvec4 getColorFromGradient(in vec2 gradientAlphas[4],in vec4 gradientColors[4],in float normalizedAge)\r\n{\r\n\tvec4 overTimeColor;\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec2 gradientAlpha=gradientAlphas[i];\r\n\t\tfloat alphaKey=gradientAlpha.x;\r\n\t\tif(alphaKey>=normalizedAge)\r\n\t\t{\r\n\t\t\tvec2 lastGradientAlpha=gradientAlphas[i-1];\r\n\t\t\tfloat lastAlphaKey=lastGradientAlpha.x;\r\n\t\t\tfloat age=(normalizedAge-lastAlphaKey)/(alphaKey-lastAlphaKey);\r\n\t\t\toverTimeColor.a=mix(lastGradientAlpha.y,gradientAlpha.y,age);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec4 gradientColor=gradientColors[i];\r\n\t\tfloat colorKey=gradientColor.x;\r\n\t\tif(colorKey>=normalizedAge)\r\n\t\t{\r\n\t\t\tvec4 lastGradientColor=gradientColors[i-1];\r\n\t\t\tfloat lastColorKey=lastGradientColor.x;\r\n\t\t\tfloat age=(normalizedAge-lastColorKey)/(colorKey-lastColorKey);\r\n\t\t\toverTimeColor.rgb=mix(gradientColors[i-1].yzw,gradientColor.yzw,age);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn overTimeColor;\r\n}\r\n#endif\r\n\r\n\r\n#if defined(TEXTURESHEETANIMATIONCURVE)||defined(TEXTURESHEETANIMATIONRANDOMCURVE)\r\nfloat getFrameFromGradient(in vec2 gradientFrames[4],in float normalizedAge)\r\n{\r\n\tfloat overTimeFrame;\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec2 gradientFrame=gradientFrames[i];\r\n\t\tfloat key=gradientFrame.x;\r\n\t\tif(key>=normalizedAge)\r\n\t\t{\r\n\t\t\tvec2 lastGradientFrame=gradientFrames[i-1];\r\n\t\t\tfloat lastKey=lastGradientFrame.x;\r\n\t\t\tfloat age=(normalizedAge-lastKey)/(key-lastKey);\r\n\t\t\toverTimeFrame=mix(lastGradientFrame.y,gradientFrame.y,age);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn floor(overTimeFrame);\r\n}\r\n#endif\r\n\r\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\nvec3 computeParticleLifeVelocity(in float normalizedAge)\r\n{\r\n vec3 outLifeVelocity;\r\n #ifdef VELOCITYOVERLIFETIMECONSTANT\r\n\t outLifeVelocity=u_VOLVelocityConst; \r\n #endif\r\n #ifdef VELOCITYOVERLIFETIMECURVE\r\n outLifeVelocity= vec3(getCurValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge));\r\n #endif\r\n #ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\r\n\t outLifeVelocity=mix(u_VOLVelocityConst,u_VOLVelocityConstMax,vec3(a_Random1.y,a_Random1.z,a_Random1.w)); \r\n #endif\r\n #ifdef VELOCITYOVERLIFETIMERANDOMCURVE\r\n outLifeVelocity=vec3(mix(getCurValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxX,normalizedAge),a_Random1.y),\r\n\t mix(getCurValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxY,normalizedAge),a_Random1.z),\r\n\t\t\t\t\t mix(getCurValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxZ,normalizedAge),a_Random1.w));\r\n #endif\r\n\t\t\t\t\t\r\n return outLifeVelocity;\r\n} \r\n#endif\r\n\r\nvec3 computeParticlePosition(in vec3 startVelocity, in vec3 lifeVelocity,in float age,in float normalizedAge,vec3 gravityVelocity,vec4 worldRotation)\r\n{\r\n vec3 startPosition;\r\n vec3 lifePosition;\r\n #if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n\t#ifdef VELOCITYOVERLIFETIMECONSTANT\r\n\t\t startPosition=startVelocity*age;\r\n\t\t lifePosition=lifeVelocity*age;\r\n\t#endif\r\n\t#ifdef VELOCITYOVERLIFETIMECURVE\r\n\t\t startPosition=startVelocity*age;\r\n\t\t lifePosition=vec3(getTotalValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge));\r\n\t#endif\r\n\t#ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\r\n\t\t startPosition=startVelocity*age;\r\n\t\t lifePosition=lifeVelocity*age;\r\n\t#endif\r\n\t#ifdef VELOCITYOVERLIFETIMERANDOMCURVE\r\n\t\t startPosition=startVelocity*age;\r\n\t\t lifePosition=vec3(mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxX,normalizedAge),a_Random1.y)\r\n\t ,mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxY,normalizedAge),a_Random1.z)\r\n\t ,mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxZ,normalizedAge),a_Random1.w));\r\n\t#endif\r\n\t\r\n\tvec3 finalPosition;\r\n\tif(u_VOLSpaceType==0){\r\n\t if(u_ScalingMode!=2)\r\n\t finalPosition =rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition+lifePosition),worldRotation);\r\n\t else\r\n\t finalPosition =rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition+lifePosition,worldRotation);\r\n\t}\r\n\telse{\r\n\t if(u_ScalingMode!=2)\r\n\t finalPosition = rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition),worldRotation)+lifePosition;\r\n\t else\r\n\t finalPosition = rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition,worldRotation)+lifePosition;\r\n\t}\r\n #else\r\n\t startPosition=startVelocity*age;\r\n\t vec3 finalPosition;\r\n\t if(u_ScalingMode!=2)\r\n\t\t\tfinalPosition = rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition),worldRotation);\r\n\t else\r\n\t \tfinalPosition = rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition,worldRotation);\r\n #endif\r\n \r\n if(u_SimulationSpace==0)\r\n finalPosition=finalPosition+a_SimulationWorldPostion;\r\n else if(u_SimulationSpace==1) \r\n finalPosition=finalPosition+u_WorldPosition;\r\n \r\n finalPosition+=0.5*gravityVelocity*age;\r\n \r\n return finalPosition;\r\n}\r\n\r\n\r\nvec4 computeParticleColor(in vec4 color,in float normalizedAge)\r\n{\r\n\t#ifdef COLOROVERLIFETIME\r\n\t color*=getColorFromGradient(u_ColorOverLifeGradientAlphas,u_ColorOverLifeGradientColors,normalizedAge);\r\n\t#endif\r\n\t\r\n\t#ifdef RANDOMCOLOROVERLIFETIME\r\n\t color*=mix(getColorFromGradient(u_ColorOverLifeGradientAlphas,u_ColorOverLifeGradientColors,normalizedAge),getColorFromGradient(u_MaxColorOverLifeGradientAlphas,u_MaxColorOverLifeGradientColors,normalizedAge),a_Random0.y);\r\n\t#endif\r\n\r\n return color;\r\n}\r\n\r\nvec2 computeParticleSizeBillbard(in vec2 size,in float normalizedAge)\r\n{\r\n\t#ifdef SIZEOVERLIFETIMECURVE\r\n\t\tsize*=getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge);\r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMERANDOMCURVES\r\n\t size*=mix(getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMax,normalizedAge),a_Random0.z); \r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMECURVESEPERATE\r\n\t\tsize*=vec2(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge));\r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\r\n\t size*=vec2(mix(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxX,normalizedAge),a_Random0.z)\r\n\t ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxY,normalizedAge),a_Random0.z));\r\n\t#endif\r\n\treturn size;\r\n}\r\n\r\n#ifdef RENDERMODE_MESH\r\nvec3 computeParticleSizeMesh(in vec3 size,in float normalizedAge)\r\n{\r\n\t#ifdef SIZEOVERLIFETIMECURVE\r\n\t\tsize*=getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge);\r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMERANDOMCURVES\r\n\t size*=mix(getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMax,normalizedAge),a_Random0.z); \r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMECURVESEPERATE\r\n\t\tsize*=vec3(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientZ,normalizedAge));\r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\r\n\t size*=vec3(mix(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxX,normalizedAge),a_Random0.z)\r\n\t ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxY,normalizedAge),a_Random0.z)\r\n\t\t,mix(getCurValueFromGradientFloat(u_SOLSizeGradientZ,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxZ,normalizedAge),a_Random0.z));\r\n\t#endif\r\n\treturn size;\r\n}\r\n#endif\r\n\r\nfloat computeParticleRotationFloat(in float rotation,in float age,in float normalizedAge)\r\n{ \r\n\t#ifdef ROTATIONOVERLIFETIME\r\n\t\t#ifdef ROTATIONOVERLIFETIMECONSTANT\r\n\t\t\tfloat ageRot=u_ROLAngularVelocityConst*age;\r\n\t rotation+=ageRot;\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMECURVE\r\n\t\t\trotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge);\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n\t\t\tfloat ageRot=mix(u_ROLAngularVelocityConst,u_ROLAngularVelocityConstMax,a_Random0.w)*age;\r\n\t rotation+=ageRot;\r\n\t #endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n\t\t\trotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMax,normalizedAge),a_Random0.w);\r\n\t\t#endif\r\n\t#endif\r\n\t#ifdef ROTATIONOVERLIFETIMESEPERATE\r\n\t\t#ifdef ROTATIONOVERLIFETIMECONSTANT\r\n\t\t\tfloat ageRot=u_ROLAngularVelocityConstSeprarate.z*age;\r\n\t rotation+=ageRot;\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMECURVE\r\n\t\t\trotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge);\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n\t\t\tfloat ageRot=mix(u_ROLAngularVelocityConstSeprarate.z,u_ROLAngularVelocityConstMaxSeprarate.z,a_Random0.w)*age;\r\n\t rotation+=ageRot;\r\n\t #endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n\t\t\trotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxZ,normalizedAge),a_Random0.w));\r\n\t\t#endif\r\n\t#endif\r\n\treturn rotation;\r\n}\r\n\r\n#if defined(RENDERMODE_MESH)&&(defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE))\r\nvec3 computeParticleRotationVec3(in vec3 rotation,in float age,in float normalizedAge)\r\n{ \r\n\t#ifdef ROTATIONOVERLIFETIME\r\n\t#ifdef ROTATIONOVERLIFETIMECONSTANT\r\n\t\t\tfloat ageRot=u_ROLAngularVelocityConst*age;\r\n\t rotation+=ageRot;\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMECURVE\r\n\t\t\trotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge);\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n\t\t\tfloat ageRot=mix(u_ROLAngularVelocityConst,u_ROLAngularVelocityConstMax,a_Random0.w)*age;\r\n\t rotation+=ageRot;\r\n\t #endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n\t\t\trotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMax,normalizedAge),a_Random0.w);\r\n\t\t#endif\r\n\t#endif\r\n\t#ifdef ROTATIONOVERLIFETIMESEPERATE\r\n\t\t#ifdef ROTATIONOVERLIFETIMECONSTANT\r\n\t\t\tvec3 ageRot=u_ROLAngularVelocityConstSeprarate*age;\r\n\t rotation+=ageRot;\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMECURVE\r\n\t\t\trotation+=vec3(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge));\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n\t\t\tvec3 ageRot=mix(u_ROLAngularVelocityConstSeprarate,u_ROLAngularVelocityConstMaxSeprarate,a_Random0.w)*age;\r\n\t rotation+=ageRot;\r\n\t #endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n\t\t\trotation+=vec3(mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxX,normalizedAge),a_Random0.w)\r\n\t ,mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxY,normalizedAge),a_Random0.w)\r\n\t ,mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxZ,normalizedAge),a_Random0.w));\r\n\t\t#endif\r\n\t#endif\r\n\treturn rotation;\r\n}\r\n#endif\r\n\r\nvec2 computeParticleUV(in vec2 uv,in float normalizedAge)\r\n{ \r\n\t#ifdef TEXTURESHEETANIMATIONCURVE\r\n\t\tfloat cycleNormalizedAge=normalizedAge*u_TSACycles;\r\n\t\tfloat frame=getFrameFromGradient(u_TSAGradientUVs,cycleNormalizedAge-floor(cycleNormalizedAge));\r\n\t\tfloat totalULength=frame*u_TSASubUVLength.x;\r\n\t\tfloat floorTotalULength=floor(totalULength);\r\n\t uv.x+=totalULength-floorTotalULength;\r\n\t\tuv.y+=floorTotalULength*u_TSASubUVLength.y;\r\n #endif\r\n\t#ifdef TEXTURESHEETANIMATIONRANDOMCURVE\r\n\t\tfloat cycleNormalizedAge=normalizedAge*u_TSACycles;\r\n\t\tfloat uvNormalizedAge=cycleNormalizedAge-floor(cycleNormalizedAge);\r\n\t float frame=floor(mix(getFrameFromGradient(u_TSAGradientUVs,uvNormalizedAge),getFrameFromGradient(u_TSAMaxGradientUVs,uvNormalizedAge),a_Random1.x));\r\n\t\tfloat totalULength=frame*u_TSASubUVLength.x;\r\n\t\tfloat floorTotalULength=floor(totalULength);\r\n\t uv.x+=totalULength-floorTotalULength;\r\n\t\tuv.y+=floorTotalULength*u_TSASubUVLength.y;\r\n #endif\r\n\treturn uv;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat age = u_CurrentTime - a_DirectionTime.w;\r\n\tfloat normalizedAge = age/a_ShapePositionStartLifeTime.w;\r\n\tvec3 lifeVelocity;\r\n\tif(normalizedAge<1.0)\r\n\t{ \r\n\t\tvec3 startVelocity=a_DirectionTime.xyz*a_StartSpeed;\r\n\t\t#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n\t\t\tlifeVelocity= computeParticleLifeVelocity(normalizedAge);//计算粒子生命周期速度\r\n\t\t#endif \r\n\t\tvec3 gravityVelocity=u_Gravity*age;\r\n\t\t\r\n\t\tvec4 worldRotation;\r\n\t\tif(u_SimulationSpace==0)\r\n\t\t\tworldRotation=a_SimulationWorldRotation;\r\n\t\telse\r\n\t\t\tworldRotation=u_WorldRotation;\r\n\t\t\r\n\t\tvec3 center=computeParticlePosition(startVelocity, lifeVelocity, age, normalizedAge,gravityVelocity,worldRotation);//计算粒子位置\r\n\t\r\n\t\r\n\t\t#ifdef SPHERHBILLBOARD\r\n\t\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\t\tvec3 cameraUpVector =normalize(u_CameraUp);//TODO:是否外面归一化\r\n\t\t\tvec3 sideVector = normalize(cross(u_CameraDirection,cameraUpVector));\r\n\t\t\tvec3 upVector = normalize(cross(sideVector,u_CameraDirection));\r\n\t\t\tcorner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\r\n\t\t\t#if defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE)\r\n\t\t\t\tif(u_ThreeDStartRotation){\r\n\t\t\t\t\tvec3 rotation=vec3(a_StartRotation0.xy,computeParticleRotationFloat(a_StartRotation0.z,age,normalizedAge));\r\n\t\t\t\t\tcenter += u_SizeScale.xzy*rotationByEuler(corner.x*sideVector+corner.y*upVector,rotation);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tfloat rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\r\n\t\t\t\t\tfloat c = cos(rot);\r\n\t\t\t\t\tfloat s = sin(rot);\r\n\t\t\t\t\tmat2 rotation= mat2(c, -s, s, c);\r\n\t\t\t\t\tcorner=rotation*corner;\r\n\t\t\t\t\tcenter += u_SizeScale.xzy*(corner.x*sideVector+corner.y*upVector);\r\n\t\t\t\t}\r\n\t\t\t#else\r\n\t\t\t\tif(u_ThreeDStartRotation){\r\n\t\t\t\t\tcenter += u_SizeScale.xzy*rotationByEuler(corner.x*sideVector+corner.y*upVector,a_StartRotation0);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tfloat c = cos(a_StartRotation0.x);\r\n\t\t\t\t\tfloat s = sin(a_StartRotation0.x);\r\n\t\t\t\t\tmat2 rotation= mat2(c, -s, s, c);\r\n\t\t\t\t\tcorner=rotation*corner;\r\n\t\t\t\t\tcenter += u_SizeScale.xzy*(corner.x*sideVector+corner.y*upVector);\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef STRETCHEDBILLBOARD\r\n\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\tvec3 velocity;\r\n\t\t#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n\t\t\tif(u_VOLSpaceType==0)\r\n\t\t\tvelocity=rotationByQuaternions(u_SizeScale*(startVelocity+lifeVelocity),worldRotation)+gravityVelocity;\r\n\t\t\telse\r\n\t\t\tvelocity=rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+lifeVelocity+gravityVelocity;\r\n\t\t#else\r\n\t\t\tvelocity= rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+gravityVelocity;\r\n\t\t#endif\t\r\n\t\t\tvec3 cameraUpVector = normalize(velocity);\r\n\t\t\tvec3 direction = normalize(center-u_CameraPos);\r\n\t\t\tvec3 sideVector = normalize(cross(direction,normalize(velocity)));\r\n\t\t\t\r\n\t\t\tsideVector=u_SizeScale.xzy*sideVector;\r\n\t\t\tcameraUpVector=length(vec3(u_SizeScale.x,0.0,0.0))*cameraUpVector;\r\n\t\t\t\r\n\t\t\tvec2 size=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\r\n\t\t\t\r\n\t\t\tconst mat2 rotaionZHalfPI=mat2(0.0, -1.0, 1.0, 0.0);\r\n\t\t\tcorner=rotaionZHalfPI*corner;\r\n\t\t\tcorner.y=corner.y-abs(corner.y);\r\n\t\t\t\r\n\t\t\tfloat speed=length(velocity);//TODO:\r\n\t\t\tcenter +=sign(u_SizeScale.x)*(sign(u_StretchedBillboardLengthScale)*size.x*corner.x*sideVector+(speed*u_StretchedBillboardSpeedScale+size.y*u_StretchedBillboardLengthScale)*corner.y*cameraUpVector);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef HORIZONTALBILLBOARD\r\n\t\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\t\tconst vec3 cameraUpVector=vec3(0.0,0.0,1.0);\r\n\t\t\tconst vec3 sideVector = vec3(-1.0,0.0,0.0);\r\n\t\t\t\r\n\t\t\tfloat rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\r\n\t\t\tfloat c = cos(rot);\r\n\t\t\tfloat s = sin(rot);\r\n\t\t\tmat2 rotation= mat2(c, -s, s, c);\r\n\t\t\tcorner=rotation*corner*cos(0.78539816339744830961566084581988);//TODO:临时缩小cos45,不确定U3D原因\r\n\t\t\tcorner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\r\n\t\t\tcenter +=u_SizeScale.xzy*(corner.x*sideVector+ corner.y*cameraUpVector);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef VERTICALBILLBOARD\r\n\t\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\t\tconst vec3 cameraUpVector =vec3(0.0,1.0,0.0);\r\n\t\t\tvec3 sideVector = normalize(cross(u_CameraDirection,cameraUpVector));\r\n\t\t\t\r\n\t\t\tfloat rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\r\n\t\t\tfloat c = cos(rot);\r\n\t\t\tfloat s = sin(rot);\r\n\t\t\tmat2 rotation= mat2(c, -s, s, c);\r\n\t\t\tcorner=rotation*corner*cos(0.78539816339744830961566084581988);//TODO:临时缩小cos45,不确定U3D原因\r\n\t\t\tcorner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\r\n\t\t\tcenter +=u_SizeScale.xzy*(corner.x*sideVector+ corner.y*cameraUpVector);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef RENDERMODE_MESH\r\n\t\t\tvec3 size=computeParticleSizeMesh(a_StartSize,normalizedAge);\r\n\t\t\t#if defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE)\r\n\t\t\t\tif(u_ThreeDStartRotation){\r\n\t\t\t\t\tvec3 rotation=vec3(a_StartRotation0.xy,computeParticleRotationFloat(a_StartRotation0.z, age,normalizedAge));\r\n\t\t\t\t\tcenter+= rotationByQuaternions(u_SizeScale*rotationByEuler(a_MeshPosition*size,rotation),worldRotation);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\t#ifdef ROTATIONOVERLIFETIME\r\n\t\t\t\t\t\tfloat angle=computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\r\n\t\t\t\t\t\tif(a_ShapePositionStartLifeTime.x!=0.0||a_ShapePositionStartLifeTime.y!=0.0){\r\n\t\t\t\t\t\t\tcenter+= (rotationByQuaternions(rotationByAxis(u_SizeScale*a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),angle),worldRotation));//已验证\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t#ifdef SHAPE\r\n\t\t\t\t\t\t\t\tcenter+= u_SizeScale.xzy*(rotationByQuaternions(rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),angle),worldRotation));\r\n\t\t\t\t\t\t\t#else\r\n\t\t\t\t\t\t\t\tif(u_SimulationSpace==0)\r\n\t\t\t\t\t\t\t\t\tcenter+=rotationByAxis(u_SizeScale*a_MeshPosition*size,vec3(0.0,0.0,-1.0),angle);//已验证\r\n\t\t\t\t\t\t\t\telse if(u_SimulationSpace==1)\r\n\t\t\t\t\t\t\t\t\tcenter+=rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,0.0,-1.0),angle),worldRotation);//已验证\r\n\t\t\t\t\t\t\t#endif\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t#endif\r\n\t\t\t\t\t#ifdef ROTATIONOVERLIFETIMESEPERATE\r\n\t\t\t\t\t\t//TODO:是否应合并if(u_ThreeDStartRotation)分支代码,待测试\r\n\t\t\t\t\t\tvec3 angle=computeParticleRotationVec3(vec3(0.0,0.0,-a_StartRotation0.x), age,normalizedAge);\r\n\t\t\t\t\t\tcenter+= (rotationByQuaternions(rotationByEuler(u_SizeScale*a_MeshPosition*size,vec3(angle.x,angle.y,angle.z)),worldRotation));//已验证\r\n\t\t\t\t\t#endif\t\t\r\n\t\t\t\t}\r\n\t\t\t#else\r\n\t\t\t\tif(u_ThreeDStartRotation){\r\n\t\t\t\t\tcenter+= rotationByQuaternions(u_SizeScale*rotationByEuler(a_MeshPosition*size,a_StartRotation0),worldRotation);//已验证\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tif(a_ShapePositionStartLifeTime.x!=0.0||a_ShapePositionStartLifeTime.y!=0.0){\r\n\t\t\t\t\t\tif(u_SimulationSpace==0)\r\n\t\t\t\t\t\t\tcenter+= rotationByAxis(u_SizeScale*a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),a_StartRotation0.x);\r\n\t\t\t\t\t\telse if(u_SimulationSpace==1)\r\n\t\t\t\t\t\t\tcenter+= (rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),a_StartRotation0.x),worldRotation));//已验证\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{\r\n\t\t\t\t\t\t#ifdef SHAPE\r\n\t\t\t\t\t\t\tif(u_SimulationSpace==0)\r\n\t\t\t\t\t\t\t\tcenter+= u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),a_StartRotation0.x);\r\n\t\t\t\t\t\t\telse if(u_SimulationSpace==1)\r\n\t\t\t\t\t\t\t\tcenter+= rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),a_StartRotation0.x),worldRotation);\t\r\n\t\t\t\t\t\t#else\r\n\t\t\t\t\t\t\tif(u_SimulationSpace==0)\r\n\t\t\t\t\t\t\t\tcenter+= rotationByAxis(u_SizeScale*a_MeshPosition*size,vec3(0.0,0.0,-1.0),a_StartRotation0.x);\r\n\t\t\t\t\t\t\telse if(u_SimulationSpace==1)\r\n\t\t\t\t\t\t\t\tcenter+= rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,0.0,-1.0),a_StartRotation0.x),worldRotation);//已验证\r\n\t\t\t\t\t\t#endif\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\tv_MeshColor=a_MeshColor;\r\n\t\t#endif\r\n\t\r\n\t\tgl_Position=u_Projection*u_View*vec4(center,1.0);\r\n\t\tv_Color = computeParticleColor(a_StartColor, normalizedAge);\r\n\t\t#ifdef DIFFUSEMAP\r\n\t\t\t#if defined(SPHERHBILLBOARD)||defined(STRETCHEDBILLBOARD)||defined(HORIZONTALBILLBOARD)||defined(VERTICALBILLBOARD)\r\n\t\t\t\tv_TextureCoordinate =computeParticleUV(a_CornerTextureCoordinate.zw, normalizedAge);\r\n\t\t\t#endif\r\n\t\t\t#ifdef RENDERMODE_MESH\r\n\t\t\t\tv_TextureCoordinate =computeParticleUV(a_MeshTextureCoordinate, normalizedAge);\r\n\t\t\t#endif\r\n\t\t\t\r\n\t\t\t#ifdef TILINGOFFSET\r\n\t\t\t\tv_TextureCoordinate=TransformUV(v_TextureCoordinate,u_TilingOffset);\r\n\t\t\t#endif\r\n\t\t#endif\r\n \t}\r\n \telse\r\n\t{\r\n\t\tgl_Position=vec4(2.0,2.0,2.0,1.0);//Discard use out of X(-1,1),Y(-1,1),Z(0,1)\r\n\t}\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n\r\n";
  28638. var BRDFGLSL = "struct LayaGI\r\n{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nvec4 LayaAirBRDF(in vec3 diffuseColor, in vec3 specularColor, in float oneMinusReflectivity, in float smoothness, in vec3 normal, in vec3 viewDir, in vec3 lightDir, in vec3 lightColor, in LayaGI gi)\r\n{\r\n\tfloat perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);\r\n\tvec3 halfDir = SafeNormalize(viewDir - lightDir);\r\n\t\r\n\tfloat nv = abs(dot(normal, viewDir));\r\n\t\r\n\tfloat nl = clamp(dot(normal, -lightDir), 0.0, 1.0);\r\n\tfloat nh = clamp(dot(normal, halfDir), 0.0, 1.0);\r\n\tfloat lv = clamp(dot(lightDir, viewDir), 0.0, 1.0);\r\n\tfloat lh = clamp(dot(lightDir, -halfDir), 0.0, 1.0);\r\n\t\r\n\tfloat diffuseTerm = DisneyDiffuse(nv, nl, lh, perceptualRoughness) * nl;\r\n\t\r\n\tfloat roughness = PerceptualRoughnessToRoughness(perceptualRoughness);\r\n\t\r\n\t//#if UNITY_BRDF_GGX\r\n\t // GGX with roughtness to 0 would mean no specular at all, using max(roughness, 0.002) here to match HDrenderloop roughtness remapping.\r\n\troughness = max(roughness,0.014);\r\n\tfloat V = SmithJointGGXVisibilityTerm(nl, nv, roughness);\r\n\tfloat D = GGXTerm(nh, roughness);\r\n\t\r\n\tfloat specularTerm = V * D * PI;\r\n\t\r\n\tspecularTerm = sqrt(max(0.0001, specularTerm));\r\n\tspecularTerm = max(0.0, specularTerm * nl);\r\n\t\r\n\tfloat surfaceReduction = 1.0 - 0.28 * roughness * perceptualRoughness;\r\n\tfloat grazingTerm = clamp(smoothness + (1.0 - oneMinusReflectivity), 0.0, 1.0);\r\n\t\r\n\tvec4 color;\r\n\tcolor.rgb = diffuseColor * (gi.diffuse+lightColor * diffuseTerm) \r\n\t\t\t + specularTerm * lightColor * FresnelTerm (specularColor, lh);\r\n\t\t\t //+ surfaceReduction * gi.specular * FresnelLerp(specularColor, vec3(grazingTerm), nv);\r\n\t\r\n\treturn color;\r\n}\r\nvec4 LayaAirStandardReflect(in vec4 albedoColor,in float metallic,in float smoothness,in LayaGI gi)\r\n{\r\n\tvec3 diffuseColor;\r\n\tvec3 specularColor;\r\n\tfloat alpha;\r\n\tfloat oneMinusReflectivity;\r\n\tdiffuseColor = DiffuseAndSpecularFromMetallic (albedoColor.rgb, metallic, specularColor, oneMinusReflectivity);\r\n\tdiffuseColor = LayaPreMultiplyAlpha(diffuseColor, albedoColor.a, oneMinusReflectivity, alpha);\r\n\tfloat perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);\r\n\tfloat roughness = PerceptualRoughnessToRoughness(perceptualRoughness);\r\n\tfloat surfaceReduction = 1.0 - 0.28 * roughness * perceptualRoughness;\r\n\tvec4 color;\r\n\tcolor.rgb = surfaceReduction * gi.specular;\r\n\tcolor.a = alpha;\r\n\treturn color;\r\n\r\n}\r\n\r\nvec4 LayaAirSpecularReflect(in vec4 albedoColor,in vec3 specularColor,in float smoothness,in LayaGI gi)\r\n{\r\n\tfloat oneMinusReflectivity;\r\n\tvec3 diffuseColor;\r\n\tfloat alpha;\r\n\t\r\n\tdiffuseColor = EnergyConservationBetweenDiffuseAndSpecular (albedoColor.rgb, specularColor, oneMinusReflectivity);\r\n\t\r\n\tdiffuseColor = LayaPreMultiplyAlpha(diffuseColor, albedoColor.a, oneMinusReflectivity, alpha);\r\n\r\n\tfloat perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);\r\n\tfloat roughness = PerceptualRoughnessToRoughness(perceptualRoughness);\r\n\tfloat surfaceReduction = 1.0 - 0.28 * roughness * perceptualRoughness;\r\n\tvec4 color;\r\n\tcolor.rgb = surfaceReduction * gi.specular;\r\n\tcolor.a = alpha;\r\n\treturn color;\r\n}";
  28639. var PBRSpecularLightingGLSL = "#include \"PBRUtils.glsl\"\r\n#include \"BRDF.glsl\"\r\n\r\nvec4 PBRSpecularLight(in vec4 albedoColor, in vec3 specularColor, in float smoothness, in vec3 normal, in vec3 viewDir, in vec3 lightDir, in vec3 lightColor, in LayaGI gi)\r\n{\r\n\tfloat oneMinusReflectivity;\r\n\tvec3 diffuseColor;\r\n\tfloat alpha;\r\n\t\r\n\tdiffuseColor = EnergyConservationBetweenDiffuseAndSpecular (albedoColor.rgb, specularColor, oneMinusReflectivity);\r\n\t\r\n\tdiffuseColor = LayaPreMultiplyAlpha(diffuseColor, albedoColor.a, oneMinusReflectivity, alpha);\r\n\t\r\n\tvec4 color = LayaAirBRDF(diffuseColor, specularColor, oneMinusReflectivity, smoothness, normal, viewDir, lightDir, lightColor, gi);\r\n\tcolor.a = alpha;\r\n\treturn color;\r\n}\r\n\r\nvec4 PBRSpecularDiectionLight (in vec4 albedoColor, in vec3 specularColor, in float smoothness, in vec3 normal, in vec3 viewDir, in DirectionLight light, in LayaGI gi,in float shadowValue)\r\n{\r\n\tvec3 lightVec = normalize(light.direction);\r\n\treturn PBRSpecularLight(albedoColor, specularColor, smoothness, normal, viewDir, lightVec, light.color*shadowValue, gi);\r\n}\r\n#ifdef POINTLIGHT\r\nvec4 PBRSpecularPointLight (in vec4 albedoColor, in vec3 specularColor, in float smoothness, in vec3 normal, in vec3 viewDir, in PointLight light, in vec3 pos, in LayaGI gi,in float shadowValue)\r\n{\r\n\tvec3 lightVec = pos-light.position;\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range);\r\n\treturn PBRSpecularLight(albedoColor, specularColor, smoothness, normal, viewDir, lightVec, light.color*shadowValue, gi) * attenuate;\r\n}\r\n#endif\r\nvec4 PBRSpecularSpotLight (in vec4 albedoColor, in vec3 specularColor, in float smoothness, in vec3 normal, in vec3 viewDir, in SpotLight light, in vec3 pos, in LayaGI gi,in float shadowValue)\r\n{\r\n\tvec3 lightVec = pos - light.position;\r\n\tvec3 normalLightVec = normalize(lightVec);\r\n\tvec2 cosAngles = cos(vec2(light.spot, light.spot*0.5) * 0.5);//ConeAttenuation\r\n\tfloat dl = dot(normalize(light.direction), normalLightVec);\r\n\tdl *= smoothstep(cosAngles[0], cosAngles[1], dl);\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range) * dl;\r\n\treturn PBRSpecularLight(albedoColor, specularColor, smoothness, normal, viewDir, lightVec, light.color*shadowValue, gi) * attenuate;\r\n}\r\n\r\n//vec4 PBRStandardSpotLight1 (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in SpotLight light, in vec3 pos, in LayaGI gi)\r\n//{\r\n//\tvec4 lightCoord = u_SpotLightMatrix * vec4(pos, 1.0);\r\n//\t\r\n//\tfloat distance = dot(lightCoord, lightCoord);\r\n//\tfloat attenuate = (lightCoord.z < 0.0) ? texture2D(u_RangeTexture, vec2(distance)).w : 0.0;\r\n//\t//float attenuate = (lightCoord.z < 0.0) ? texture2D(u_AngleTexture, vec2(lightCoord.x / lightCoord.w + 0.5, lightCoord.y / lightCoord.w + 0.5)).r * texture2D(u_RangeTexture, vec2(distance)).w : 0.0;\r\n//\t//vec2 _uv = vec2(pos.x * 180.0/(2.0 * pos.z) + 0.5, pos.y * 180.0/(2.0 * pos.z) + 0.5);\r\n//\tvec3 lightVec = normalize(pos - light.cosition);\r\n//\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color, gi) * attenuate;\r\n//}\r\n\r\nvec4 SpecularGloss(float albedoTextureAlpha, in vec2 uv0)\r\n{\r\n vec4 sg;\r\n\t\r\n\t#ifdef SPECULARTEXTURE\r\n\t\tvec4 specularTextureColor = texture2D(u_SpecularTexture, uv0);\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tsg.rgb = specularTextureColor.rgb;\r\n\t\t\tsg.a = albedoTextureAlpha;\r\n\t\t#else\r\n\t\t\tsg = specularTextureColor;\r\n\t\t#endif\r\n\t\tsg.a *= u_smoothnessScale;\r\n\t#else\r\n\t\tsg.rgb = u_SpecularColor.rgb;\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tsg.a = albedoTextureAlpha * u_smoothnessScale;\r\n\t\t#else\r\n\t\t\tsg.a = u_smoothness;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n return sg;\r\n}\r\n\r\n";
  28640. var PBRStandardLightingGLSL = "#include \"PBRUtils.glsl\"\r\n#include \"BRDF.glsl\"\r\n\r\nvec4 PBRStandardLight(in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in vec3 lightDir, in vec3 lightColor, in LayaGI gi)\r\n{\r\n\tfloat oneMinusReflectivity;\r\n\tvec3 diffuseColor;\r\n\tvec3 specularColor;\r\n\tfloat alpha;\r\n\t\r\n\tdiffuseColor = DiffuseAndSpecularFromMetallic (albedoColor.rgb, metallic, specularColor, oneMinusReflectivity);\r\n\t\r\n\tdiffuseColor = LayaPreMultiplyAlpha(diffuseColor, albedoColor.a, oneMinusReflectivity, alpha);\r\n\t\r\n\tvec4 color = LayaAirBRDF(diffuseColor, specularColor, oneMinusReflectivity, smoothness, normal, viewDir, lightDir, lightColor, gi);\r\n\tcolor.a = alpha;\r\n\treturn color;\r\n}\r\n\r\nvec4 PBRStandardDiectionLight (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in DirectionLight light, in LayaGI gi,in float shadowValue)\r\n{\r\n\tvec3 lightVec = normalize(light.direction);\r\n\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color*shadowValue, gi);\r\n}\r\n#ifdef POINTLIGHT\r\nvec4 PBRStandardPointLight (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in PointLight light, in vec3 pos, in LayaGI gi,in float shadowValue)\r\n{\r\n\tvec3 lightVec = pos-light.position;\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range);\r\n\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color*shadowValue, gi) * attenuate;\r\n}\r\n#endif\r\nvec4 PBRStandardSpotLight (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in SpotLight light, in vec3 pos, in LayaGI gi,in float shadowValue)\r\n{\r\n\tvec3 lightVec = pos - light.position;\r\n\tvec3 normalLightVec = normalize(lightVec);\r\n\tvec2 cosAngles = cos(vec2(light.spot, light.spot*0.5) * 0.5);//ConeAttenuation\r\n\tfloat dl = dot(normalize(light.direction), normalLightVec);\r\n\tdl *= smoothstep(cosAngles[0], cosAngles[1], dl);\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range) * dl;\r\n\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color*shadowValue, gi) * attenuate;\r\n\t\r\n}\r\n\r\n//vec4 PBRStandardSpotLight1 (in vec4 albedoColor, in float metallic, in float smoothness, in vec3 normal, in vec3 viewDir, in SpotLight light, in vec3 pos, in LayaGI gi)\r\n//{\r\n//\tvec4 lightCoord = u_SpotLightMatrix * vec4(pos, 1.0);\r\n//\t\r\n//\tfloat distance = dot(lightCoord, lightCoord);\r\n//\tfloat attenuate = (lightCoord.z < 0.0) ? texture2D(u_RangeTexture, vec2(distance)).w : 0.0;\r\n//\t//float attenuate = (lightCoord.z < 0.0) ? texture2D(u_AngleTexture, vec2(lightCoord.x / lightCoord.w + 0.5, lightCoord.y / lightCoord.w + 0.5)).r * texture2D(u_RangeTexture, vec2(distance)).w : 0.0;\r\n//\t//vec2 _uv = vec2(pos.x * 180.0/(2.0 * pos.z) + 0.5, pos.y * 180.0/(2.0 * pos.z) + 0.5);\r\n//\tvec3 lightVec = normalize(pos - light.position);\r\n//\treturn PBRStandardLight(albedoColor, metallic, smoothness, normal, viewDir, lightVec, light.color, gi) * attenuate;\r\n//}\r\n\r\nvec2 MetallicGloss(in float albedoTextureAlpha, in vec2 uv0)\r\n{\r\n\tvec2 mg;\r\n\t\r\n\t#ifdef METALLICGLOSSTEXTURE\r\n\t\tvec4 metallicGlossTextureColor = texture2D(u_MetallicGlossTexture, uv0);\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tmg.r = metallicGlossTextureColor.r;\r\n\t\t\tmg.g = albedoTextureAlpha;\r\n\t\t#else\r\n\t\t mg = metallicGlossTextureColor.ra;\r\n\t\t#endif\r\n\t\tmg.g *= u_smoothnessScale;\r\n\t#else\r\n\t\tmg.r = u_metallic;\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tmg.g = albedoTextureAlpha * u_smoothnessScale;\r\n\t\t#else\r\n\t\t\tmg.g = u_smoothness;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\treturn mg;\r\n}\r\n\r\n";
  28641. var PBRUtilsGLSL = "\r\nvec3 UnpackScaleNormal(in vec2 uv0)\r\n{\r\n\t#ifdef NORMALTEXTURE\r\n\t\tvec3 normalT;\r\n\t\tvec4 normalMapSample = texture2D(u_NormalTexture, uv0);\r\n\t\tnormalT.x = 2.0 * normalMapSample.x - 1.0;\r\n\t\tnormalT.y = 1.0 - 2.0 * normalMapSample.y;\r\n\t\tnormalT.xy *= u_normalScale;\r\n\t\tnormalT.z = sqrt(1.0 - clamp(dot(normalT.xy, normalT.xy), 0.0, 1.0));\r\n\t\t\r\n\t\tvec3 T = normalize(v_Tangent);\r\n\t\tvec3 B = normalize(v_Binormal);\r\n\t\tvec3 N = normalize(v_Normal);\r\n\t\tmat3 TBN = mat3(T, B, N);\r\n\t\t\r\n\t\tvec3 bumpedNormal = TBN * normalize(normalT);\r\n\t\treturn bumpedNormal;\r\n\t#else\r\n\t\treturn normalize(v_Normal);\r\n\t#endif\r\n}\r\n\r\nvec4 DielectricSpecularColor = vec4(0.220916301, 0.220916301, 0.220916301, 1.0 - 0.220916301);\r\n\r\nfloat PI = 3.14159265359;\r\n\r\nvec3 FresnelTerm (in vec3 F0, in float cosA)\r\n{\r\n\treturn F0 + (vec3(1.0) - F0) * pow(1.0 - cosA, 5.0);\r\n}\r\n\r\nvec3 FresnelLerp (in vec3 F0, in vec3 F90, float cosA)\r\n{\r\n float t = pow(1.0 - cosA, 5.0);\r\n return mix(F0, F90, t);\r\n}\r\n\r\nfloat PerceptualRoughnessToRoughness(in float perceptualRoughness)\r\n{\r\n\treturn perceptualRoughness * perceptualRoughness;\r\n}\r\n\r\nfloat PerceptualRoughnessToSpecularPower(in float perceptualRoughness)\r\n{\r\n\tfloat m = PerceptualRoughnessToRoughness(perceptualRoughness);\r\n\tfloat sq = max(0.0001, m * m);\r\n\tfloat n = (2.0 / sq) - 2.0;\r\n\tn = max(n, 0.0001);\r\n\treturn n;\r\n}\r\n\r\nfloat RoughnessToPerceptualRoughness(in float roughness)\r\n{\r\n\treturn sqrt(roughness);\r\n}\r\n\r\nfloat SmoothnessToRoughness(in float smoothness)\r\n{\r\n\treturn (1.0 - smoothness) * (1.0 - smoothness);\r\n}\r\n\r\nfloat SmoothnessToPerceptualRoughness(in float smoothness)\r\n{\r\n\treturn (1.0 - smoothness);\r\n}\r\n\r\nvec3 SafeNormalize(in vec3 inVec)\r\n{\r\n\tfloat dp3 = max(0.001,dot(inVec,inVec));\r\n\treturn inVec * (1.0 / sqrt(dp3));\r\n}\r\n\r\nfloat DisneyDiffuse(in float NdotV, in float NdotL, in float LdotH, in float perceptualRoughness)\r\n{\r\n\tfloat fd90 = 0.5 + 2.0 * LdotH * LdotH * perceptualRoughness;\r\n\tfloat lightScatter\t= (1.0 + (fd90 - 1.0) * pow(1.0 - NdotL,5.0));\r\n\tfloat viewScatter\t= (1.0 + (fd90 - 1.0) * pow(1.0 - NdotV,5.0));\r\n\r\n\treturn lightScatter * viewScatter;\r\n}\r\n\r\nfloat SmithJointGGXVisibilityTerm (float NdotL, float NdotV, float roughness)\r\n{\r\n\tfloat a = roughness;\r\n\tfloat lambdaV = NdotL * (NdotV * (1.0 - a) + a);\r\n\tfloat lambdaL = NdotV * (NdotL * (1.0 - a) + a);\r\n\r\n\treturn 0.5 / (lambdaV + lambdaL + 0.00001);\r\n}\r\n\r\nfloat GGXTerm (float NdotH, float roughness)\r\n{\r\n\tfloat a2 = roughness * roughness;\r\n\tfloat d = (NdotH * a2 - NdotH) * NdotH + 1.0;\r\n\treturn 0.31830988618 * a2 / (d * d + 0.0000001);\r\n}\r\n\r\nfloat OneMinusReflectivityFromMetallic(in float metallic)\r\n{\r\n\tfloat oneMinusDielectricSpec = DielectricSpecularColor.a;\r\n\treturn oneMinusDielectricSpec - metallic * oneMinusDielectricSpec;\r\n}\r\n\r\nfloat SpecularStrength(vec3 specular)\r\n{\r\n //(SHADER_TARGET < 30)return specular.r; \r\n return max (max (specular.r, specular.g), specular.b);\r\n}\r\n\r\nvec3 DiffuseAndSpecularFromMetallic(in vec3 diffuseColor, in float metallic, out vec3 specularColor, out float oneMinusReflectivity)\r\n{\r\n\tspecularColor = mix(DielectricSpecularColor.rgb, diffuseColor, metallic);\r\n\toneMinusReflectivity = OneMinusReflectivityFromMetallic(metallic);\r\n\treturn diffuseColor * oneMinusReflectivity;\r\n}\r\n\r\nvec3 EnergyConservationBetweenDiffuseAndSpecular(in vec3 diffuseColor, in vec3 specularColor, out float oneMinusReflectivity)\r\n{\r\n\toneMinusReflectivity = 1.0 - SpecularStrength(specularColor);\r\n\treturn diffuseColor * oneMinusReflectivity;\r\n}\r\n\r\nvec4 Occlusion(in vec2 uv0){\r\n\t#ifdef OCCLUSIONTEXTURE\r\n\t\tvec4 occlusionTextureColor = texture2D(u_OcclusionTexture, uv0);\r\n\t\tfloat occ = occlusionTextureColor.g;\r\n\t\tfloat oneMinusT = 1.0 - u_occlusionStrength;\r\n\t\tfloat lerpOneTo = oneMinusT + occ * u_occlusionStrength;\r\n\t\treturn occlusionTextureColor * lerpOneTo;\r\n\t#else\r\n\t\treturn vec4(1.0);\r\n\t#endif\r\n}\r\n\r\nvec2 ParallaxOffset(in vec3 viewDir){\r\n\t#ifdef PARALLAXTEXTURE\r\n\t\tfloat h = texture2D(u_ParallaxTexture, v_Texcoord0).g;\r\n\t\th = h * u_parallaxScale - u_parallaxScale / 2.0;\r\n\t\tvec3 v = viewDir;\r\n\t\tv.z += 0.42;\r\n\t\tvec2 offset = h * (v.xy / v.z);\r\n\t\treturn v_Texcoord0 + offset;\r\n\t#else\r\n\t\treturn v_Texcoord0;\r\n\t#endif\r\n}\r\n\r\nvec3 ReflectCubeMap(in vec3 viewDir, in vec3 normal){\r\n\t#ifdef REFLECTMAP\r\n\t\tvec3 incident = -viewDir;\r\n\t\tvec3 reflectionVector = reflect(incident, normal);\r\n\t\tvec3 reflectionColor = textureCube(u_ReflectTexture, vec3(-reflectionVector.x, reflectionVector.yz)).rgb;\r\n\t\treturn reflectionColor * u_ReflectIntensity;\r\n\t#else\r\n\t\treturn vec3(0.0);\r\n\t#endif\r\n}\r\n\r\n\r\n\r\nvec3 LayaPreMultiplyAlpha(vec3 diffColor, float alpha, float oneMinusReflectivity, out float outModifiedAlpha)\r\n{\r\n\t#ifdef ALPHAPREMULTIPLY\r\n\t\tdiffColor *= alpha;\r\n\t\toutModifiedAlpha = 1.0 - oneMinusReflectivity + alpha * oneMinusReflectivity;\r\n\t#else\r\n\t\toutModifiedAlpha = alpha;\r\n\t#endif\r\n\treturn diffColor;\r\n}\r\n\r\n";
  28642. var PBRSpecularPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec3 v_PositionWorld;\r\n\r\nuniform vec3 u_AmbientColor;\r\nuniform vec4 u_AlbedoColor;\r\nuniform vec4 u_SpecularColor;\r\n\r\n#ifdef ALBEDOTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n#endif\r\n#ifdef SPECULARTEXTURE\r\n\tuniform sampler2D u_SpecularTexture;\r\n#endif\r\n#ifdef NORMALTEXTURE\r\n\tuniform sampler2D u_NormalTexture;\r\n\tuniform float u_normalScale;\r\n#endif\r\n#ifdef PARALLAXTEXTURE\r\n\tuniform sampler2D u_ParallaxTexture;\r\n\tuniform float u_parallaxScale;\r\n#endif\r\n#ifdef OCCLUSIONTEXTURE\r\n\tuniform sampler2D u_OcclusionTexture;\r\n\tuniform float u_occlusionStrength;\r\n#endif\r\n#ifdef EMISSION\r\n\t#ifdef EMISSIONTEXTURE\r\n\t\tuniform sampler2D u_EmissionTexture;\r\n\t#endif\r\n\tuniform vec4 u_EmissionColor;\r\n#endif\r\n#ifdef REFLECTMAP\r\n\tuniform samplerCube u_ReflectTexture;\r\n\tuniform float u_ReflectIntensity;\r\n#endif\r\n\r\nuniform float u_AlphaTestValue;\r\nuniform float u_metallic;\r\nuniform float u_smoothness;\r\nuniform float u_smoothnessScale;\r\n\r\n\r\n\r\n#include \"Lighting.glsl\";\r\n#include \"PBRSpecularLighting.glsl\"\r\n#include \"ShadowHelper.glsl\"\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n\t#if defined(SHADOWMAP_PSSM2)||defined(SHADOWMAP_PSSM3)\r\n\t\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\t\tvarying vec4 v_lightMVPPos;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef LEGACYSINGLELIGHTING\r\n\t#ifdef DIRECTIONLIGHT\r\n\t\tuniform DirectionLight u_DirectionLight;\r\n\t#endif\r\n\t#ifdef POINTLIGHT\r\n\t\tuniform PointLight u_PointLight;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT\r\n\t\tuniform SpotLight u_SpotLight;\r\n\t#endif\r\n#else\r\n\t\tuniform mat4 u_View;\r\n\t\tuniform vec4 u_ProjectionParams;\r\n\t\tuniform vec4 u_Viewport;\r\n\t\tuniform int u_DirationLightCount;\r\n\t\tuniform sampler2D u_LightBuffer;\r\n\t\tuniform sampler2D u_LightClusterBuffer;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\tuniform vec3 u_FogColor;\r\n#endif\r\n\r\nvoid main_castShadow()\r\n{\r\n\tgl_FragColor=packDepth(v_posViewZ);\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tfloat alpha = texture2D(u_AlbedoTexture,v_Texcoord0).w;\r\n\t\tif( alpha < u_AlphaTestValue )\r\n\t\t{\r\n\t\t\tdiscard;\r\n\t\t}\r\n\t#endif\r\n}\r\n\r\nvoid main_normal()\r\n{\t\r\n\tvec3 viewDir = normalize(v_ViewDir);\r\n\t\r\n\tvec2 uv0 = ParallaxOffset(viewDir);\r\n\t\r\n\tvec4 sg;\r\n\tvec4 albedoColor;\r\n\t#ifdef ALBEDOTEXTURE\r\n\t\tvec4 albedoTextureColor = texture2D(u_AlbedoTexture, uv0);\r\n\t\talbedoColor = albedoTextureColor * u_AlbedoColor;\r\n\t\tsg = SpecularGloss(albedoTextureColor.a, uv0);\r\n\t#else\r\n\t\talbedoColor = u_AlbedoColor;\r\n\t\tsg = SpecularGloss(1.0, uv0);\r\n\t#endif\r\n\t\r\n\t#ifdef ALPHATEST\r\n\t\tif(albedoColor.a < u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n \r\n\tvec3 normal = UnpackScaleNormal(uv0);\r\n\t\r\n\tLayaGI gi;\r\n\tgi.diffuse = u_AmbientColor * Occlusion(uv0).rgb;\r\n\tgi.specular = ReflectCubeMap(viewDir, normal);\r\n\t\r\n\t//float a = (sg.r+sg.g+sg.b) / 3.0;\r\n \tfloat shadowValue = 1.0;\r\n\t#ifdef RECEIVESHADOW\r\n\t\t\r\n\t\t#ifdef SHADOWMAP_PSSM3\r\n\t\t\tshadowValue = getShadowPSSM3( u_shadowMap1,u_shadowMap2,u_shadowMap3,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\t#ifdef SHADOWMAP_PSSM2\r\n\t\t\tshadowValue = getShadowPSSM2( u_shadowMap1,u_shadowMap2,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif \r\n\t\t#ifdef SHADOWMAP_PSSM1\r\n\t\t\tshadowValue = getShadowPSSM1( u_shadowMap1,v_lightMVPPos,u_shadowPSSMDistance,u_shadowPCFoffset,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t#endif\r\n\tvec4 color = vec4(0.0);\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tcolor += PBRSpecularDiectionLight(albedoColor, sg.rgb, sg.a, normal, viewDir, u_DirectionLight, gi,shadowValue);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tcolor.a = 0.0;\r\n\t\t\tcolor += PBRSpecularPointLight(albedoColor, sg.rgb, sg.a, normal, viewDir, u_PointLight, v_PositionWorld, gi,shadowValue);\r\n\t\t#endif\r\n\t\t\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tcolor.a = 0.0;\r\n\t\t\tcolor += PBRSpecularSpotLight(albedoColor, sg.rgb, sg.a, normal, viewDir, u_SpotLight, v_PositionWorld, gi,shadowValue);\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t{\r\n\t\t\t\tif(i >= u_DirationLightCount)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tDirectionLight directionLight = getDirectionLight(u_LightBuffer,i);\r\n\t\t\t\tcolor.a = 0.0;\r\n\t\t\t\tcolor +=PBRSpecularDiectionLight(albedoColor, sg.rgb, sg.a, normal, viewDir, directionLight, gi,shadowValue);\r\n\t\t\t}\r\n\t\t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tivec4 clusterInfo =getClusterInfo(u_LightClusterBuffer,u_View,u_Viewport, v_PositionWorld,gl_FragCoord,u_ProjectionParams);\r\n\t\t\t#ifdef POINTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.x)//PointLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tPointLight pointLight = getPointLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tcolor.a = 0.0;\r\n\t\t\t\t\tcolor +=PBRSpecularPointLight(albedoColor, sg.rgb, sg.a, normal, viewDir, pointLight, v_PositionWorld, gi,shadowValue);\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#ifdef SPOTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.y)//SpotLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tSpotLight spotLight = getSpotLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tcolor.a = 0.0;\r\n\t\t\t\t\tcolor += PBRSpecularSpotLight(albedoColor, sg.rgb, sg.a, normal, viewDir, spotLight, v_PositionWorld, gi,shadowValue);\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t#ifdef REFLECTMAP\r\n\t \tcolor += LayaAirSpecularReflect(albedoColor,sg.rgb,sg.a,gi);\r\n\t#endif\r\n\r\n\t#ifdef EMISSION\r\n\t\tvec4 emissionColor = u_EmissionColor;\r\n\t\t#ifdef EMISSIONTEXTURE\r\n\t\t\temissionColor *= texture2D(u_EmissionTexture, uv0);\r\n\t\t#endif\r\n\t\tcolor.rgb += emissionColor.rgb;\r\n\t#endif\r\n\r\n\tgl_FragColor = color;\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact = clamp((1.0 / gl_FragCoord.w - u_FogStart) / u_FogRange, 0.0, 1.0);\r\n\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, u_FogColor, lerpFact);\r\n\t#endif\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\t\t\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif \r\n}\r\n\r\n";
  28643. var PBRSpecularVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\r\nattribute vec4 a_Tangent0;\r\nattribute vec2 a_Texcoord0;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n#endif\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\nuniform vec3 u_CameraPos;\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec3 v_PositionWorld;\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n #ifdef SHADOWMAP_PSSM1 \r\n\t varying vec4 v_lightMVPPos;\r\n\t uniform mat4 u_lightShadowVP[4];\r\n #endif\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\nvoid main_castShadow()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\tposition=skinTransform*a_Position;\r\n\t#else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t \r\n\t//TODO没考虑UV动画呢\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tv_Texcoord0 = a_Texcoord0;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n\tv_posViewZ = gl_Position.z;\r\n}\r\n\r\nvoid main_normal()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\tposition=skinTransform*a_Position;\r\n\t#else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)||defined(REFLECTMAP)\r\n\t\tmat4 worldMat;\r\n\t\t#ifdef GPU_INSTANCE\r\n\t\t\tworldMat = a_WorldMat;\r\n\t\t#else\r\n\t\t\tworldMat = u_WorldMat;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(REFLECTMAP)\r\n\t\tmat3 worldInvMat;\r\n\t\t#ifdef BONE\r\n\t\t\tworldInvMat=inverse(mat3(worldMat*skinTransform));\r\n\t\t#else\r\n\t\t\tworldInvMat=inverse(mat3(worldMat));\r\n\t\t#endif \r\n\t\tv_Normal=a_Normal*worldInvMat;\r\n\t\t#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))\r\n\t\t\tv_Tangent=a_Tangent0.xyz*worldInvMat;\r\n\t\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)||defined(REFLECTMAP)\r\n\t\tv_PositionWorld=(worldMat*position).xyz;\r\n\t#endif\r\n\t\r\n \r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(REFLECTMAP)\r\n\t\tv_ViewDir=u_CameraPos-v_PositionWorld;\r\n\t#endif\r\n\r\n\t#ifdef TILINGOFFSET\r\n\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t#else\r\n\t\tv_Texcoord0=a_Texcoord0;\r\n\t#endif\r\n \r\n\t#ifdef RECEIVESHADOW\r\n\t\tv_posViewZ = gl_Position.w;\r\n\t\t#ifdef SHADOWMAP_PSSM1 \r\n\t\t\tv_lightMVPPos = u_lightShadowVP[0] * vec4(v_PositionWorld,1.0);\r\n\t\t#endif\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif\r\n}";
  28644. var PBRStandardPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec3 v_PositionWorld;\r\n\r\nuniform vec3 u_AmbientColor;\r\nuniform vec4 u_AlbedoColor;\r\n\r\n#ifdef ALBEDOTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n#endif\r\n#ifdef METALLICGLOSSTEXTURE\r\n\tuniform sampler2D u_MetallicGlossTexture;\r\n#endif\r\n#ifdef NORMALTEXTURE\r\n\tuniform sampler2D u_NormalTexture;\r\n\tuniform float u_normalScale;\r\n#endif\r\n#ifdef PARALLAXTEXTURE\r\n\tuniform sampler2D u_ParallaxTexture;\r\n\tuniform float u_parallaxScale;\r\n#endif\r\n#ifdef OCCLUSIONTEXTURE\r\n\tuniform sampler2D u_OcclusionTexture;\r\n\tuniform float u_occlusionStrength;\r\n#endif\r\n#ifdef EMISSION\r\n\t#ifdef EMISSIONTEXTURE\r\n\t\tuniform sampler2D u_EmissionTexture;\r\n\t#endif\r\n\tuniform vec4 u_EmissionColor;\r\n#endif\r\n#ifdef REFLECTMAP\r\n\tuniform samplerCube u_ReflectTexture;\r\n\tuniform float u_ReflectIntensity;\r\n#endif\r\n\r\nuniform float u_AlphaTestValue;\r\nuniform float u_metallic;\r\nuniform float u_smoothness;\r\nuniform float u_smoothnessScale;\r\n\r\n\r\n\r\n\r\n#include \"Lighting.glsl\";\r\n#include \"PBRStandardLighting.glsl\"\r\n#include \"ShadowHelper.glsl\"\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n\t#if defined(SHADOWMAP_PSSM2)||defined(SHADOWMAP_PSSM3)\r\n\t\tuniform mat4 u_lightShadowVP[4];\r\n\t#endif\r\n\t#ifdef SHADOWMAP_PSSM1 \r\n\t\tvarying vec4 v_lightMVPPos;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef LEGACYSINGLELIGHTING\r\n\t#ifdef DIRECTIONLIGHT\r\n\t\tuniform DirectionLight u_DirectionLight;\r\n\t#endif\r\n\t#ifdef POINTLIGHT\r\n\t\tuniform PointLight u_PointLight;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT\r\n\t\tuniform SpotLight u_SpotLight;\r\n\t#endif\r\n#else\r\n\t\tuniform mat4 u_View;\r\n\t\tuniform vec4 u_ProjectionParams;\r\n\t\tuniform vec4 u_Viewport;\r\n\t\tuniform int u_DirationLightCount;\r\n\t\tuniform sampler2D u_LightBuffer;\r\n\t\tuniform sampler2D u_LightClusterBuffer;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\tuniform vec3 u_FogColor;\r\n#endif\r\n\r\nvoid main_castShadow()\r\n{\r\n\tgl_FragColor=packDepth(v_posViewZ);\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tfloat alpha = texture2D(u_AlbedoTexture,v_Texcoord0).w;\r\n\t\tif( alpha < u_AlphaTestValue )\r\n\t\t{\r\n\t\t\tdiscard;\r\n\t\t}\r\n\t#endif\r\n}\r\n\r\nvoid main_normal()\r\n{\t\r\n\tvec3 viewDir = normalize(v_ViewDir);\r\n\t\r\n\tvec2 uv0 = ParallaxOffset(viewDir);\r\n\t\r\n\tvec2 mg;\r\n\tvec4 albedoColor;\r\n\t#ifdef ALBEDOTEXTURE\r\n\t\tvec4 abledoTextureColor = texture2D(u_AlbedoTexture, uv0);\r\n\t\talbedoColor = abledoTextureColor * u_AlbedoColor;\r\n\t\tmg = MetallicGloss(abledoTextureColor.a, uv0);\r\n\t#else\r\n\t\talbedoColor = u_AlbedoColor;\r\n\t\tmg = MetallicGloss(1.0, uv0);\r\n\t#endif\r\n\t\r\n\t#ifdef ALPHATEST\r\n\t\tif(albedoColor.a < u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n\t\r\n\tvec3 normal = UnpackScaleNormal(uv0);\r\n \r\n\tLayaGI gi;\r\n\tgi.diffuse = u_AmbientColor * Occlusion(uv0).rgb;\r\n\tgi.specular = ReflectCubeMap(viewDir, normal);\r\n \r\n \tfloat shadowValue = 1.0;\r\n\t#ifdef RECEIVESHADOW\r\n\t\r\n\t\t#ifdef SHADOWMAP_PSSM3\r\n\t\t\tshadowValue = getShadowPSSM3( u_shadowMap1,u_shadowMap2,u_shadowMap3,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t\t#ifdef SHADOWMAP_PSSM2\r\n\t\t\tshadowValue = getShadowPSSM2( u_shadowMap1,u_shadowMap2,u_lightShadowVP,u_shadowPSSMDistance,u_shadowPCFoffset,v_PositionWorld,v_posViewZ,0.001);\r\n\t\t#endif \r\n\t\t#ifdef SHADOWMAP_PSSM1\r\n\t\t\tshadowValue = getShadowPSSM1( u_shadowMap1,v_lightMVPPos,u_shadowPSSMDistance,u_shadowPCFoffset,v_posViewZ,0.001);\r\n\t\t#endif\r\n\t#endif\r\n\r\n\tvec4 color = vec4(0.0);\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tcolor += PBRStandardDiectionLight(albedoColor, mg.r, mg.g, normal, viewDir, u_DirectionLight, gi,shadowValue);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tcolor.a = 0.0;\r\n\t\t\tcolor += PBRStandardPointLight(albedoColor, mg.r, mg.g, normal, viewDir, u_PointLight, v_PositionWorld, gi,shadowValue);\r\n\t\t#endif\r\n\t\t\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tcolor.a = 0.0;\r\n\t\t\tcolor += PBRStandardSpotLight(albedoColor, mg.r, mg.g, normal, viewDir, u_SpotLight, v_PositionWorld, gi,shadowValue);\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t{\r\n\t\t\t\tif(i >= u_DirationLightCount)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tDirectionLight directionLight = getDirectionLight(u_LightBuffer,i);\r\n\t\t\t\tcolor.a = 0.0;\r\n\t\t\t\tcolor += PBRStandardDiectionLight(albedoColor, mg.r, mg.g, normal, viewDir, directionLight, gi,shadowValue);\r\n\t\t\t}\r\n\t\t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tivec4 clusterInfo =getClusterInfo(u_LightClusterBuffer,u_View,u_Viewport, v_PositionWorld,gl_FragCoord,u_ProjectionParams);\r\n\t\t\t#ifdef POINTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.x)//PointLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tPointLight pointLight = getPointLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tcolor.a = 0.0;\r\n\t\t\t\t\tcolor += PBRStandardPointLight(albedoColor, mg.r, mg.g, normal, viewDir, pointLight, v_PositionWorld, gi,shadowValue);\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#ifdef SPOTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.y)//SpotLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tSpotLight spotLight = getSpotLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tcolor.a = 0.0;\r\n\t\t\t\t\tcolor += PBRStandardSpotLight(albedoColor, mg.r, mg.g, normal, viewDir, spotLight, v_PositionWorld, gi,shadowValue);\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t\r\n\t#ifdef REFLECTMAP\r\n\t \tcolor += LayaAirStandardReflect(albedoColor,mg.r,mg.g,gi);\r\n\t#endif\r\n\r\n\t#ifdef EMISSION\r\n\t\tvec4 emissionColor = u_EmissionColor;\r\n\t\t#ifdef EMISSIONTEXTURE\r\n\t\t\temissionColor *= texture2D(u_EmissionTexture, uv0);\r\n\t\t#endif\r\n\t\tcolor.rgb += emissionColor.rgb;\r\n\t#endif\r\n\t\r\n\t\tgl_FragColor = color;\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact = clamp((1.0 / gl_FragCoord.w - u_FogStart) / u_FogRange, 0.0, 1.0);\r\n\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, u_FogColor, lerpFact);\r\n\t#endif\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\t\t\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif \r\n}";
  28645. var PBRStandardVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\r\nattribute vec4 a_Tangent0;\r\nattribute vec2 a_Texcoord0;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n#endif\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\n\r\nuniform vec3 u_CameraPos;\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec3 v_PositionWorld;\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\nvarying float v_posViewZ;\r\n#ifdef RECEIVESHADOW\r\n #ifdef SHADOWMAP_PSSM1 \r\n\t varying vec4 v_lightMVPPos;\r\n\t uniform mat4 u_lightShadowVP[4];\r\n #endif\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\nvoid main_castShadow()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\tposition=skinTransform*a_Position;\r\n\t#else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t \r\n\t//TODO没考虑UV动画呢\r\n\t#if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t\tv_Texcoord0 = a_Texcoord0;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n\tv_posViewZ = gl_Position.z;\r\n}\r\n\r\nvoid main_normal()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\tposition=skinTransform*a_Position;\r\n\t#else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)||defined(REFLECTMAP)\r\n\t\tmat4 worldMat;\r\n\t\t#ifdef GPU_INSTANCE\r\n\t\t\tworldMat = a_WorldMat;\r\n\t\t#else\r\n\t\t\tworldMat = u_WorldMat;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(REFLECTMAP)\r\n\t\tmat3 worldInvMat;\r\n\t\t#ifdef BONE\r\n\t\t\tworldInvMat=inverse(mat3(worldMat*skinTransform));\r\n\t\t#else\r\n\t\t\tworldInvMat=inverse(mat3(worldMat));\r\n\t\t#endif \r\n\t\tv_Normal=a_Normal*worldInvMat;\r\n\t\t#if (defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))\r\n\t\t\tv_Tangent=a_Tangent0.xyz*worldInvMat;\r\n\t\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(RECEIVESHADOW)||defined(REFLECTMAP)\r\n\t\tv_PositionWorld=(worldMat*position).xyz;\r\n\t#endif\r\n\t\r\n \r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(REFLECTMAP)||defined(REFLECTMAP)\r\n\t\tv_ViewDir=u_CameraPos-v_PositionWorld;\r\n\t#endif\r\n\r\n\t#ifdef TILINGOFFSET\r\n\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t#else\r\n\t\tv_Texcoord0=a_Texcoord0;\r\n\t#endif\r\n \r\n\t#ifdef RECEIVESHADOW\r\n\t\tv_posViewZ = gl_Position.w;\r\n\t\t#ifdef SHADOWMAP_PSSM1 \r\n\t\t\tv_lightMVPPos = u_lightShadowVP[0] * vec4(v_PositionWorld,1.0);\r\n\t\t#endif\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n\r\nvoid main()\r\n{\r\n\t#ifdef CASTSHADOW\r\n\t\tmain_castShadow();\r\n\t#else\r\n\t\tmain_normal();\r\n\t#endif\r\n}";
  28646. var BloomVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_PositionTexcoord;\r\nvarying vec2 v_Texcoord0;\r\n\r\nvoid main() {\r\n\tgl_Position = vec4(a_PositionTexcoord.xy, 0.0, 1.0);\r\n\tv_Texcoord0 = a_PositionTexcoord.zw;\r\n\tgl_Position = remapGLPositionZ(gl_Position);\r\n}";
  28647. var BloomDownsample13PS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform vec4 u_MainTex_TexelSize;\r\n\r\nvoid fragDownsample13() {\r\n\tmediump vec4 color = downsampleBox13Tap(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy);\r\n\tgl_FragColor = color;\r\n}\r\n\r\nvoid main() {\r\n\tfragDownsample13();\r\n}";
  28648. var BloomDownsample4PS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform vec4 u_MainTex_TexelSize;\r\n\r\nvoid fragDownsample4() {\r\n\tmediump vec4 color = downsampleBox4Tap(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy);\r\n\tgl_FragColor = color;\r\n}\r\n\r\nvoid main() {\r\n\tfragDownsample4();\r\n}";
  28649. var BloomPrefilter13PS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_AutoExposureTex;\r\nuniform vec4 u_MainTex_TexelSize;\r\nuniform vec4 u_Threshold; // x: threshold value (linear), y: threshold - knee, z: knee * 2, w: 0.25 / knee\r\nuniform vec4 u_Params; // x: clamp, yzw: unused\r\n\r\nmediump vec4 prefilter(mediump vec4 color, vec2 uv) {\r\n\tmediump float autoExposure = texture2D(u_AutoExposureTex, uv).r;\r\n\tcolor *= autoExposure;\r\n\tcolor = min(vec4(u_Params.x), color); // clamp to max\r\n\tcolor = quadraticThreshold(color, u_Threshold.x, u_Threshold.yzw);\r\n\treturn color;\r\n}\r\n\r\nvoid fragPrefilter13() {\r\n\tmediump vec4 color = downsampleBox13Tap(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy);\r\n\tgl_FragColor = prefilter(safeHDR(color), v_Texcoord0);\r\n}\r\n\r\nvoid main() {\r\n\tfragPrefilter13();\r\n}";
  28650. var BloomPrefilter4PS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_AutoExposureTex;\r\nuniform vec4 u_MainTex_TexelSize;\r\nuniform vec4 u_Threshold; // x: threshold value (linear), y: threshold - knee, z: knee * 2, w: 0.25 / knee\r\nuniform vec4 u_Params; // x: clamp, yzw: unused\r\n\r\nmediump vec4 prefilter(mediump vec4 color, vec2 uv) {\r\n\tmediump float autoExposure = texture2D(u_AutoExposureTex, uv).r;\r\n\tcolor *= autoExposure;\r\n\tcolor = min(vec4(u_Params.x), color); // clamp to max\r\n\tcolor = quadraticThreshold(color, u_Threshold.x, u_Threshold.yzw);\r\n\treturn color;\r\n}\r\n\r\nvoid fragPrefilter4() {\r\n\tmediump vec4 color = downsampleBox4Tap(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy);\r\n\tgl_FragColor = prefilter(safeHDR(color), v_Texcoord0);\r\n}\r\n\r\nvoid main() {\r\n\tfragPrefilter4();\r\n}";
  28651. var BloomUpsampleBoxPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_BloomTex;\r\n\r\nuniform vec4 u_MainTex_TexelSize;\r\nuniform float u_SampleScale;\r\n\r\nmediump vec4 combine(mediump vec4 bloom, vec2 uv) {\r\n\tmediump vec4 color = texture2D(u_BloomTex, uv);\r\n\treturn bloom + color;\r\n}\r\n\r\nvoid fragUpsampleBox() {\r\n\tmediump vec4 bloom = upsampleBox(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy, vec4(u_SampleScale));\r\n\tgl_FragColor = combine(bloom, v_Texcoord0);\r\n}\r\n\r\nvoid main() {\r\n\tfragUpsampleBox();\r\n}";
  28652. var BloomUpsampleTentPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_BloomTex;\r\n\r\nuniform vec4 u_MainTex_TexelSize;\r\nuniform float u_SampleScale;\r\n\r\nmediump vec4 combine(mediump vec4 bloom, vec2 uv) {\r\n\tmediump vec4 color = texture2D(u_BloomTex, uv);\r\n\treturn bloom + color;\r\n}\r\n\r\nvoid fragUpsampleTent() {\r\n\tmediump vec4 bloom = upsampleTent(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy, vec4(u_SampleScale));\r\n\tgl_FragColor = combine(bloom, v_Texcoord0);\r\n}\r\n\r\nvoid main() {\r\n\tfragUpsampleTent();\r\n}";
  28653. var ColorsGLSL = "#include \"StdLib.glsl\";\r\n\r\n#define EPSILON 1.0e-4\r\n\r\n// Quadratic color thresholding\r\n// curve = (threshold - knee, knee * 2, 0.25 / knee)\r\nmediump vec4 quadraticThreshold(mediump vec4 color, mediump float threshold, mediump vec3 curve) {\r\n\t// Pixel brightness\r\n\tmediump float br = max3(color.r, color.g, color.b);\r\n\r\n\t// Under-threshold part: quadratic curve\r\n\tmediump float rq = clamp(br - curve.x, 0.0, curve.y);\r\n\trq = curve.z * rq * rq;\r\n\r\n\t// Combine and apply the brightness response curve.\r\n\tcolor *= max(rq, br - threshold) / max(br, EPSILON);\r\n\r\n\treturn color;\r\n}\r\n\r\n\r\n\r\n//\r\n// sRGB transfer functions\r\n// Fast path ref: http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1\r\n//\r\nmediump vec3 sRGBToLinear(mediump vec3 c) {\r\n\t#ifdef USE_VERY_FAST_SRGB\r\n\t\treturn c * c;\r\n\t#elif defined(USE_FAST_SRGB)\r\n\t\treturn c * (c * (c * 0.305306011 + 0.682171111) + 0.012522878);\r\n\t#else\r\n\t\tmediump vec3 linearRGBLo = c / 12.92;\r\n\t\tmediump vec3 power=vec3(2.4, 2.4, 2.4);\r\n\t\tmediump vec3 linearRGBHi = positivePow((c + 0.055) / 1.055, power);\r\n\t\tmediump vec3 linearRGB =vec3((c.r<=0.04045) ? linearRGBLo.r : linearRGBHi.r,(c.g<=0.04045) ? linearRGBLo.g : linearRGBHi.g,(c.b<=0.04045) ? linearRGBLo.b : linearRGBHi.b);\r\n\t\treturn linearRGB;\r\n\t#endif\r\n}\r\n\r\nmediump vec4 sRGBToLinear(mediump vec4 c){\r\n return vec4(sRGBToLinear(c.rgb), c.a);\r\n}\r\n\r\n\r\n\r\nmediump vec3 linearToSRGB(mediump vec3 c) {\r\n\t#ifdef USE_VERY_FAST_SRGB\r\n\t\treturn sqrt(c);\r\n\t#elif defined(USE_FAST_SRGB)\r\n\t\treturn max(1.055 * PositivePow(c, 0.416666667) - 0.055, 0.0);\r\n\t#else\r\n\t\tmediump vec3 sRGBLo = c * 12.92;\r\n\t\tmediump vec3 power=vec3(1.0 / 2.4, 1.0 / 2.4, 1.0 / 2.4);\r\n\t\tmediump vec3 sRGBHi = (positivePow(c, power) * 1.055) - 0.055;\r\n\t\tmediump vec3 sRGB =vec3((c.r<=0.0031308) ? sRGBLo.r : sRGBHi.r,(c.g<=0.0031308) ? sRGBLo.g : sRGBHi.g,(c.b<=0.0031308) ? sRGBLo.b : sRGBHi.b);\r\n\t\treturn sRGB;\r\n\t#endif\r\n}\r\n\r\nmediump vec4 linearToSRGB(mediump vec4 c){\r\n return vec4(linearToSRGB(c.rgb), c.a);\r\n}";
  28654. var CompositePS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_BloomTex;\r\n\r\nuniform sampler2D u_AutoExposureTex;\r\nuniform sampler2D u_Bloom_DirtTex;\r\nuniform vec4 u_BloomTex_TexelSize;\r\nuniform vec4 u_Bloom_DirtTileOffset; // xy: tiling, zw: offset\r\nuniform mediump vec3 u_Bloom_Settings;// x: sampleScale, y: intensity, z: dirt intensity\r\nuniform mediump vec3 u_Bloom_Color;\r\n\r\nvoid main() {\r\n\tmediump float autoExposure = texture2D(u_AutoExposureTex, v_Texcoord0).r;\r\n\tmediump vec4 color=vec4(0.0);\r\n\tcolor = texture2D(u_MainTex, v_Texcoord0);\r\n\t\r\n\tcolor = sRGBToLinear(color);\r\n\tcolor.rgb *= autoExposure;\r\n\t\r\n\t#if defined(BLOOM)||defined(BLOOM_LOW)\r\n\t\t#ifdef BLOOM\r\n\t\t\tmediump vec4 bloom = upsampleTent(u_BloomTex, v_Texcoord0, u_BloomTex_TexelSize.xy, vec4(u_Bloom_Settings.x));\r\n\t\t#else\r\n\t\t\tmediump vec4 bloom = upsampleBox(u_BloomTex, v_Texcoord0, u_BloomTex_TexelSize.xy, vec4(u_Bloom_Settings.x));\r\n\t\t#endif\r\n\r\n\t\t// UVs should be Distort(uv * u_Bloom_DirtTileOffset.xy + u_Bloom_DirtTileOffset.zw)\r\n\t\t// but considering we use a cover-style scale on the dirt texture the difference\r\n\t\t// isn't massive so we chose to save a few ALUs here instead in case lens distortion\r\n\t\t// is active\r\n\t\tmediump vec4 dirt =vec4(texture2D(u_Bloom_DirtTex, v_Texcoord0 * u_Bloom_DirtTileOffset.xy + u_Bloom_DirtTileOffset.zw).rgb, 0.0);\r\n\r\n\t\t// Additive bloom (artist friendly)\r\n\t\tbloom *= u_Bloom_Settings.y;\r\n\t\tdirt *= u_Bloom_Settings.z;\r\n\t\tmediump vec4 bloomColor=vec4(u_Bloom_Color, 1.0);\r\n\t\tcolor += bloom * bloomColor;\r\n\t\tcolor += dirt * bloom;\r\n\t#endif\r\n\t\r\n\tmediump vec4 finalColor = color;\r\n\tfinalColor = linearToSRGB(finalColor);\r\n\t//finalColor.rgb = Dither(finalColor.rgb, v_Texcoord0);//TODO:抖动\r\n\tgl_FragColor = finalColor;\r\n}";
  28655. var CompositeVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_PositionTexcoord;\r\nvarying vec2 v_Texcoord0;\r\n\r\nvoid main() {\r\n\tgl_Position = vec4(a_PositionTexcoord.xy, 0.0, 1.0);\r\n\tv_Texcoord0 = a_PositionTexcoord.zw;\r\n\tgl_Position = remapGLPositionZ(gl_Position);\r\n}";
  28656. var SamplingGLSL = "// Better, temporally stable box filtering\r\n// [Jimenez14] http://goo.gl/eomGso\r\n// . . . . . . .\r\n// . A . B . C .\r\n// . . D . E . .\r\n// . F . G . H .\r\n// . . I . J . .\r\n// . K . L . M .\r\n// . . . . . . .\r\nmediump vec4 downsampleBox13Tap(sampler2D tex, vec2 uv, vec2 texelSize)\r\n{\r\n mediump vec4 A = texture2D(tex, uv + texelSize * vec2(-1.0, -1.0));\r\n mediump vec4 B = texture2D(tex, uv + texelSize * vec2( 0.0, -1.0));\r\n mediump vec4 C = texture2D(tex, uv + texelSize * vec2( 1.0, -1.0));\r\n mediump vec4 D = texture2D(tex, uv + texelSize * vec2(-0.5, -0.5));\r\n mediump vec4 E = texture2D(tex, uv + texelSize * vec2( 0.5, -0.5));\r\n mediump vec4 F = texture2D(tex, uv + texelSize * vec2(-1.0, 0.0));\r\n mediump vec4 G = texture2D(tex, uv);\r\n mediump vec4 H = texture2D(tex, uv + texelSize * vec2( 1.0, 0.0));\r\n mediump vec4 I = texture2D(tex, uv + texelSize * vec2(-0.5, 0.5));\r\n mediump vec4 J = texture2D(tex, uv + texelSize * vec2( 0.5, 0.5));\r\n mediump vec4 K = texture2D(tex, uv + texelSize * vec2(-1.0, 1.0));\r\n mediump vec4 L = texture2D(tex, uv + texelSize * vec2( 0.0, 1.0));\r\n mediump vec4 M = texture2D(tex, uv + texelSize * vec2( 1.0, 1.0));\r\n\r\n\tmediump vec2 scale= vec2(0.5, 0.125);\r\n mediump vec2 div = (1.0 / 4.0) * scale;\r\n\r\n mediump vec4 o = (D + E + I + J) * div.x;\r\n o += (A + B + G + F) * div.y;\r\n o += (B + C + H + G) * div.y;\r\n o += (F + G + L + K) * div.y;\r\n o += (G + H + M + L) * div.y;\r\n\r\n return o;\r\n}\r\n\r\n// Standard box filtering\r\nmediump vec4 downsampleBox4Tap(sampler2D tex, vec2 uv, vec2 texelSize)\r\n{\r\n vec4 d = texelSize.xyxy * vec4(-1.0, -1.0, 1.0, 1.0);\r\n\r\n mediump vec4 s = texture2D(tex, uv + d.xy);\r\n s += texture2D(tex, uv + d.zy);\r\n s += texture2D(tex, uv + d.xw);\r\n s += texture2D(tex, uv + d.zw);\r\n\r\n return s * (1.0 / 4.0);\r\n}\r\n\r\n// 9-tap bilinear upsampler (tent filter)\r\n// . . . . . . .\r\n// . 1 . 2 . 1 .\r\n// . . . . . . .\r\n// . 2 . 4 . 2 .\r\n// . . . . . . .\r\n// . 1 . 2 . 1 .\r\n// . . . . . . .\r\nmediump vec4 upsampleTent(sampler2D tex, vec2 uv, vec2 texelSize, vec4 sampleScale)\r\n{\r\n vec4 d = texelSize.xyxy * vec4(1.0, 1.0, -1.0, 0.0) * sampleScale;\r\n\r\n mediump vec4 s = texture2D(tex, uv - d.xy);\r\n s += texture2D(tex, uv - d.wy) * 2.0;\r\n s += texture2D(tex, uv - d.zy);\r\n\r\n s += texture2D(tex, uv + d.zw) * 2.0;\r\n s += texture2D(tex, uv) * 4.0;\r\n s += texture2D(tex,\tuv + d.xw) * 2.0;\r\n\r\n s += texture2D(tex, uv + d.zy);\r\n s += texture2D(tex, uv + d.wy) * 2.0;\r\n s += texture2D(tex, uv + d.xy);\r\n\r\n return s * (1.0 / 16.0);\r\n}\r\n\r\n// Standard box filtering\r\nmediump vec4 upsampleBox(sampler2D tex, vec2 uv, vec2 texelSize, vec4 sampleScale)\r\n{\r\n vec4 d = texelSize.xyxy * vec4(-1.0, -1.0, 1.0, 1.0) * 0.5 * sampleScale;\r\n\r\n mediump vec4 s = texture2D(tex, uv + d.xy);\r\n s += texture2D(tex, uv + d.zy);\r\n s += texture2D(tex, uv + d.xw);\r\n s += texture2D(tex, uv + d.zw);\r\n\r\n return s * (1.0 / 4.0);\r\n}";
  28657. var StdLibGLSL = "#define HALF_MAX 65504.0 // (2 - 2^-10) * 2^15\r\n\r\n#define FLT_EPSILON 1.192092896e-07 // Smallest positive number, such that 1.0 + FLT_EPSILON != 1.0\r\n\r\nmediump vec4 safeHDR(mediump vec4 c)\r\n{\r\n return min(c, HALF_MAX);\r\n}\r\n\r\nfloat max3(float a, float b, float c)\r\n{\r\n return max(max(a, b), c);\r\n}\r\n\r\nvec3 positivePow(vec3 base, vec3 power)\r\n{\r\n return pow(max(abs(base), vec3(FLT_EPSILON, FLT_EPSILON, FLT_EPSILON)), power);\r\n}";
  28658. var ShadowHelperGLSL = "uniform sampler2D u_shadowMap1;\r\nuniform sampler2D u_shadowMap2;\r\nuniform sampler2D u_shadowMap3;\r\nuniform vec2\t u_shadowPCFoffset;\r\nuniform vec4 u_shadowPSSMDistance;\r\nvec4 packDepth(const in float depth)\r\n{\r\n\tconst vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);\r\n\tconst vec4 bitMask\t= vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);\r\n\tvec4 res = mod(depth*bitShift*vec4(255), vec4(256))/vec4(255);\r\n\tres -= res.xxyz * bitMask;\r\n\treturn res;\r\n}\r\nfloat unpackDepth(const in vec4 rgbaDepth)\r\n{\r\n\tconst vec4 bitShift = vec4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1.0);\r\n\tfloat depth = dot(rgbaDepth, bitShift);\r\n\treturn depth;\r\n}\r\nfloat tex2DPCF( sampler2D shadowMap,vec2 texcoord,vec2 invsize,float zRef )\r\n{\r\n\tvec2 texelpos =texcoord / invsize;\r\n\tvec2 lerps = fract( texelpos );\r\n\tfloat sourcevals[4];\r\n\tsourcevals[0] = float( unpackDepth(texture2D(shadowMap,texcoord)) > zRef );\r\n\tsourcevals[1] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(invsize.x,0))) > zRef );\r\n\tsourcevals[2] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(0,invsize.y))) > zRef );\r\n\tsourcevals[3] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(invsize.x, invsize.y) )) > zRef );\r\n\treturn mix( mix(sourcevals[0],sourcevals[2],lerps.y),mix(sourcevals[1],sourcevals[3],lerps.y),lerps.x );\r\n}\r\nfloat getShadowPSSM3( sampler2D shadowMap1,sampler2D shadowMap2,sampler2D shadowMap3,mat4 lightShadowVP[4],vec4 pssmDistance,vec2 shadowPCFOffset,vec3 worldPos,float posViewZ,float zBias )\r\n{\r\n\tfloat value = 1.0;\r\n\tint nPSNum = int(posViewZ>pssmDistance.x);\r\n\tnPSNum += int(posViewZ>pssmDistance.y);\r\n\tnPSNum += int(posViewZ>pssmDistance.z);\r\n\t//真SB,webgl不支持在PS中直接访问数组\r\n\tmat4 lightVP;\r\n\tif( nPSNum == 0 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[1];\r\n\t}\r\n\telse if( nPSNum == 1 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[2];\r\n\t}\r\n\telse if( nPSNum == 2 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[3];\r\n\t}\r\n\tvec4 vLightMVPPos = lightVP * vec4(worldPos,1.0);\r\n\t//为了效率,在CPU计算/2.0 + 0.5\r\n\t//vec3 vText = (vLightMVPPos.xyz / vLightMVPPos.w)/2.0 + 0.5;\r\n\tvec3 vText = vLightMVPPos.xyz / vLightMVPPos.w;\r\n\tfloat fMyZ = vText.z - zBias;\r\n\t/*\r\n\tbvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\r\n\tbool bInFrustum = all( bInFrustumVec );\r\n\tbvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\r\n\tbool bFrustumTest = all( bFrustumTestVec );\r\n\tif ( bFrustumTest ) \r\n\t*/\r\n\tif( fMyZ <= 1.0 )\r\n\t{\r\n\t\tfloat zdepth=0.0;\r\n#ifdef SHADOWMAP_PCF3\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue = value/4.0;\r\n\t\t} \r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 2 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap3,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF2\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 2 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap3,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n\r\n#endif\r\n#ifdef SHADOWMAP_PCF1\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap2,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n\t\telse if( nPSNum == 2 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap3,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF_NO\r\n\t\tvec4 color;\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap1,vText.xy );\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap2,vText.xy );\r\n\t\t}\r\n\t\telse if( nPSNum == 2 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap3,vText.xy );\r\n\t\t}\r\n\t\tzdepth = unpackDepth(color);\r\n\t\tvalue = float(fMyZ < zdepth);\r\n#endif\r\n\t}\r\n\treturn value;\r\n}\r\nfloat getShadowPSSM2( sampler2D shadowMap1,sampler2D shadowMap2,mat4 lightShadowVP[4],vec4 pssmDistance,vec2 shadowPCFOffset,vec3 worldPos,float posViewZ,float zBias )\r\n{\r\n\tfloat value = 1.0;\r\n\tint nPSNum = int(posViewZ>pssmDistance.x);\r\n\tnPSNum += int(posViewZ>pssmDistance.y);\r\n\t//真SB,webgl不支持在PS中直接访问数组\r\n\tmat4 lightVP;\r\n\tif( nPSNum == 0 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[1];\r\n\t}\r\n\telse if( nPSNum == 1 )\r\n\t{\r\n\t\tlightVP = lightShadowVP[2];\r\n\t}\r\n\tvec4 vLightMVPPos = lightVP * vec4(worldPos,1.0);\r\n\t//为了效率,在CPU计算/2.0 + 0.5\r\n\t//vec3 vText = (vLightMVPPos.xyz / vLightMVPPos.w)/2.0 + 0.5;\r\n\tvec3 vText = vLightMVPPos.xyz / vLightMVPPos.w;\r\n\tfloat fMyZ = vText.z - zBias;\r\n\t/*\r\n\tbvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\r\n\tbool bInFrustum = all( bInFrustumVec );\r\n\tbvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\r\n\tbool bFrustumTest = all( bFrustumTestVec );\r\n\tif ( bFrustumTest ) \r\n\t*/\r\n\tif( fMyZ <= 1.0 )\r\n\t{\r\n\t\tfloat zdepth=0.0;\r\n#ifdef SHADOWMAP_PCF3\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset,\tfMyZ );\r\n\t\t\tvalue = value/4.0;\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF2\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF1\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tvec4 color = texture2D( shadowMap2,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n\t\t}\r\n#endif\r\n#ifdef SHADOWMAP_PCF_NO\r\n\t\tvec4 color;\r\n\t\tif ( nPSNum == 0 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap1,vText.xy );\r\n\t\t}\r\n\t\telse if( nPSNum == 1 )\r\n\t\t{\r\n\t\t\tcolor = texture2D( shadowMap2,vText.xy );\r\n\t\t}\r\n\t\tzdepth = unpackDepth(color);\r\n\t\tvalue = float(fMyZ < zdepth);\r\n#endif\r\n\t}\r\n\treturn value;\r\n}\r\nfloat getShadowPSSM1( sampler2D shadowMap1,vec4 lightMVPPos,vec4 pssmDistance,vec2 shadowPCFOffset,float posViewZ,float zBias )\r\n{\r\n\tfloat value = 1.0;\r\n\tif( posViewZ < pssmDistance.x )\r\n\t{\r\n\t\tvec3 vText = lightMVPPos.xyz / lightMVPPos.w;\r\n\t\tfloat fMyZ = vText.z - zBias;\r\n\t\t/*\r\n\t\tbvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\r\n\t\tbool bInFrustum = all( bInFrustumVec );\r\n\t\tbvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\r\n\t\tbool bFrustumTest = all( bFrustumTestVec );\r\n\t\t*/\r\n\t\tif ( fMyZ <= 1.0 ) \r\n\t\t{\r\n\t\t\tfloat zdepth=0.0;\r\n#ifdef SHADOWMAP_PCF3\r\n\t\t\tvalue = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset,fMyZ );\r\n\t\t\tvalue += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset,fMyZ );\r\n\t\t\tvalue = value/4.0;\r\n#endif\r\n#ifdef SHADOWMAP_PCF2\t\t\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n#endif\r\n#ifdef SHADOWMAP_PCF1\r\n\t\t\tvalue = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\r\n#endif\r\n#ifdef SHADOWMAP_PCF_NO\t\t\r\n\t\t\tvec4 color = texture2D( shadowMap1,vText.xy );\r\n\t\t\tzdepth = unpackDepth(color);\r\n\t\t\tvalue = float(fMyZ < zdepth);\r\n#endif\r\n\t\t}\r\n\t}\r\n\treturn value;\r\n}";
  28659. var SkyBoxPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\nprecision highp float;\r\n#else\r\nprecision mediump float;\r\n#endif\r\n\r\nvarying vec3 v_Texcoord;\r\n\r\nuniform samplerCube u_CubeTexture;\r\nuniform float u_Exposure;\r\nuniform vec4 u_TintColor;\r\n\r\n\r\nvoid main()\r\n{\t\r\n\tvec3 color=textureCube(u_CubeTexture, v_Texcoord).rgb*u_TintColor.rgb*u_Exposure*2.0;\r\n\tgl_FragColor=vec4(color,1.0);\r\n}\r\n\r\n";
  28660. var SkyBoxVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nuniform mat4 u_ViewProjection;\r\nuniform float u_Rotation;\r\nvarying vec3 v_Texcoord;\r\n\r\n\r\nvec4 rotateAroundYInDegrees (vec4 vertex, float degrees)\r\n{\r\n\tfloat angle = degrees * 3.141593 / 180.0;\r\n\tfloat sina=sin(angle);\r\n\tfloat cosa=cos(angle);\r\n\tmat2 m = mat2(cosa, -sina, sina, cosa);\r\n\treturn vec4(m*vertex.xz, vertex.yw).xzyw;\r\n}\r\n\t\t\r\nvoid main()\r\n{\r\n\tvec4 position=rotateAroundYInDegrees(a_Position,u_Rotation);\r\n\tgl_Position = u_ViewProjection*position;\r\n\tv_Texcoord=vec3(-a_Position.x,a_Position.yz);//转换坐标系\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n";
  28661. var SkyBoxProceduralPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\nconst float MIE_G = -0.990;\r\nconst float MIE_G2 = 0.9801;\r\nconst float SKY_GROUND_THRESHOLD = 0.02;\r\n\r\nuniform float u_SunSize;\r\nuniform float u_SunSizeConvergence;\r\nuniform DirectionLight u_SunLight;\r\n\r\n\r\nvarying vec3 v_GroundColor;\r\nvarying vec3 v_SkyColor;\r\n\r\n\r\n#ifdef SUN_HIGH_QUALITY\r\n\tvarying vec3 v_Vertex;\r\n#elif defined(SUN_SIMPLE)\r\n\tvarying vec3 v_RayDir;\r\n#else\r\n\tvarying float v_SkyGroundFactor;\r\n#endif\r\n\r\n#if defined(SUN_HIGH_QUALITY)||defined(SUN_SIMPLE)\r\n\tvarying vec3 v_SunColor;\r\n#endif\r\n\r\n// Calculates the Mie phase function\r\nfloat getMiePhase(float eyeCos, float eyeCos2) {\r\n\tfloat temp = 1.0 + MIE_G2 - 2.0 * MIE_G * eyeCos;\r\n\ttemp = pow(temp, pow(u_SunSize,0.65) * 10.0);\r\n\ttemp = max(temp,1.0e-4); // prevent division by zero, esp. in half precision\r\n\ttemp = 1.5 * ((1.0 - MIE_G2) / (2.0 + MIE_G2)) * (1.0 + eyeCos2) / temp;\r\n\treturn temp;\r\n}\r\n\r\n// Calculates the sun shape\r\nfloat calcSunAttenuation(vec3 lightPos, vec3 ray) {\r\n\t#ifdef SUN_HIGH_QUALITY\r\n\t\tfloat focusedEyeCos = pow(clamp(dot(lightPos, ray),0.0,1.0), u_SunSizeConvergence);\r\n\t\treturn getMiePhase(-focusedEyeCos, focusedEyeCos * focusedEyeCos);\r\n\t#else //SUN_SIMPLE\r\n\t\tvec3 delta = lightPos - ray;\r\n\t\tfloat dist = length(delta);\r\n\t\tfloat spot = 1.0 - smoothstep(0.0, u_SunSize, dist);\r\n\t\treturn spot * spot;\r\n\t#endif\r\n}\r\n\r\nvoid main() {\r\n\t// if y > 1 [eyeRay.y < -SKY_GROUND_THRESHOLD] - ground\r\n\t// if y >= 0 and < 1 [eyeRay.y <= 0 and > -SKY_GROUND_THRESHOLD] - horizon\r\n\t// if y < 0 [eyeRay.y > 0] - sky\r\n\tvec3 col = vec3(0.0, 0.0, 0.0);\r\n\r\n\t#ifdef SUN_HIGH_QUALITY\r\n\t\tvec3 ray = normalize(v_Vertex);\r\n\t\tfloat y = ray.y / SKY_GROUND_THRESHOLD;\r\n\t#elif defined(SUN_SIMPLE) \r\n\t\tvec3 ray = v_RayDir;\r\n\t\tfloat y = ray.y / SKY_GROUND_THRESHOLD;\t\r\n\t#else\r\n\t\tfloat y = v_SkyGroundFactor;\r\n\t#endif\r\n\r\n\t// if we did precalculate color in vprog: just do lerp between them\r\n\tcol = mix(v_SkyColor, v_GroundColor, clamp(y,0.0,1.0));\r\n\r\n\t#if defined(SUN_HIGH_QUALITY)||defined(SUN_SIMPLE)\r\n\t\tif (y < 0.0)\r\n\t\t\tcol += v_SunColor * calcSunAttenuation(-u_SunLight.direction, -ray);\r\n\t#endif\r\n\r\n\tcol = sqrt(col);//linear space convert to gamma space\r\n\tgl_FragColor=vec4(col,1.0);\r\n}\r\n\r\n";
  28662. var SkyBoxProceduralVS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\n#define OUTER_RADIUS 1.025\r\n#define RAYLEIGH (mix(0.0, 0.0025, pow(u_AtmosphereThickness,2.5)))// Rayleigh constant Rayleigh为夜空光和极光亮度单位\r\n#define MIE 0.0010 // Mie constant 米氏散射\r\n#define SUN_BRIGHTNESS 20.0 // Sun brightness\r\n#define MAX_SCATTER 50.0 // Maximum scattering value, to prevent math overflows on Adrenos\r\n\r\nconst float SKY_GROUND_THRESHOLD = 0.02;\r\nconst float outerRadius = OUTER_RADIUS;\r\nconst float outerRadius2 = OUTER_RADIUS*OUTER_RADIUS;\r\nconst float innerRadius = 1.0;\r\nconst float innerRadius2 = 1.0;\r\nconst float cameraHeight = 0.0001;\r\n\r\nconst float HDSundiskIntensityFactor = 15.0;\r\nconst float simpleSundiskIntensityFactor = 27.0;\r\n\r\nconst float sunScale = 400.0 * SUN_BRIGHTNESS;\r\nconst float kmESun = MIE * SUN_BRIGHTNESS;\r\nconst float km4PI = MIE * 4.0 * 3.14159265;\r\nconst float scale = 1.0 / (OUTER_RADIUS - 1.0);\r\nconst float scaleDepth = 0.25;\r\nconst float scaleOverScaleDepth = (1.0 / (OUTER_RADIUS - 1.0)) / 0.25;\r\nconst float samples = 2.0; // THIS IS UNROLLED MANUALLY, DON'T TOUCH\r\n\r\n// RGB wavelengths .35 (.62=158), .43 (.68=174), .525 (.75=190)\r\nconst vec3 c_DefaultScatteringWavelength = vec3(0.65, 0.57, 0.475);//默认散射波长\r\nconst vec3 c_VariableRangeForScatteringWavelength = vec3(0.15, 0.15, 0.15);//散射播放的可变范围\r\n\r\nattribute vec4 a_Position;\r\n\r\nuniform mat4 u_ViewProjection;\r\nuniform vec3 u_SkyTint;\r\nuniform vec3 u_GroundTint;\r\nuniform float u_Exposure;\r\nuniform float u_AtmosphereThickness;\r\nuniform DirectionLight u_SunLight;\r\n\r\nvarying vec3 v_GroundColor;\r\nvarying vec3 v_SkyColor;\r\n\r\n#ifdef SUN_HIGH_QUALITY\r\n\tvarying vec3 v_Vertex;\r\n#elif defined(SUN_SIMPLE)\r\n\tvarying vec3 v_RayDir;\r\n#else\r\n\tvarying float v_SkyGroundFactor;\r\n#endif\r\n\r\n#if defined(SUN_HIGH_QUALITY)||defined(SUN_SIMPLE)\r\n\tvarying vec3 v_SunColor;\r\n#endif\r\n\r\n// Calculates the Rayleigh phase function\r\nfloat getRayleighPhase(vec3 light, vec3 ray) \r\n{\r\n\tfloat eyeCos = dot(light, ray);\r\n\treturn 0.75 + 0.75*eyeCos*eyeCos;\r\n}\r\n\r\nfloat scaleAngle(float inCos)\r\n{\r\n\tfloat x = 1.0 - inCos;\r\n\treturn 0.25 * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));\r\n}\r\n\r\n\r\nvoid main () {\r\n\tgl_Position = u_ViewProjection*a_Position;\r\n\r\n\tvec3 skyTintInGammaSpace = u_SkyTint;//支持非GAMMA空间后要调整\r\n\tvec3 scatteringWavelength = mix(c_DefaultScatteringWavelength-c_VariableRangeForScatteringWavelength,c_DefaultScatteringWavelength+c_VariableRangeForScatteringWavelength,vec3(1.0) - skyTintInGammaSpace); // using Tint in sRGB+ gamma allows for more visually linear interpolation and to keep (0.5) at (128, gray in sRGB) point\r\n\tvec3 invWavelength = 1.0 / pow(scatteringWavelength, vec3(4.0));\r\n\r\n\tfloat krESun = RAYLEIGH * SUN_BRIGHTNESS;\r\n\tfloat kr4PI = RAYLEIGH * 4.0 * 3.14159265;\r\n\r\n\tvec3 cameraPos = vec3(0.0,innerRadius + cameraHeight,0.0); // The camera's current position\r\n\r\n\t// Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere)\r\n\tvec3 eyeRay = normalize(a_Position.xyz);\r\n\r\n\tfloat far = 0.0;\r\n\tvec3 cIn, cOut;\r\n\tif (eyeRay.y >= 0.0) {// Sky\r\n\t\t// Calculate the length of the \"atmosphere\"\r\n\t\tfar = sqrt(outerRadius2 + innerRadius2 * eyeRay.y * eyeRay.y - innerRadius2) - innerRadius * eyeRay.y;\r\n\r\n\t\t// Calculate the ray's starting position, then calculate its scattering offset\r\n\t\tfloat height = innerRadius + cameraHeight;\r\n\t\tfloat depth = exp(scaleOverScaleDepth * -cameraHeight);\r\n\t\tfloat startAngle = dot(eyeRay, cameraPos) / height;\r\n\t\tfloat startOffset = depth*scaleAngle(startAngle);\r\n\r\n\t\t// Initialize the scattering loop variables\r\n\t\tfloat sampleLength = far / samples;\r\n\t\tfloat scaledLength = sampleLength * scale;\r\n\t\tvec3 sampleRay = eyeRay * sampleLength;\r\n\t\tvec3 samplePoint = cameraPos + sampleRay * 0.5;\r\n\r\n\t\tvec3 frontColor = vec3(0.0);\r\n\t\t//unrolling this manually to avoid some platform for loop slow\r\n\t\t{\r\n\t\t\tfloat height = length(samplePoint);\r\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\r\n\t\t\tfloat lightAngle = dot(-u_SunLight.direction, samplePoint) / height;\r\n\t\t\tfloat cameraAngle = dot(eyeRay, samplePoint) / height;\r\n\t\t\tfloat scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle)));\r\n\t\t\tvec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\r\n\r\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\r\n\t\t\tsamplePoint += sampleRay;\r\n\t\t}\r\n\t\t{\r\n\t\t\tfloat height = length(samplePoint);\r\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\r\n\t\t\tfloat lightAngle = dot(-u_SunLight.direction, samplePoint) / height;\r\n\t\t\tfloat cameraAngle = dot(eyeRay, samplePoint) / height;\r\n\t\t\tfloat scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle)));\r\n\t\t\tvec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\r\n\r\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\r\n\t\t\tsamplePoint += sampleRay;\r\n\t\t}\r\n\r\n\t\t// Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader\r\n\t\tcIn = frontColor * (invWavelength * krESun);\r\n\t\tcOut = frontColor * kmESun;\r\n\t} else {// Ground\r\n\t\tfar = (-cameraHeight) / (min(-0.001, eyeRay.y));\r\n\t\tvec3 pos = cameraPos + far * eyeRay;\r\n\r\n\t\t// Calculate the ray's starting position, then calculate its scattering offset\r\n\t\tfloat depth = exp((-cameraHeight) * (1.0/scaleDepth));\r\n\t\tfloat cameraAngle = dot(-eyeRay, pos);\r\n\t\tfloat lightAngle = dot(-u_SunLight.direction, pos);\r\n\t\tfloat cameraScale = scaleAngle(cameraAngle);\r\n\t\tfloat lightScale = scaleAngle(lightAngle);\r\n\t\tfloat cameraOffset = depth*cameraScale;\r\n\t\tfloat temp = lightScale + cameraScale;\r\n\r\n\t\t// Initialize the scattering loop variables\r\n\t\tfloat sampleLength = far / samples;\r\n\t\tfloat scaledLength = sampleLength * scale;\r\n\t\tvec3 sampleRay = eyeRay * sampleLength;\r\n\t\tvec3 samplePoint = cameraPos + sampleRay * 0.5;\r\n\r\n\t\t// Now loop through the sample rays\r\n\t\tvec3 frontColor = vec3(0.0, 0.0, 0.0);\r\n\t\tvec3 attenuate;\r\n\r\n\t\t// Loop removed because we kept hitting SM2.0 temp variable limits. Doesn't affect the image too much.\r\n\t\t{\r\n\t\t\tfloat height = length(samplePoint);\r\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\r\n\t\t\tfloat scatter = depth*temp - cameraOffset;\r\n\t\t\tattenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\r\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\r\n\t\t\tsamplePoint += sampleRay;\r\n\t\t}\r\n\r\n\t\tcIn = frontColor * (invWavelength * krESun + kmESun);\r\n\t\tcOut = clamp(attenuate, 0.0, 1.0);\r\n\t}\r\n\r\n\t#ifdef SUN_HIGH_QUALITY\r\n\t\tv_Vertex = -a_Position.xyz;\r\n\t#elif defined(SUN_SIMPLE) \r\n\t\tv_RayDir = -eyeRay;\r\n\t#else\r\n\t\tv_SkyGroundFactor = -eyeRay.y / SKY_GROUND_THRESHOLD;\r\n\t#endif\r\n\r\n\t// if we want to calculate color in vprog:\r\n\t// in case of linear: multiply by _Exposure in here (even in case of lerp it will be common multiplier, so we can skip mul in fshader)\r\n\tv_GroundColor = u_Exposure * (cIn + u_GroundTint*u_GroundTint * cOut);//u_GroundColor*u_GroundColor is gamma space convert to linear space\r\n\tv_SkyColor = u_Exposure * (cIn * getRayleighPhase(-u_SunLight.direction, -eyeRay));\r\n\r\n\t\r\n\t// The sun should have a stable intensity in its course in the sky. Moreover it should match the highlight of a purely specular material.\r\n\t// This matching was done using the Unity3D standard shader BRDF1 on the 5/31/2017\r\n\t// Finally we want the sun to be always bright even in LDR thus the normalization of the lightColor for low intensity.\r\n\tfloat lightColorIntensity = clamp(length(u_SunLight.color), 0.25, 1.0);\r\n\r\n\t#ifdef SUN_HIGH_QUALITY \r\n\t\tv_SunColor = HDSundiskIntensityFactor * clamp(cOut,0.0,1.0) * u_SunLight.color / lightColorIntensity;\r\n\t#elif defined(SUN_SIMPLE) \r\n\t\tv_SunColor = simpleSundiskIntensityFactor * clamp(cOut * sunScale,0.0,1.0) * u_SunLight.color / lightColorIntensity;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n";
  28663. var TrailPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\nuniform sampler2D u_MainTexture;\r\nuniform vec4 u_MainColor;\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec4 v_Color;\r\n\r\nvoid main()\r\n{\r\n\tvec4 color = 2.0 * u_MainColor * v_Color;\r\n\t#ifdef MAINTEXTURE\r\n\t\tvec4 mainTextureColor = texture2D(u_MainTexture, v_Texcoord0);\r\n\t\tcolor *= mainTextureColor;\r\n\t#endif\r\n\tgl_FragColor = color;\r\n}\r\n\r\n ";
  28664. var TrailVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec3 a_Position;\r\nattribute vec3 a_OffsetVector;\r\nattribute vec4 a_Color;\r\nattribute float a_Texcoord0X;\r\nattribute float a_Texcoord0Y;\r\nattribute float a_BirthTime;\r\n\r\nuniform mat4 u_View;\r\nuniform mat4 u_Projection;\r\n\r\nuniform vec4 u_TilingOffset;\r\n\r\nuniform float u_CurTime;\r\nuniform float u_LifeTime;\r\nuniform vec4 u_WidthCurve[10];\r\nuniform int u_WidthCurveKeyLength;\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec4 v_Color;\r\n\r\nfloat hermiteInterpolate(float t, float outTangent, float inTangent, float duration, float value1, float value2)\r\n{\r\n\tfloat t2 = t * t;\r\n\tfloat t3 = t2 * t;\r\n\tfloat a = 2.0 * t3 - 3.0 * t2 + 1.0;\r\n\tfloat b = t3 - 2.0 * t2 + t;\r\n\tfloat c = t3 - t2;\r\n\tfloat d = -2.0 * t3 + 3.0 * t2;\r\n\treturn a * value1 + b * outTangent * duration + c * inTangent * duration + d * value2;\r\n}\r\n\r\nfloat getCurWidth(in float normalizeTime)\r\n{\r\n\tfloat width;\r\n\tif(normalizeTime == 0.0){\r\n\t\twidth=u_WidthCurve[0].w;\r\n\t}\r\n\telse if(normalizeTime >= 1.0){\r\n\t\twidth=u_WidthCurve[u_WidthCurveKeyLength - 1].w;\r\n\t}\r\n\telse{\r\n\t\tfor(int i = 0; i < 10; i ++ )\r\n\t\t{\r\n\t\t\tif(normalizeTime == u_WidthCurve[i].x){\r\n\t\t\t\twidth=u_WidthCurve[i].w;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tvec4 lastFrame = u_WidthCurve[i];\r\n\t\t\tvec4 nextFrame = u_WidthCurve[i + 1];\r\n\t\t\tif(normalizeTime > lastFrame.x && normalizeTime < nextFrame.x)\r\n\t\t\t{\r\n\t\t\t\tfloat duration = nextFrame.x - lastFrame.x;\r\n\t\t\t\tfloat t = (normalizeTime - lastFrame.x) / duration;\r\n\t\t\t\tfloat outTangent = lastFrame.z;\r\n\t\t\t\tfloat inTangent = nextFrame.y;\r\n\t\t\t\tfloat value1 = lastFrame.w;\r\n\t\t\t\tfloat value2 = nextFrame.w;\r\n\t\t\t\twidth=hermiteInterpolate(t, outTangent, inTangent, duration, value1, value2);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn width;\r\n}\t\r\n\r\nvoid main()\r\n{\r\n\tfloat normalizeTime = (u_CurTime - a_BirthTime) / u_LifeTime;\r\n\t\r\n\t#ifdef TILINGOFFSET\r\n\t\tv_Texcoord0 = vec2(a_Texcoord0X, 1.0 - a_Texcoord0Y) * u_TilingOffset.xy + u_TilingOffset.zw;\r\n\t#else\r\n\t\tv_Texcoord0 = vec2(a_Texcoord0X, a_Texcoord0Y);\r\n\t#endif\r\n\t\r\n\tv_Color = a_Color;\r\n\t\r\n\tgl_Position = u_Projection * u_View * vec4(a_Position + a_OffsetVector * getCurWidth(normalizeTime),1.0);\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n";
  28665. var UnlitPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\tvarying vec4 v_Color;\r\n#endif\r\n\r\n#ifdef ALBEDOTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n\tvarying vec2 v_Texcoord0;\r\n#endif\r\n\r\nuniform vec4 u_AlbedoColor;\r\n\r\n#ifdef ALPHATEST\r\n\tuniform float u_AlphaTestValue;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\t#ifdef ADDTIVEFOG\r\n\t#else\r\n\t\tuniform vec3 u_FogColor;\r\n\t#endif\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tvec4 color = u_AlbedoColor;\r\n\t#ifdef ALBEDOTEXTURE\r\n\t\tcolor *= texture2D(u_AlbedoTexture, v_Texcoord0);\r\n\t#endif\r\n\t#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\t\tcolor *= v_Color;\r\n\t#endif\r\n\t\r\n\t#ifdef ALPHATEST\r\n\t\tif(color.a < u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n\t\r\n\tgl_FragColor = color;\r\n\t\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact = clamp((1.0 / gl_FragCoord.w - u_FogStart) / u_FogRange, 0.0, 1.0);\r\n\t\t#ifdef ADDTIVEFOG\r\n\t\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0.0), lerpFact);\r\n\t\t#else\r\n\t\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, u_FogColor, lerpFact);\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n}\r\n\r\n";
  28666. var UnlitVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\n\r\nattribute vec2 a_Texcoord0;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n#endif\r\n\r\nattribute vec4 a_Color;\r\nvarying vec4 v_Color;\r\nvarying vec2 v_Texcoord0;\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\tposition=skinTransform*a_Position;\r\n\t#else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\r\n\t#ifdef TILINGOFFSET\r\n\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t#else\r\n\t\tv_Texcoord0=a_Texcoord0;\r\n\t#endif\r\n\r\n\t#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\t\tv_Color = a_Color;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  28667. var WaterPrimaryPS = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#ifdef MAINTEXTURE\r\n\tuniform sampler2D u_MainTexture;\r\n#endif\r\n\r\n#ifdef NORMALTEXTURE\r\n\tuniform sampler2D u_NormalTexture;\r\n#endif\r\n\r\nuniform vec4 u_HorizonColor;\r\n\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec2 v_Texcoord0;\r\nvarying vec2 v_Texcoord1;\r\n\r\n#include \"Lighting.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 bumpColor1 = texture2D(u_NormalTexture, v_Texcoord0);\r\n\tvec4 bumpColor2 = texture2D(u_NormalTexture, v_Texcoord1);\r\n\t\r\n\tvec3 normal1 = NormalSampleToWorldSpace1(bumpColor1, v_Tangent, v_Binormal, v_Normal);\r\n\tvec3 normal2 = NormalSampleToWorldSpace1(bumpColor2, v_Tangent, v_Binormal, v_Normal);\r\n\t\r\n\tvec3 normal = normalize((normal1 + normal2) * 0.5);\r\n\tvec3 viewDir = normalize(v_ViewDir);\r\n\tfloat fresnel = dot(viewDir, normal);\r\n\t\r\n\tvec4 waterColor = texture2D(u_MainTexture, vec2(fresnel, fresnel));\r\n\t\r\n\tvec4 color;\r\n\tcolor.rgb = mix(waterColor.rgb, u_HorizonColor.rgb, vec3(waterColor.a));\r\n\tcolor.a = u_HorizonColor.a;\r\n\t\r\n\tgl_FragColor = color;\r\n}\r\n\r\n";
  28668. var WaterPrimaryVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\r\nattribute vec4 a_Tangent0;\r\n\r\nuniform mat4 u_MvpMatrix;\r\nuniform mat4 u_WorldMat;\r\nuniform vec3 u_CameraPos;\r\nuniform float u_WaveScale;\r\nuniform vec4 u_WaveSpeed;\r\nuniform float u_Time;\r\n\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec2 v_Texcoord0;\r\nvarying vec2 v_Texcoord1;\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionWorld = u_WorldMat * a_Position;\r\n\tvec4 position = u_MvpMatrix * a_Position;\r\n\t\r\n\tvec4 temp = vec4(positionWorld.x, positionWorld.z, positionWorld.x, positionWorld.z) * u_WaveScale + u_WaveSpeed * u_WaveScale * u_Time;\r\n\t\r\n\tv_Texcoord0 = temp.xy * vec2(0.4, 0.45);\r\n\tv_Texcoord1 = temp.wz;\r\n\t\r\n\tmat3 worldMat = mat3(u_WorldMat);\r\n\tv_Normal = worldMat * a_Normal;\r\n\tv_Tangent = worldMat * a_Tangent0.xyz;\r\n\tv_Binormal = cross(v_Normal, v_Tangent) * a_Tangent0.w;\r\n\t\r\n\tv_ViewDir = u_CameraPos - positionWorld.xyz;\r\n\tgl_Position = position;\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  28669. class ShaderVariable {
  28670. constructor() {
  28671. this.textureID = -1;
  28672. }
  28673. }
  28674. class ShaderInstance extends Laya.Resource {
  28675. constructor(vs, ps, attributeMap, uniformMap, shaderPass) {
  28676. super();
  28677. this._stateParamsMap = [];
  28678. this._uploadMark = -1;
  28679. this._uploadRenderType = -1;
  28680. this._vs = vs;
  28681. this._ps = ps;
  28682. this._attributeMap = attributeMap;
  28683. this._uniformMap = uniformMap;
  28684. this._shaderPass = shaderPass;
  28685. this._create();
  28686. this.lock = true;
  28687. }
  28688. _create() {
  28689. var gl = Laya.LayaGL.instance;
  28690. this._program = gl.createProgram();
  28691. this._vshader = this._createShader(gl, this._vs, gl.VERTEX_SHADER);
  28692. this._pshader = this._createShader(gl, this._ps, gl.FRAGMENT_SHADER);
  28693. gl.attachShader(this._program, this._vshader);
  28694. gl.attachShader(this._program, this._pshader);
  28695. for (var k in this._attributeMap)
  28696. gl.bindAttribLocation(this._program, this._attributeMap[k], k);
  28697. gl.linkProgram(this._program);
  28698. if (!Laya.Render.isConchApp && Shader3D.debugMode && !gl.getProgramParameter(this._program, gl.LINK_STATUS))
  28699. throw gl.getProgramInfoLog(this._program);
  28700. var sceneParms = [];
  28701. var cameraParms = [];
  28702. var spriteParms = [];
  28703. var materialParms = [];
  28704. var customParms = [];
  28705. this._customUniformParamsMap = [];
  28706. var nUniformNum = gl.getProgramParameter(this._program, gl.ACTIVE_UNIFORMS);
  28707. Laya.WebGLContext.useProgram(gl, this._program);
  28708. this._curActTexIndex = 0;
  28709. var one, i, n;
  28710. for (i = 0; i < nUniformNum; i++) {
  28711. var uniformData = gl.getActiveUniform(this._program, i);
  28712. var uniName = uniformData.name;
  28713. one = new ShaderVariable();
  28714. one.location = gl.getUniformLocation(this._program, uniName);
  28715. if (uniName.indexOf('[0]') > 0) {
  28716. one.name = uniName = uniName.substr(0, uniName.length - 3);
  28717. one.isArray = true;
  28718. }
  28719. else {
  28720. one.name = uniName;
  28721. one.isArray = false;
  28722. }
  28723. one.type = uniformData.type;
  28724. this._addShaderUnifiormFun(one);
  28725. var uniformPeriod = this._uniformMap[uniName];
  28726. if (uniformPeriod != null) {
  28727. one.dataOffset = Shader3D.propertyNameToID(uniName);
  28728. switch (uniformPeriod) {
  28729. case Shader3D.PERIOD_CUSTOM:
  28730. customParms.push(one);
  28731. break;
  28732. case Shader3D.PERIOD_MATERIAL:
  28733. materialParms.push(one);
  28734. break;
  28735. case Shader3D.PERIOD_SPRITE:
  28736. spriteParms.push(one);
  28737. break;
  28738. case Shader3D.PERIOD_CAMERA:
  28739. cameraParms.push(one);
  28740. break;
  28741. case Shader3D.PERIOD_SCENE:
  28742. sceneParms.push(one);
  28743. break;
  28744. default:
  28745. throw new Error("Shader3D: period is unkonw.");
  28746. }
  28747. }
  28748. }
  28749. this._sceneUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(sceneParms.length * 4 * 5 + 4, 64, true);
  28750. for (i = 0, n = sceneParms.length; i < n; i++)
  28751. this._sceneUniformParamsMap.addShaderUniform(sceneParms[i]);
  28752. this._cameraUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(cameraParms.length * 4 * 5 + 4, 64, true);
  28753. for (i = 0, n = cameraParms.length; i < n; i++)
  28754. this._cameraUniformParamsMap.addShaderUniform(cameraParms[i]);
  28755. this._spriteUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(spriteParms.length * 4 * 5 + 4, 64, true);
  28756. for (i = 0, n = spriteParms.length; i < n; i++)
  28757. this._spriteUniformParamsMap.addShaderUniform(spriteParms[i]);
  28758. this._materialUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(materialParms.length * 4 * 5 + 4, 64, true);
  28759. for (i = 0, n = materialParms.length; i < n; i++)
  28760. this._materialUniformParamsMap.addShaderUniform(materialParms[i]);
  28761. this._customUniformParamsMap.length = customParms.length;
  28762. for (i = 0, n = customParms.length; i < n; i++) {
  28763. var custom = customParms[i];
  28764. this._customUniformParamsMap[custom.dataOffset] = custom;
  28765. }
  28766. var stateMap = this._shaderPass._stateMap;
  28767. for (var s in stateMap)
  28768. this._stateParamsMap[stateMap[s]] = Shader3D.propertyNameToID(s);
  28769. }
  28770. _getRenderState(shaderDatas, stateIndex) {
  28771. var stateID = this._stateParamsMap[stateIndex];
  28772. if (stateID == null)
  28773. return null;
  28774. else
  28775. return shaderDatas[stateID];
  28776. }
  28777. _disposeResource() {
  28778. Laya.LayaGL.instance.deleteShader(this._vshader);
  28779. Laya.LayaGL.instance.deleteShader(this._pshader);
  28780. Laya.LayaGL.instance.deleteProgram(this._program);
  28781. this._vshader = this._pshader = this._program = null;
  28782. this._setGPUMemory(0);
  28783. this._curActTexIndex = 0;
  28784. }
  28785. _addShaderUnifiormFun(one) {
  28786. var gl = Laya.LayaGL.instance;
  28787. one.caller = this;
  28788. var isArray = one.isArray;
  28789. switch (one.type) {
  28790. case gl.BOOL:
  28791. one.fun = this._uniform1i;
  28792. one.uploadedValue = new Array(1);
  28793. break;
  28794. case gl.INT:
  28795. one.fun = isArray ? this._uniform1iv : this._uniform1i;
  28796. one.uploadedValue = new Array(1);
  28797. break;
  28798. case gl.FLOAT:
  28799. one.fun = isArray ? this._uniform1fv : this._uniform1f;
  28800. one.uploadedValue = new Array(1);
  28801. break;
  28802. case gl.FLOAT_VEC2:
  28803. one.fun = isArray ? this._uniform_vec2v : this._uniform_vec2;
  28804. one.uploadedValue = new Array(2);
  28805. break;
  28806. case gl.FLOAT_VEC3:
  28807. one.fun = isArray ? this._uniform_vec3v : this._uniform_vec3;
  28808. one.uploadedValue = new Array(3);
  28809. break;
  28810. case gl.FLOAT_VEC4:
  28811. one.fun = isArray ? this._uniform_vec4v : this._uniform_vec4;
  28812. one.uploadedValue = new Array(4);
  28813. break;
  28814. case gl.FLOAT_MAT2:
  28815. one.fun = this._uniformMatrix2fv;
  28816. break;
  28817. case gl.FLOAT_MAT3:
  28818. one.fun = this._uniformMatrix3fv;
  28819. break;
  28820. case gl.FLOAT_MAT4:
  28821. one.fun = isArray ? this._uniformMatrix4fv : this._uniformMatrix4f;
  28822. break;
  28823. case gl.SAMPLER_2D:
  28824. gl.uniform1i(one.location, this._curActTexIndex);
  28825. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  28826. one.fun = this._uniform_sampler2D;
  28827. break;
  28828. case 0x8b5f:
  28829. gl.uniform1i(one.location, this._curActTexIndex);
  28830. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  28831. one.fun = this._uniform_sampler3D;
  28832. break;
  28833. case gl.SAMPLER_CUBE:
  28834. gl.uniform1i(one.location, this._curActTexIndex);
  28835. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  28836. one.fun = this._uniform_samplerCube;
  28837. break;
  28838. default:
  28839. throw new Error("compile shader err!");
  28840. break;
  28841. }
  28842. }
  28843. _createShader(gl, str, type) {
  28844. var shader = gl.createShader(type);
  28845. gl.shaderSource(shader, str);
  28846. gl.compileShader(shader);
  28847. if (Shader3D.debugMode && !gl.getShaderParameter(shader, gl.COMPILE_STATUS))
  28848. throw gl.getShaderInfoLog(shader);
  28849. return shader;
  28850. }
  28851. _uniform1f(one, value) {
  28852. var uploadedValue = one.uploadedValue;
  28853. if (uploadedValue[0] !== value) {
  28854. Laya.LayaGL.instance.uniform1f(one.location, uploadedValue[0] = value);
  28855. return 1;
  28856. }
  28857. return 0;
  28858. }
  28859. _uniform1fv(one, value) {
  28860. if (value.length < 4) {
  28861. var uploadedValue = one.uploadedValue;
  28862. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  28863. Laya.LayaGL.instance.uniform1fv(one.location, value);
  28864. uploadedValue[0] = value[0];
  28865. uploadedValue[1] = value[1];
  28866. uploadedValue[2] = value[2];
  28867. uploadedValue[3] = value[3];
  28868. return 1;
  28869. }
  28870. return 0;
  28871. }
  28872. else {
  28873. Laya.LayaGL.instance.uniform1fv(one.location, value);
  28874. return 1;
  28875. }
  28876. }
  28877. _uniform_vec2(one, v) {
  28878. var uploadedValue = one.uploadedValue;
  28879. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y) {
  28880. Laya.LayaGL.instance.uniform2f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y);
  28881. return 1;
  28882. }
  28883. return 0;
  28884. }
  28885. _uniform_vec2v(one, value) {
  28886. if (value.length < 2) {
  28887. var uploadedValue = one.uploadedValue;
  28888. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  28889. Laya.LayaGL.instance.uniform2fv(one.location, value);
  28890. uploadedValue[0] = value[0];
  28891. uploadedValue[1] = value[1];
  28892. uploadedValue[2] = value[2];
  28893. uploadedValue[3] = value[3];
  28894. return 1;
  28895. }
  28896. return 0;
  28897. }
  28898. else {
  28899. Laya.LayaGL.instance.uniform2fv(one.location, value);
  28900. return 1;
  28901. }
  28902. }
  28903. _uniform_vec3(one, v) {
  28904. var uploadedValue = one.uploadedValue;
  28905. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y || uploadedValue[2] !== v.z) {
  28906. Laya.LayaGL.instance.uniform3f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y, uploadedValue[2] = v.z);
  28907. return 1;
  28908. }
  28909. return 0;
  28910. }
  28911. _uniform_vec3v(one, v) {
  28912. Laya.LayaGL.instance.uniform3fv(one.location, v);
  28913. return 1;
  28914. }
  28915. _uniform_vec4(one, v) {
  28916. var uploadedValue = one.uploadedValue;
  28917. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y || uploadedValue[2] !== v.z || uploadedValue[3] !== v.w) {
  28918. Laya.LayaGL.instance.uniform4f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y, uploadedValue[2] = v.z, uploadedValue[3] = v.w);
  28919. return 1;
  28920. }
  28921. return 0;
  28922. }
  28923. _uniform_vec4v(one, v) {
  28924. Laya.LayaGL.instance.uniform4fv(one.location, v);
  28925. return 1;
  28926. }
  28927. _uniformMatrix2fv(one, value) {
  28928. Laya.LayaGL.instance.uniformMatrix2fv(one.location, false, value);
  28929. return 1;
  28930. }
  28931. _uniformMatrix3fv(one, value) {
  28932. Laya.LayaGL.instance.uniformMatrix3fv(one.location, false, value);
  28933. return 1;
  28934. }
  28935. _uniformMatrix4f(one, m) {
  28936. var value = m.elements;
  28937. Laya.LayaGL.instance.uniformMatrix4fv(one.location, false, value);
  28938. return 1;
  28939. }
  28940. _uniformMatrix4fv(one, m) {
  28941. Laya.LayaGL.instance.uniformMatrix4fv(one.location, false, m);
  28942. return 1;
  28943. }
  28944. _uniform1i(one, value) {
  28945. var uploadedValue = one.uploadedValue;
  28946. if (uploadedValue[0] !== value) {
  28947. Laya.LayaGL.instance.uniform1i(one.location, uploadedValue[0] = value);
  28948. return 1;
  28949. }
  28950. return 0;
  28951. }
  28952. _uniform1iv(one, value) {
  28953. Laya.LayaGL.instance.uniform1iv(one.location, value);
  28954. return 1;
  28955. }
  28956. _uniform_ivec2(one, value) {
  28957. var uploadedValue = one.uploadedValue;
  28958. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1]) {
  28959. Laya.LayaGL.instance.uniform2i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1]);
  28960. return 1;
  28961. }
  28962. return 0;
  28963. }
  28964. _uniform_ivec2v(one, value) {
  28965. Laya.LayaGL.instance.uniform2iv(one.location, value);
  28966. return 1;
  28967. }
  28968. _uniform_vec3i(one, value) {
  28969. var uploadedValue = one.uploadedValue;
  28970. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2]) {
  28971. Laya.LayaGL.instance.uniform3i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1], uploadedValue[2] = value[2]);
  28972. return 1;
  28973. }
  28974. return 0;
  28975. }
  28976. _uniform_vec3vi(one, value) {
  28977. Laya.LayaGL.instance.uniform3iv(one.location, value);
  28978. return 1;
  28979. }
  28980. _uniform_vec4i(one, value) {
  28981. var uploadedValue = one.uploadedValue;
  28982. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  28983. Laya.LayaGL.instance.uniform4i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1], uploadedValue[2] = value[2], uploadedValue[3] = value[3]);
  28984. return 1;
  28985. }
  28986. return 0;
  28987. }
  28988. _uniform_vec4vi(one, value) {
  28989. Laya.LayaGL.instance.uniform4iv(one.location, value);
  28990. return 1;
  28991. }
  28992. _uniform_sampler2D(one, texture) {
  28993. var value = texture._getSource() || texture.defaulteTexture._getSource();
  28994. var gl = Laya.LayaGL.instance;
  28995. Laya.WebGLContext.activeTexture(gl, one.textureID);
  28996. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, value);
  28997. return 0;
  28998. }
  28999. _uniform_sampler3D(one, texture) {
  29000. var value = texture._getSource() || texture.defaulteTexture._getSource();
  29001. var gl = Laya.LayaGL.instance;
  29002. Laya.WebGLContext.activeTexture(gl, one.textureID);
  29003. Laya.WebGLContext.bindTexture(gl, WebGL2RenderingContext.TEXTURE_3D, value);
  29004. return 0;
  29005. }
  29006. _uniform_samplerCube(one, texture) {
  29007. var value = texture._getSource() || texture.defaulteTexture._getSource();
  29008. var gl = Laya.LayaGL.instance;
  29009. Laya.WebGLContext.activeTexture(gl, one.textureID);
  29010. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_CUBE_MAP, value);
  29011. return 0;
  29012. }
  29013. bind() {
  29014. return Laya.WebGLContext.useProgram(Laya.LayaGL.instance, this._program);
  29015. }
  29016. uploadUniforms(shaderUniform, shaderDatas, uploadUnTexture) {
  29017. Laya.Stat.shaderCall += Laya.LayaGLRunner.uploadShaderUniforms(Laya.LayaGL.instance, shaderUniform, shaderDatas, uploadUnTexture);
  29018. }
  29019. uploadRenderStateBlendDepth(shaderDatas) {
  29020. var gl = Laya.LayaGL.instance;
  29021. var renderState = this._shaderPass.renderState;
  29022. var datas = shaderDatas.getData();
  29023. var depthWrite = this._getRenderState(datas, Shader3D.RENDER_STATE_DEPTH_WRITE);
  29024. var depthTest = this._getRenderState(datas, Shader3D.RENDER_STATE_DEPTH_TEST);
  29025. var blend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND);
  29026. depthWrite == null && (depthWrite = renderState.depthWrite);
  29027. depthTest == null && (depthTest = renderState.depthTest);
  29028. blend == null && (blend = renderState.blend);
  29029. Laya.WebGLContext.setDepthMask(gl, depthWrite);
  29030. if (depthTest === RenderState.DEPTHTEST_OFF)
  29031. Laya.WebGLContext.setDepthTest(gl, false);
  29032. else {
  29033. Laya.WebGLContext.setDepthTest(gl, true);
  29034. Laya.WebGLContext.setDepthFunc(gl, depthTest);
  29035. }
  29036. switch (blend) {
  29037. case RenderState.BLEND_DISABLE:
  29038. Laya.WebGLContext.setBlend(gl, false);
  29039. break;
  29040. case RenderState.BLEND_ENABLE_ALL:
  29041. var blendEquation = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION);
  29042. var srcBlend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC);
  29043. var dstBlend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST);
  29044. blendEquation == null && (blendEquation = renderState.blendEquation);
  29045. srcBlend == null && (srcBlend = renderState.srcBlend);
  29046. dstBlend == null && (dstBlend = renderState.dstBlend);
  29047. Laya.WebGLContext.setBlend(gl, true);
  29048. Laya.WebGLContext.setBlendEquation(gl, blendEquation);
  29049. Laya.WebGLContext.setBlendFunc(gl, srcBlend, dstBlend);
  29050. break;
  29051. case RenderState.BLEND_ENABLE_SEPERATE:
  29052. var blendEquationRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION_RGB);
  29053. var blendEquationAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION_ALPHA);
  29054. var srcRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC_RGB);
  29055. var dstRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST_RGB);
  29056. var srcAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC_ALPHA);
  29057. var dstAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST_ALPHA);
  29058. blendEquationRGB == null && (blendEquationRGB = renderState.blendEquationRGB);
  29059. blendEquationAlpha == null && (blendEquationAlpha = renderState.blendEquationAlpha);
  29060. srcRGB == null && (srcRGB = renderState.srcBlendRGB);
  29061. dstRGB == null && (dstRGB = renderState.dstBlendRGB);
  29062. srcAlpha == null && (srcAlpha = renderState.srcBlendAlpha);
  29063. dstAlpha == null && (dstAlpha = renderState.dstBlendAlpha);
  29064. Laya.WebGLContext.setBlend(gl, true);
  29065. Laya.WebGLContext.setBlendEquationSeparate(gl, blendEquationRGB, blendEquationAlpha);
  29066. Laya.WebGLContext.setBlendFuncSeperate(gl, srcRGB, dstRGB, srcAlpha, dstAlpha);
  29067. break;
  29068. }
  29069. }
  29070. uploadRenderStateFrontFace(shaderDatas, isTarget, invertFront) {
  29071. var gl = Laya.LayaGL.instance;
  29072. var renderState = this._shaderPass.renderState;
  29073. var datas = shaderDatas.getData();
  29074. var cull = this._getRenderState(datas, Shader3D.RENDER_STATE_CULL);
  29075. cull == null && (cull = renderState.cull);
  29076. var forntFace;
  29077. switch (cull) {
  29078. case RenderState.CULL_NONE:
  29079. Laya.WebGLContext.setCullFace(gl, false);
  29080. break;
  29081. case RenderState.CULL_FRONT:
  29082. Laya.WebGLContext.setCullFace(gl, true);
  29083. if (isTarget) {
  29084. if (invertFront)
  29085. forntFace = gl.CCW;
  29086. else
  29087. forntFace = gl.CW;
  29088. }
  29089. else {
  29090. if (invertFront)
  29091. forntFace = gl.CW;
  29092. else
  29093. forntFace = gl.CCW;
  29094. }
  29095. Laya.WebGLContext.setFrontFace(gl, forntFace);
  29096. break;
  29097. case RenderState.CULL_BACK:
  29098. Laya.WebGLContext.setCullFace(gl, true);
  29099. if (isTarget) {
  29100. if (invertFront)
  29101. forntFace = gl.CW;
  29102. else
  29103. forntFace = gl.CCW;
  29104. }
  29105. else {
  29106. if (invertFront)
  29107. forntFace = gl.CCW;
  29108. else
  29109. forntFace = gl.CW;
  29110. }
  29111. Laya.WebGLContext.setFrontFace(gl, forntFace);
  29112. break;
  29113. }
  29114. }
  29115. uploadCustomUniform(index, data) {
  29116. Laya.Stat.shaderCall += Laya.LayaGLRunner.uploadCustomUniform(Laya.LayaGL.instance, this._customUniformParamsMap, index, data);
  29117. }
  29118. _uniformMatrix2fvForNative(one, value) {
  29119. Laya.LayaGL.instance.uniformMatrix2fvEx(one.location, false, value);
  29120. return 1;
  29121. }
  29122. _uniformMatrix3fvForNative(one, value) {
  29123. Laya.LayaGL.instance.uniformMatrix3fvEx(one.location, false, value);
  29124. return 1;
  29125. }
  29126. _uniformMatrix4fvForNative(one, m) {
  29127. Laya.LayaGL.instance.uniformMatrix4fvEx(one.location, false, m);
  29128. return 1;
  29129. }
  29130. }
  29131. class ShaderPass extends Laya.ShaderCompile {
  29132. constructor(owner, vs, ps, stateMap) {
  29133. super(vs, ps, null);
  29134. this._cacheSharders = {};
  29135. this._cacheShaderHierarchy = 1;
  29136. this._renderState = new RenderState();
  29137. this._validDefine = new DefineDatas();
  29138. this._owner = owner;
  29139. this._stateMap = stateMap;
  29140. for (var k in this.defs)
  29141. this._validDefine.add(Shader3D.getDefineByName(k));
  29142. }
  29143. get renderState() {
  29144. return this._renderState;
  29145. }
  29146. _compileToTree(parent, lines, start, includefiles, defs) {
  29147. var node, preNode;
  29148. var text, name, fname;
  29149. var ofs, words, noUseNode;
  29150. var i, n, j;
  29151. for (i = start; i < lines.length; i++) {
  29152. text = lines[i];
  29153. if (text.length < 1)
  29154. continue;
  29155. ofs = text.indexOf("//");
  29156. if (ofs === 0)
  29157. continue;
  29158. if (ofs >= 0)
  29159. text = text.substr(0, ofs);
  29160. node = noUseNode || new Laya.ShaderNode(includefiles);
  29161. noUseNode = null;
  29162. node.text = text;
  29163. if ((ofs = text.indexOf("#")) >= 0) {
  29164. name = "#";
  29165. for (j = ofs + 1, n = text.length; j < n; j++) {
  29166. var c = text.charAt(j);
  29167. if (c === ' ' || c === '\t' || c === '?')
  29168. break;
  29169. name += c;
  29170. }
  29171. node.name = name;
  29172. switch (name) {
  29173. case "#ifdef":
  29174. case "#ifndef":
  29175. node.setParent(parent);
  29176. parent = node;
  29177. if (defs) {
  29178. words = text.substr(j).split(Laya.ShaderCompile._splitToWordExps3);
  29179. for (j = 0; j < words.length; j++) {
  29180. text = words[j];
  29181. text.length && (defs[text] = true);
  29182. }
  29183. }
  29184. continue;
  29185. case "#if":
  29186. case "#elif":
  29187. node.setParent(parent);
  29188. parent = node;
  29189. if (defs) {
  29190. words = text.substr(j).split(Laya.ShaderCompile._splitToWordExps3);
  29191. for (j = 0; j < words.length; j++) {
  29192. text = words[j];
  29193. text.length && text != "defined" && (defs[text] = true);
  29194. }
  29195. }
  29196. continue;
  29197. case "#else":
  29198. parent = parent.parent;
  29199. preNode = parent.childs[parent.childs.length - 1];
  29200. node.setParent(parent);
  29201. parent = node;
  29202. continue;
  29203. case "#endif":
  29204. parent = parent.parent;
  29205. preNode = parent.childs[parent.childs.length - 1];
  29206. node.setParent(parent);
  29207. continue;
  29208. case "#include":
  29209. words = Laya.ShaderCompile.splitToWords(text, null);
  29210. var inlcudeFile = Laya.ShaderCompile.includes[words[1]];
  29211. if (!inlcudeFile) {
  29212. throw "ShaderCompile error no this include file:" + words[1];
  29213. }
  29214. if ((ofs = words[0].indexOf("?")) < 0) {
  29215. node.setParent(parent);
  29216. text = inlcudeFile.getWith(words[2] == 'with' ? words[3] : null);
  29217. this._compileToTree(node, text.split('\n'), 0, includefiles, defs);
  29218. node.text = "";
  29219. continue;
  29220. }
  29221. node.setCondition(words[0].substr(ofs + 1), Laya.ShaderCompile.IFDEF_YES);
  29222. node.text = inlcudeFile.getWith(words[2] == 'with' ? words[3] : null);
  29223. break;
  29224. case "#import":
  29225. words = Laya.ShaderCompile.splitToWords(text, null);
  29226. fname = words[1];
  29227. includefiles.push({ node: node, file: Laya.ShaderCompile.includes[fname], ofs: node.text.length });
  29228. continue;
  29229. }
  29230. }
  29231. else {
  29232. preNode = parent.childs[parent.childs.length - 1];
  29233. if (preNode && !preNode.name) {
  29234. includefiles.length > 0 && Laya.ShaderCompile.splitToWords(text, preNode);
  29235. noUseNode = node;
  29236. preNode.text += "\n" + text;
  29237. continue;
  29238. }
  29239. includefiles.length > 0 && Laya.ShaderCompile.splitToWords(text, node);
  29240. }
  29241. node.setParent(parent);
  29242. }
  29243. }
  29244. _resizeCacheShaderMap(cacheMap, hierarchy, resizeLength) {
  29245. var end = this._cacheShaderHierarchy - 1;
  29246. if (hierarchy == end) {
  29247. for (var k in cacheMap) {
  29248. var shader = cacheMap[k];
  29249. for (var i = 0, n = resizeLength - end; i < n; i++) {
  29250. if (i == n - 1)
  29251. cacheMap[0] = shader;
  29252. else
  29253. cacheMap = cacheMap[i == 0 ? k : 0] = {};
  29254. }
  29255. }
  29256. this._cacheShaderHierarchy = resizeLength;
  29257. }
  29258. else {
  29259. for (var k in cacheMap)
  29260. this._resizeCacheShaderMap(cacheMap[k], ++hierarchy, resizeLength);
  29261. }
  29262. }
  29263. _addDebugShaderVariantCollection(compileDefine) {
  29264. var dbugShaderVariantInfo = Shader3D._debugShaderVariantInfo;
  29265. var debugSubShader = this._owner;
  29266. var debugShader = debugSubShader._owner;
  29267. var deugDefines = ShaderPass._debugDefineString;
  29268. Shader3D._getNamesByDefineData(compileDefine, deugDefines);
  29269. if (!Config3D._config._multiLighting) {
  29270. var index = deugDefines.indexOf("LEGACYSINGLELIGHTING");
  29271. (index !== -1) && (deugDefines.splice(index, 1));
  29272. }
  29273. if (dbugShaderVariantInfo)
  29274. dbugShaderVariantInfo.setValue(debugShader, debugShader._subShaders.indexOf(debugSubShader), debugSubShader._passes.indexOf(this), deugDefines);
  29275. else
  29276. Shader3D._debugShaderVariantInfo = dbugShaderVariantInfo = new ShaderVariant(debugShader, debugShader._subShaders.indexOf(debugSubShader), debugSubShader._passes.indexOf(this), deugDefines);
  29277. Shader3D.debugShaderVariantCollection.add(dbugShaderVariantInfo);
  29278. }
  29279. withCompile(compileDefine) {
  29280. compileDefine._intersectionDefineDatas(this._validDefine);
  29281. if (Shader3D.debugMode)
  29282. this._addDebugShaderVariantCollection(compileDefine);
  29283. var cacheShaders = this._cacheSharders;
  29284. var maskLength = compileDefine._length;
  29285. if (maskLength > this._cacheShaderHierarchy) {
  29286. this._resizeCacheShaderMap(cacheShaders, 0, maskLength);
  29287. this._cacheShaderHierarchy = maskLength;
  29288. }
  29289. var mask = compileDefine._mask;
  29290. var endIndex = compileDefine._length - 1;
  29291. var maxEndIndex = this._cacheShaderHierarchy - 1;
  29292. for (var i = 0; i < maxEndIndex; i++) {
  29293. var subMask = endIndex < i ? 0 : mask[i];
  29294. var subCacheShaders = cacheShaders[subMask];
  29295. (subCacheShaders) || (cacheShaders[subMask] = subCacheShaders = {});
  29296. cacheShaders = subCacheShaders;
  29297. }
  29298. var cacheKey = endIndex < maxEndIndex ? 0 : mask[maxEndIndex];
  29299. var shader = cacheShaders[cacheKey];
  29300. if (shader)
  29301. return shader;
  29302. var defineString = ShaderPass._defineString;
  29303. Shader3D._getNamesByDefineData(compileDefine, defineString);
  29304. var config = Config3D._config;
  29305. var clusterSlices = config.lightClusterCount;
  29306. var defMap = {};
  29307. var defineStr = "#define MAX_LIGHT_COUNT " + config.maxLightCount + "\n";
  29308. defineStr += "#define MAX_LIGHT_COUNT_PER_CLUSTER " + config._maxAreaLightCountPerClusterAverage + "\n";
  29309. defineStr += "#define CLUSTER_X_COUNT " + clusterSlices.x + "\n";
  29310. defineStr += "#define CLUSTER_Y_COUNT " + clusterSlices.y + "\n";
  29311. defineStr += "#define CLUSTER_Z_COUNT " + clusterSlices.z + "\n";
  29312. for (var i = 0, n = defineString.length; i < n; i++) {
  29313. var def = defineString[i];
  29314. defineStr += "#define " + def + "\n";
  29315. defMap[def] = true;
  29316. }
  29317. var vs = this._VS.toscript(defMap, []);
  29318. var vsVersion = '';
  29319. if (vs[0].indexOf('#version') == 0) {
  29320. vsVersion = vs[0] + '\n';
  29321. vs.shift();
  29322. }
  29323. var ps = this._PS.toscript(defMap, []);
  29324. var psVersion = '';
  29325. if (ps[0].indexOf('#version') == 0) {
  29326. psVersion = ps[0] + '\n';
  29327. ps.shift();
  29328. }
  29329. shader = new ShaderInstance(vsVersion + defineStr + vs.join('\n'), psVersion + defineStr + ps.join('\n'), this._owner._attributeMap || this._owner._owner._attributeMap, this._owner._uniformMap || this._owner._owner._uniformMap, this);
  29330. cacheShaders[cacheKey] = shader;
  29331. if (Shader3D.debugMode) {
  29332. var defStr = "";
  29333. var defMask = "";
  29334. if (!config._multiLighting) {
  29335. compileDefine.remove(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING);
  29336. var index = defineString.indexOf("LEGACYSINGLELIGHTING");
  29337. (index !== -1) && (defineString.splice(index, 1));
  29338. }
  29339. for (var i = 0, n = compileDefine._length; i < n; i++)
  29340. (i == n - 1) ? defMask += mask[i] : defMask += mask[i] + ",";
  29341. for (var i = 0, n = defineString.length; i < n; i++)
  29342. (i == n - 1) ? defStr += defineString[i] : defStr += defineString[i] + ",";
  29343. console.log("%cLayaAir: Shader Compile Information---ShaderName:" + this._owner._owner._name + " SubShaderIndex:" + this._owner._owner._subShaders.indexOf(this._owner) + " PassIndex:" + this._owner._passes.indexOf(this) + " DefineMask:[" + defMask + "]" + " DefineNames:[" + defStr + "]", "color:green");
  29344. }
  29345. return shader;
  29346. }
  29347. }
  29348. ShaderPass._defineString = [];
  29349. ShaderPass._debugDefineString = [];
  29350. class SubShader {
  29351. constructor(attributeMap, uniformMap) {
  29352. this._flags = {};
  29353. this._passes = [];
  29354. this._attributeMap = attributeMap;
  29355. this._uniformMap = uniformMap;
  29356. }
  29357. setFlag(key, value) {
  29358. if (value)
  29359. this._flags[key] = value;
  29360. else
  29361. delete this._flags[key];
  29362. }
  29363. getFlag(key) {
  29364. return this._flags[key];
  29365. }
  29366. addShaderPass(vs, ps, stateMap = null) {
  29367. var shaderPass = new ShaderPass(this, vs, ps, stateMap);
  29368. this._passes.push(shaderPass);
  29369. return shaderPass;
  29370. }
  29371. }
  29372. class ShaderInit3D {
  29373. constructor() {
  29374. }
  29375. static __init__() {
  29376. Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING = Shader3D.getDefineByName("LEGACYSINGLELIGHTING");
  29377. Shader3D.addInclude("Lighting.glsl", LightingGLSL);
  29378. Shader3D.addInclude("ShadowHelper.glsl", ShadowHelperGLSL);
  29379. Shader3D.addInclude("BRDF.glsl", BRDFGLSL);
  29380. Shader3D.addInclude("PBRUtils.glsl", PBRUtilsGLSL);
  29381. Shader3D.addInclude("PBRStandardLighting.glsl", PBRStandardLightingGLSL);
  29382. Shader3D.addInclude("PBRSpecularLighting.glsl", PBRSpecularLightingGLSL);
  29383. Shader3D.addInclude("Colors.glsl", ColorsGLSL);
  29384. Shader3D.addInclude("Sampling.glsl", SamplingGLSL);
  29385. Shader3D.addInclude("StdLib.glsl", StdLibGLSL);
  29386. var attributeMap = {
  29387. 'a_Position': VertexMesh.MESH_POSITION0,
  29388. 'a_Color': VertexMesh.MESH_COLOR0,
  29389. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29390. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29391. 'a_Texcoord1': VertexMesh.MESH_TEXTURECOORDINATE1,
  29392. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29393. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29394. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  29395. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  29396. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  29397. };
  29398. var uniformMap = {
  29399. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29400. 'u_DiffuseTexture': Shader3D.PERIOD_MATERIAL,
  29401. 'u_SpecularTexture': Shader3D.PERIOD_MATERIAL,
  29402. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  29403. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29404. 'u_DiffuseColor': Shader3D.PERIOD_MATERIAL,
  29405. 'u_MaterialSpecular': Shader3D.PERIOD_MATERIAL,
  29406. 'u_Shininess': Shader3D.PERIOD_MATERIAL,
  29407. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29408. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29409. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29410. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  29411. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  29412. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29413. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29414. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29415. 'u_View': Shader3D.PERIOD_CAMERA,
  29416. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  29417. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  29418. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29419. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29420. 'u_FogColor': Shader3D.PERIOD_SCENE,
  29421. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  29422. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  29423. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  29424. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  29425. 'u_shadowMap1': Shader3D.PERIOD_SCENE,
  29426. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  29427. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  29428. 'u_shadowPSSMDistance': Shader3D.PERIOD_SCENE,
  29429. 'u_lightShadowVP': Shader3D.PERIOD_SCENE,
  29430. 'u_shadowPCFoffset': Shader3D.PERIOD_SCENE,
  29431. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  29432. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  29433. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  29434. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  29435. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  29436. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  29437. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  29438. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  29439. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  29440. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  29441. };
  29442. var stateMap = {
  29443. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29444. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29445. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29446. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29447. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29448. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29449. };
  29450. var shader = Shader3D.add("BLINNPHONG", null, null, true);
  29451. var subShader = new SubShader(attributeMap, uniformMap);
  29452. shader.addSubShader(subShader);
  29453. subShader.addShaderPass(MeshBlinnPhongVS, MeshBlinnPhongPS, stateMap);
  29454. attributeMap = {
  29455. 'a_Position': VertexMesh.MESH_POSITION0,
  29456. 'a_Color': VertexMesh.MESH_COLOR0
  29457. };
  29458. uniformMap = {
  29459. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29460. 'u_Color': Shader3D.PERIOD_MATERIAL
  29461. };
  29462. stateMap = {
  29463. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29464. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29465. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29466. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29467. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29468. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29469. };
  29470. shader = Shader3D.add("LineShader");
  29471. subShader = new SubShader(attributeMap, uniformMap);
  29472. shader.addSubShader(subShader);
  29473. subShader.addShaderPass(lineVS, linePS, stateMap);
  29474. attributeMap = {
  29475. 'a_Position': VertexMesh.MESH_POSITION0,
  29476. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29477. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  29478. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29479. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29480. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29481. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  29482. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  29483. };
  29484. uniformMap = {
  29485. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29486. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29487. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29488. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29489. 'u_View': Shader3D.PERIOD_CAMERA,
  29490. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29491. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29492. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29493. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29494. 'u_EmissionColor': Shader3D.PERIOD_MATERIAL,
  29495. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29496. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  29497. 'u_ParallaxTexture': Shader3D.PERIOD_MATERIAL,
  29498. 'u_MetallicGlossTexture': Shader3D.PERIOD_MATERIAL,
  29499. 'u_OcclusionTexture': Shader3D.PERIOD_MATERIAL,
  29500. 'u_EmissionTexture': Shader3D.PERIOD_MATERIAL,
  29501. 'u_metallic': Shader3D.PERIOD_MATERIAL,
  29502. 'u_smoothness': Shader3D.PERIOD_MATERIAL,
  29503. 'u_smoothnessScale': Shader3D.PERIOD_MATERIAL,
  29504. 'u_occlusionStrength': Shader3D.PERIOD_MATERIAL,
  29505. 'u_normalScale': Shader3D.PERIOD_MATERIAL,
  29506. 'u_parallaxScale': Shader3D.PERIOD_MATERIAL,
  29507. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29508. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  29509. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  29510. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  29511. 'u_shadowMap1': Shader3D.PERIOD_SCENE,
  29512. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  29513. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  29514. 'u_shadowPSSMDistance': Shader3D.PERIOD_SCENE,
  29515. 'u_lightShadowVP': Shader3D.PERIOD_SCENE,
  29516. 'u_shadowPCFoffset': Shader3D.PERIOD_SCENE,
  29517. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29518. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29519. 'u_FogColor': Shader3D.PERIOD_SCENE,
  29520. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  29521. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  29522. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  29523. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  29524. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  29525. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  29526. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  29527. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  29528. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  29529. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  29530. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  29531. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  29532. 'u_SpotLight.color': Shader3D.PERIOD_SCENE,
  29533. };
  29534. stateMap = {
  29535. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29536. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29537. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29538. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29539. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29540. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29541. };
  29542. shader = Shader3D.add("PBRStandard", null, null, true);
  29543. subShader = new SubShader(attributeMap, uniformMap);
  29544. shader.addSubShader(subShader);
  29545. subShader.addShaderPass(PBRStandardVS, PBRStandardPS, stateMap);
  29546. attributeMap = {
  29547. 'a_Position': VertexMesh.MESH_POSITION0,
  29548. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29549. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  29550. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29551. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29552. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29553. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  29554. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  29555. };
  29556. uniformMap = {
  29557. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29558. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29559. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29560. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29561. 'u_View': Shader3D.PERIOD_CAMERA,
  29562. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29563. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29564. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29565. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29566. 'u_SpecularColor': Shader3D.PERIOD_MATERIAL,
  29567. 'u_EmissionColor': Shader3D.PERIOD_MATERIAL,
  29568. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29569. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  29570. 'u_ParallaxTexture': Shader3D.PERIOD_MATERIAL,
  29571. 'u_SpecularTexture': Shader3D.PERIOD_MATERIAL,
  29572. 'u_OcclusionTexture': Shader3D.PERIOD_MATERIAL,
  29573. 'u_EmissionTexture': Shader3D.PERIOD_MATERIAL,
  29574. 'u_smoothness': Shader3D.PERIOD_MATERIAL,
  29575. 'u_smoothnessScale': Shader3D.PERIOD_MATERIAL,
  29576. 'u_occlusionStrength': Shader3D.PERIOD_MATERIAL,
  29577. 'u_normalScale': Shader3D.PERIOD_MATERIAL,
  29578. 'u_parallaxScale': Shader3D.PERIOD_MATERIAL,
  29579. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29580. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  29581. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  29582. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  29583. 'u_shadowMap1': Shader3D.PERIOD_SCENE,
  29584. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  29585. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  29586. 'u_shadowPSSMDistance': Shader3D.PERIOD_SCENE,
  29587. 'u_lightShadowVP': Shader3D.PERIOD_SCENE,
  29588. 'u_shadowPCFoffset': Shader3D.PERIOD_SCENE,
  29589. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29590. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29591. 'u_FogColor': Shader3D.PERIOD_SCENE,
  29592. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  29593. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  29594. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  29595. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  29596. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  29597. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  29598. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  29599. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  29600. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  29601. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  29602. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  29603. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  29604. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  29605. };
  29606. stateMap = {
  29607. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29608. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29609. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29610. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29611. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29612. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29613. };
  29614. shader = Shader3D.add("PBRSpecular", null, null, true);
  29615. subShader = new SubShader(attributeMap, uniformMap);
  29616. shader.addSubShader(subShader);
  29617. subShader.addShaderPass(PBRSpecularVS, PBRSpecularPS, stateMap);
  29618. attributeMap = {
  29619. 'a_Position': VertexMesh.MESH_POSITION0,
  29620. 'a_Color': VertexMesh.MESH_COLOR0,
  29621. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29622. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29623. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29624. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0
  29625. };
  29626. uniformMap = {
  29627. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29628. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29629. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29630. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29631. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29632. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29633. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29634. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29635. 'u_FogColor': Shader3D.PERIOD_SCENE
  29636. };
  29637. stateMap = {
  29638. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29639. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29640. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29641. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29642. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29643. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29644. };
  29645. shader = Shader3D.add("Unlit", null, null, true);
  29646. subShader = new SubShader(attributeMap, uniformMap);
  29647. shader.addSubShader(subShader);
  29648. subShader.addShaderPass(UnlitVS, UnlitPS, stateMap);
  29649. attributeMap = {
  29650. 'a_Position': VertexMesh.MESH_POSITION0,
  29651. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29652. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29653. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29654. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0
  29655. };
  29656. uniformMap = {
  29657. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29658. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29659. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29660. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29661. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29662. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29663. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29664. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29665. 'u_FogColor': Shader3D.PERIOD_SCENE
  29666. };
  29667. stateMap = {
  29668. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29669. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29670. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29671. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29672. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29673. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29674. };
  29675. shader = Shader3D.add("Effect", null, null, true);
  29676. subShader = new SubShader(attributeMap, uniformMap);
  29677. shader.addSubShader(subShader);
  29678. subShader.addShaderPass(EffectVS, EffectPS, stateMap);
  29679. attributeMap = {
  29680. 'a_CornerTextureCoordinate': VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0,
  29681. 'a_MeshPosition': VertexShuriKenParticle.PARTICLE_POSITION0,
  29682. 'a_MeshColor': VertexShuriKenParticle.PARTICLE_COLOR0,
  29683. 'a_MeshTextureCoordinate': VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0,
  29684. 'a_ShapePositionStartLifeTime': VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME,
  29685. 'a_DirectionTime': VertexShuriKenParticle.PARTICLE_DIRECTIONTIME,
  29686. 'a_StartColor': VertexShuriKenParticle.PARTICLE_STARTCOLOR0,
  29687. 'a_EndColor': VertexShuriKenParticle.PARTICLE_ENDCOLOR0,
  29688. 'a_StartSize': VertexShuriKenParticle.PARTICLE_STARTSIZE,
  29689. 'a_StartRotation0': VertexShuriKenParticle.PARTICLE_STARTROTATION,
  29690. 'a_StartSpeed': VertexShuriKenParticle.PARTICLE_STARTSPEED,
  29691. 'a_Random0': VertexShuriKenParticle.PARTICLE_RANDOM0,
  29692. 'a_Random1': VertexShuriKenParticle.PARTICLE_RANDOM1,
  29693. 'a_SimulationWorldPostion': VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION,
  29694. 'a_SimulationWorldRotation': VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION
  29695. };
  29696. uniformMap = {
  29697. 'u_Tintcolor': Shader3D.PERIOD_MATERIAL,
  29698. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29699. 'u_texture': Shader3D.PERIOD_MATERIAL,
  29700. 'u_WorldPosition': Shader3D.PERIOD_SPRITE,
  29701. 'u_WorldRotation': Shader3D.PERIOD_SPRITE,
  29702. 'u_PositionScale': Shader3D.PERIOD_SPRITE,
  29703. 'u_SizeScale': Shader3D.PERIOD_SPRITE,
  29704. 'u_ScalingMode': Shader3D.PERIOD_SPRITE,
  29705. 'u_Gravity': Shader3D.PERIOD_SPRITE,
  29706. 'u_ThreeDStartRotation': Shader3D.PERIOD_SPRITE,
  29707. 'u_StretchedBillboardLengthScale': Shader3D.PERIOD_SPRITE,
  29708. 'u_StretchedBillboardSpeedScale': Shader3D.PERIOD_SPRITE,
  29709. 'u_SimulationSpace': Shader3D.PERIOD_SPRITE,
  29710. 'u_CurrentTime': Shader3D.PERIOD_SPRITE,
  29711. 'u_ColorOverLifeGradientAlphas': Shader3D.PERIOD_SPRITE,
  29712. 'u_ColorOverLifeGradientColors': Shader3D.PERIOD_SPRITE,
  29713. 'u_MaxColorOverLifeGradientAlphas': Shader3D.PERIOD_SPRITE,
  29714. 'u_MaxColorOverLifeGradientColors': Shader3D.PERIOD_SPRITE,
  29715. 'u_VOLVelocityConst': Shader3D.PERIOD_SPRITE,
  29716. 'u_VOLVelocityGradientX': Shader3D.PERIOD_SPRITE,
  29717. 'u_VOLVelocityGradientY': Shader3D.PERIOD_SPRITE,
  29718. 'u_VOLVelocityGradientZ': Shader3D.PERIOD_SPRITE,
  29719. 'u_VOLVelocityConstMax': Shader3D.PERIOD_SPRITE,
  29720. 'u_VOLVelocityGradientMaxX': Shader3D.PERIOD_SPRITE,
  29721. 'u_VOLVelocityGradientMaxY': Shader3D.PERIOD_SPRITE,
  29722. 'u_VOLVelocityGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29723. 'u_VOLSpaceType': Shader3D.PERIOD_SPRITE,
  29724. 'u_SOLSizeGradient': Shader3D.PERIOD_SPRITE,
  29725. 'u_SOLSizeGradientX': Shader3D.PERIOD_SPRITE,
  29726. 'u_SOLSizeGradientY': Shader3D.PERIOD_SPRITE,
  29727. 'u_SOLSizeGradientZ': Shader3D.PERIOD_SPRITE,
  29728. 'u_SOLSizeGradientMax': Shader3D.PERIOD_SPRITE,
  29729. 'u_SOLSizeGradientMaxX': Shader3D.PERIOD_SPRITE,
  29730. 'u_SOLSizeGradientMaxY': Shader3D.PERIOD_SPRITE,
  29731. 'u_SOLSizeGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29732. 'u_ROLAngularVelocityConst': Shader3D.PERIOD_SPRITE,
  29733. 'u_ROLAngularVelocityConstSeprarate': Shader3D.PERIOD_SPRITE,
  29734. 'u_ROLAngularVelocityGradient': Shader3D.PERIOD_SPRITE,
  29735. 'u_ROLAngularVelocityGradientX': Shader3D.PERIOD_SPRITE,
  29736. 'u_ROLAngularVelocityGradientY': Shader3D.PERIOD_SPRITE,
  29737. 'u_ROLAngularVelocityGradientZ': Shader3D.PERIOD_SPRITE,
  29738. 'u_ROLAngularVelocityConstMax': Shader3D.PERIOD_SPRITE,
  29739. 'u_ROLAngularVelocityConstMaxSeprarate': Shader3D.PERIOD_SPRITE,
  29740. 'u_ROLAngularVelocityGradientMax': Shader3D.PERIOD_SPRITE,
  29741. 'u_ROLAngularVelocityGradientMaxX': Shader3D.PERIOD_SPRITE,
  29742. 'u_ROLAngularVelocityGradientMaxY': Shader3D.PERIOD_SPRITE,
  29743. 'u_ROLAngularVelocityGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29744. 'u_ROLAngularVelocityGradientMaxW': Shader3D.PERIOD_SPRITE,
  29745. 'u_TSACycles': Shader3D.PERIOD_SPRITE,
  29746. 'u_TSASubUVLength': Shader3D.PERIOD_SPRITE,
  29747. 'u_TSAGradientUVs': Shader3D.PERIOD_SPRITE,
  29748. 'u_TSAMaxGradientUVs': Shader3D.PERIOD_SPRITE,
  29749. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29750. 'u_CameraDirection': Shader3D.PERIOD_CAMERA,
  29751. 'u_CameraUp': Shader3D.PERIOD_CAMERA,
  29752. 'u_View': Shader3D.PERIOD_CAMERA,
  29753. 'u_Projection': Shader3D.PERIOD_CAMERA,
  29754. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29755. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29756. 'u_FogColor': Shader3D.PERIOD_SCENE
  29757. };
  29758. stateMap = {
  29759. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29760. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29761. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29762. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29763. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29764. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29765. };
  29766. shader = Shader3D.add("PARTICLESHURIKEN");
  29767. subShader = new SubShader(attributeMap, uniformMap);
  29768. shader.addSubShader(subShader);
  29769. subShader.addShaderPass(ParticleShuriKenVS, ParticleShuriKenPS, stateMap);
  29770. attributeMap = {
  29771. 'a_Position': VertexMesh.MESH_POSITION0
  29772. };
  29773. uniformMap = {
  29774. 'u_TintColor': Shader3D.PERIOD_MATERIAL,
  29775. 'u_Exposure': Shader3D.PERIOD_MATERIAL,
  29776. 'u_Rotation': Shader3D.PERIOD_MATERIAL,
  29777. 'u_CubeTexture': Shader3D.PERIOD_MATERIAL,
  29778. 'u_ViewProjection': Shader3D.PERIOD_CAMERA
  29779. };
  29780. shader = Shader3D.add("SkyBox");
  29781. subShader = new SubShader(attributeMap, uniformMap);
  29782. shader.addSubShader(subShader);
  29783. subShader.addShaderPass(SkyBoxVS, SkyBoxPS);
  29784. attributeMap = {
  29785. 'a_Position': VertexMesh.MESH_POSITION0
  29786. };
  29787. uniformMap = {
  29788. 'u_SunSize': Shader3D.PERIOD_MATERIAL,
  29789. 'u_SunSizeConvergence': Shader3D.PERIOD_MATERIAL,
  29790. 'u_AtmosphereThickness': Shader3D.PERIOD_MATERIAL,
  29791. 'u_SkyTint': Shader3D.PERIOD_MATERIAL,
  29792. 'u_GroundTint': Shader3D.PERIOD_MATERIAL,
  29793. 'u_Exposure': Shader3D.PERIOD_MATERIAL,
  29794. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  29795. 'u_SunLight.direction': Shader3D.PERIOD_SCENE,
  29796. 'u_SunLight.color': Shader3D.PERIOD_SCENE,
  29797. };
  29798. shader = Shader3D.add("SkyBoxProcedural");
  29799. subShader = new SubShader(attributeMap, uniformMap);
  29800. shader.addSubShader(subShader);
  29801. subShader.addShaderPass(SkyBoxProceduralVS, SkyBoxProceduralPS);
  29802. attributeMap = {
  29803. 'a_Position': VertexMesh.MESH_POSITION0,
  29804. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29805. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0
  29806. };
  29807. uniformMap = {
  29808. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29809. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29810. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29811. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29812. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29813. 'u_View': Shader3D.PERIOD_CAMERA,
  29814. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  29815. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  29816. 'u_SplatAlphaTexture': Shader3D.PERIOD_MATERIAL,
  29817. 'u_DiffuseTexture1': Shader3D.PERIOD_MATERIAL,
  29818. 'u_DiffuseTexture2': Shader3D.PERIOD_MATERIAL,
  29819. 'u_DiffuseTexture3': Shader3D.PERIOD_MATERIAL,
  29820. 'u_DiffuseTexture4': Shader3D.PERIOD_MATERIAL,
  29821. 'u_DiffuseTexture5': Shader3D.PERIOD_MATERIAL,
  29822. 'u_DiffuseScaleOffset1': Shader3D.PERIOD_MATERIAL,
  29823. 'u_DiffuseScaleOffset2': Shader3D.PERIOD_MATERIAL,
  29824. 'u_DiffuseScaleOffset3': Shader3D.PERIOD_MATERIAL,
  29825. 'u_DiffuseScaleOffset4': Shader3D.PERIOD_MATERIAL,
  29826. 'u_DiffuseScaleOffset5': Shader3D.PERIOD_MATERIAL,
  29827. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29828. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29829. 'u_FogColor': Shader3D.PERIOD_SCENE,
  29830. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  29831. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  29832. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  29833. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  29834. 'u_shadowMap1': Shader3D.PERIOD_SCENE,
  29835. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  29836. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  29837. 'u_shadowPSSMDistance': Shader3D.PERIOD_SCENE,
  29838. 'u_lightShadowVP': Shader3D.PERIOD_SCENE,
  29839. 'u_shadowPCFoffset': Shader3D.PERIOD_SCENE,
  29840. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  29841. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  29842. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  29843. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  29844. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  29845. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  29846. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  29847. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  29848. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  29849. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  29850. };
  29851. stateMap = {
  29852. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29853. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29854. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29855. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29856. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29857. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29858. };
  29859. shader = Shader3D.add("ExtendTerrain");
  29860. subShader = new SubShader(attributeMap, uniformMap);
  29861. shader.addSubShader(subShader);
  29862. subShader.addShaderPass(extendTerrainVS, extendTerrainPS, stateMap);
  29863. attributeMap = {
  29864. 'a_Position': VertexTrail.TRAIL_POSITION0,
  29865. 'a_OffsetVector': VertexTrail.TRAIL_OFFSETVECTOR,
  29866. 'a_Texcoord0X': VertexTrail.TRAIL_TEXTURECOORDINATE0X,
  29867. 'a_Texcoord0Y': VertexTrail.TRAIL_TEXTURECOORDINATE0Y,
  29868. 'a_BirthTime': VertexTrail.TRAIL_TIME0,
  29869. 'a_Color': VertexTrail.TRAIL_COLOR
  29870. };
  29871. uniformMap = {
  29872. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29873. 'u_View': Shader3D.PERIOD_CAMERA,
  29874. 'u_Projection': Shader3D.PERIOD_CAMERA,
  29875. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29876. 'u_MainTexture': Shader3D.PERIOD_MATERIAL,
  29877. 'u_MainColor': Shader3D.PERIOD_MATERIAL,
  29878. 'u_CurTime': Shader3D.PERIOD_SPRITE,
  29879. 'u_LifeTime': Shader3D.PERIOD_SPRITE,
  29880. 'u_WidthCurve': Shader3D.PERIOD_SPRITE,
  29881. 'u_WidthCurveKeyLength': Shader3D.PERIOD_SPRITE,
  29882. 'u_GradientColorkey': Shader3D.PERIOD_SPRITE,
  29883. 'u_GradientAlphakey': Shader3D.PERIOD_SPRITE
  29884. };
  29885. stateMap = {
  29886. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29887. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29888. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29889. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29890. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29891. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29892. };
  29893. shader = Shader3D.add("Trail");
  29894. subShader = new SubShader(attributeMap, uniformMap);
  29895. shader.addSubShader(subShader);
  29896. subShader.addShaderPass(TrailVS, TrailPS, stateMap);
  29897. attributeMap = {
  29898. 'a_Position': VertexMesh.MESH_POSITION0,
  29899. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29900. 'a_Tangent0': VertexMesh.MESH_TANGENT0
  29901. };
  29902. uniformMap = {
  29903. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29904. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29905. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29906. 'u_Time': Shader3D.PERIOD_SCENE,
  29907. 'u_MainTexture': Shader3D.PERIOD_MATERIAL,
  29908. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  29909. 'u_HorizonColor': Shader3D.PERIOD_MATERIAL,
  29910. 'u_WaveScale': Shader3D.PERIOD_MATERIAL,
  29911. 'u_WaveSpeed': Shader3D.PERIOD_MATERIAL
  29912. };
  29913. shader = Shader3D.add("WaterPrimary");
  29914. subShader = new SubShader(attributeMap, uniformMap);
  29915. shader.addSubShader(subShader);
  29916. subShader.addShaderPass(WaterPrimaryVS, WaterPrimaryPS);
  29917. attributeMap = {
  29918. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  29919. };
  29920. uniformMap = {
  29921. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  29922. 'u_OffsetScale': Shader3D.PERIOD_MATERIAL
  29923. };
  29924. shader = Shader3D.add("BlitScreen");
  29925. subShader = new SubShader(attributeMap, uniformMap);
  29926. shader.addSubShader(subShader);
  29927. var shaderPass = subShader.addShaderPass(BlitScreenVS, BlitScreenPS);
  29928. var renderState = shaderPass.renderState;
  29929. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29930. renderState.depthWrite = false;
  29931. renderState.cull = RenderState.CULL_NONE;
  29932. renderState.blend = RenderState.BLEND_DISABLE;
  29933. attributeMap = {
  29934. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  29935. };
  29936. uniformMap = {
  29937. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  29938. 'u_BloomTex': Shader3D.PERIOD_MATERIAL,
  29939. 'u_AutoExposureTex': Shader3D.PERIOD_MATERIAL,
  29940. 'u_MainTex_TexelSize': Shader3D.PERIOD_MATERIAL,
  29941. 'u_SampleScale': Shader3D.PERIOD_MATERIAL,
  29942. 'u_Threshold': Shader3D.PERIOD_MATERIAL,
  29943. 'u_Params': Shader3D.PERIOD_MATERIAL
  29944. };
  29945. shader = Shader3D.add("PostProcessBloom");
  29946. subShader = new SubShader(attributeMap, uniformMap);
  29947. shader.addSubShader(subShader);
  29948. shaderPass = subShader.addShaderPass(BloomVS, BloomPrefilter13PS);
  29949. renderState = shaderPass.renderState;
  29950. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29951. renderState.depthWrite = false;
  29952. renderState.cull = RenderState.CULL_NONE;
  29953. renderState.blend = RenderState.BLEND_DISABLE;
  29954. subShader = new SubShader(attributeMap, uniformMap);
  29955. shader.addSubShader(subShader);
  29956. shaderPass = subShader.addShaderPass(BloomVS, BloomPrefilter4PS);
  29957. renderState = shaderPass.renderState;
  29958. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29959. renderState.depthWrite = false;
  29960. renderState.cull = RenderState.CULL_NONE;
  29961. renderState.blend = RenderState.BLEND_DISABLE;
  29962. subShader = new SubShader(attributeMap, uniformMap);
  29963. shader.addSubShader(subShader);
  29964. shaderPass = subShader.addShaderPass(BloomVS, BloomDownsample13PS);
  29965. renderState = shaderPass.renderState;
  29966. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29967. renderState.depthWrite = false;
  29968. renderState.cull = RenderState.CULL_NONE;
  29969. renderState.blend = RenderState.BLEND_DISABLE;
  29970. subShader = new SubShader(attributeMap, uniformMap);
  29971. shader.addSubShader(subShader);
  29972. shaderPass = subShader.addShaderPass(BloomVS, BloomDownsample4PS);
  29973. renderState = shaderPass.renderState;
  29974. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29975. renderState.depthWrite = false;
  29976. renderState.cull = RenderState.CULL_NONE;
  29977. renderState.blend = RenderState.BLEND_DISABLE;
  29978. subShader = new SubShader(attributeMap, uniformMap);
  29979. shader.addSubShader(subShader);
  29980. shaderPass = subShader.addShaderPass(BloomVS, BloomUpsampleTentPS);
  29981. renderState = shaderPass.renderState;
  29982. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29983. renderState.depthWrite = false;
  29984. renderState.cull = RenderState.CULL_NONE;
  29985. renderState.blend = RenderState.BLEND_DISABLE;
  29986. subShader = new SubShader(attributeMap, uniformMap);
  29987. shader.addSubShader(subShader);
  29988. shaderPass = subShader.addShaderPass(BloomVS, BloomUpsampleBoxPS);
  29989. renderState = shaderPass.renderState;
  29990. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  29991. renderState.depthWrite = false;
  29992. renderState.cull = RenderState.CULL_NONE;
  29993. renderState.blend = RenderState.BLEND_DISABLE;
  29994. attributeMap = {
  29995. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  29996. };
  29997. uniformMap = {
  29998. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  29999. 'u_BloomTex': Shader3D.PERIOD_MATERIAL,
  30000. 'u_AutoExposureTex': Shader3D.PERIOD_MATERIAL,
  30001. 'u_Bloom_DirtTileOffset': Shader3D.PERIOD_MATERIAL,
  30002. 'u_Bloom_DirtTex': Shader3D.PERIOD_MATERIAL,
  30003. 'u_BloomTex_TexelSize': Shader3D.PERIOD_MATERIAL,
  30004. 'u_Bloom_Settings': Shader3D.PERIOD_MATERIAL,
  30005. 'u_Bloom_Color': Shader3D.PERIOD_MATERIAL
  30006. };
  30007. shader = Shader3D.add("PostProcessComposite");
  30008. subShader = new SubShader(attributeMap, uniformMap);
  30009. shader.addSubShader(subShader);
  30010. shaderPass = subShader.addShaderPass(CompositeVS, CompositePS);
  30011. renderState = shaderPass.renderState;
  30012. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30013. renderState.depthWrite = false;
  30014. renderState.cull = RenderState.CULL_NONE;
  30015. renderState.blend = RenderState.BLEND_DISABLE;
  30016. }
  30017. }
  30018. class ParallelSplitShadowMap {
  30019. constructor() {
  30020. this._spiltDistance = [];
  30021. this._currentPSSM = -1;
  30022. this._shadowMapCount = 3;
  30023. this._maxDistance = 200.0;
  30024. this._ratioOfDistance = 1.0 / this._shadowMapCount;
  30025. this._globalParallelLightDir = new Vector3(0, -1, 0);
  30026. this._statesDirty = true;
  30027. this._shadowMapTextureSize = 1024;
  30028. this._scene = null;
  30029. this._boundingSphere = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  30030. this._boundingBox = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  30031. this._frustumPos = new Array((ParallelSplitShadowMap.MAX_PSSM_COUNT + 1) * 4);
  30032. this._uniformDistance = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  30033. this._logDistance = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  30034. this._dimension = new Array(ParallelSplitShadowMap.MAX_PSSM_COUNT + 1);
  30035. this._PCFType = 0;
  30036. this._tempLookAt3 = new Vector3();
  30037. this._tempLookAt4 = new Vector4();
  30038. this._tempValue = new Vector4();
  30039. this._tempPos = new Vector3();
  30040. this._tempLightUp = new Vector3();
  30041. this._tempMin = new Vector4();
  30042. this._tempMax = new Vector4();
  30043. this._tempMatrix44 = new Matrix4x4;
  30044. this._splitFrustumCulling = new BoundFrustum(Matrix4x4.DEFAULT);
  30045. this._tempScaleMatrix44 = new Matrix4x4();
  30046. this._shadowPCFOffset = new Vector2(1.0 / 1024.0, 1.0 / 1024.0);
  30047. this._shaderValueDistance = new Vector4();
  30048. this._shaderValueLightVP = null;
  30049. this.cameras = [];
  30050. this._shaderValueVPs = [];
  30051. var i;
  30052. for (i = 0; i < this._spiltDistance.length; i++) {
  30053. this._spiltDistance[i] = 0.0;
  30054. }
  30055. for (i = 0; i < this._dimension.length; i++) {
  30056. this._dimension[i] = new Vector2();
  30057. }
  30058. for (i = 0; i < this._frustumPos.length; i++) {
  30059. this._frustumPos[i] = new Vector3();
  30060. }
  30061. for (i = 0; i < this._boundingBox.length; i++) {
  30062. this._boundingBox[i] = new BoundBox(new Vector3(), new Vector3());
  30063. }
  30064. for (i = 0; i < this._boundingSphere.length; i++) {
  30065. this._boundingSphere[i] = new BoundSphere(new Vector3(), 0.0);
  30066. }
  30067. Matrix4x4.createScaling(new Vector3(0.5, 0.5, 1.0), this._tempScaleMatrix44);
  30068. this._tempScaleMatrix44.elements[12] = 0.5;
  30069. this._tempScaleMatrix44.elements[13] = 0.5;
  30070. }
  30071. setInfo(scene, maxDistance, globalParallelDir, shadowMapTextureSize, numberOfPSSM, PCFType) {
  30072. if (numberOfPSSM > ParallelSplitShadowMap.MAX_PSSM_COUNT) {
  30073. this._shadowMapCount = ParallelSplitShadowMap.MAX_PSSM_COUNT;
  30074. }
  30075. this._scene = scene;
  30076. this._maxDistance = maxDistance;
  30077. this.shadowMapCount = numberOfPSSM;
  30078. this._globalParallelLightDir = globalParallelDir;
  30079. this._ratioOfDistance = 1.0 / this._shadowMapCount;
  30080. for (var i = 0; i < this._spiltDistance.length; i++) {
  30081. this._spiltDistance[i] = 0.0;
  30082. }
  30083. this._shadowMapTextureSize = shadowMapTextureSize;
  30084. this._shadowPCFOffset.x = 1.0 / this._shadowMapTextureSize;
  30085. this._shadowPCFOffset.y = 1.0 / this._shadowMapTextureSize;
  30086. this.setPCFType(PCFType);
  30087. this._statesDirty = true;
  30088. }
  30089. setPCFType(PCFtype) {
  30090. this._PCFType = PCFtype;
  30091. var defineData = this._scene._shaderValues;
  30092. switch (this._PCFType) {
  30093. case 0:
  30094. defineData.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO);
  30095. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1);
  30096. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2);
  30097. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3);
  30098. break;
  30099. case 1:
  30100. defineData.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1);
  30101. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO);
  30102. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2);
  30103. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3);
  30104. break;
  30105. case 2:
  30106. defineData.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2);
  30107. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO);
  30108. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1);
  30109. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3);
  30110. break;
  30111. case 3:
  30112. defineData.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF3);
  30113. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF_NO);
  30114. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF1);
  30115. defineData.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PCF2);
  30116. break;
  30117. }
  30118. }
  30119. getPCFType() {
  30120. return this._PCFType;
  30121. }
  30122. setFarDistance(value) {
  30123. if (this._maxDistance != value) {
  30124. this._maxDistance = value;
  30125. this._statesDirty = true;
  30126. }
  30127. }
  30128. getFarDistance() {
  30129. return this._maxDistance;
  30130. }
  30131. set shadowMapCount(value) {
  30132. value = value > 0 ? value : 1;
  30133. value = value <= ParallelSplitShadowMap.MAX_PSSM_COUNT ? value : ParallelSplitShadowMap.MAX_PSSM_COUNT;
  30134. if (this._shadowMapCount != value) {
  30135. this._shadowMapCount = value;
  30136. this._ratioOfDistance = 1.0 / this._shadowMapCount;
  30137. this._statesDirty = true;
  30138. this._shaderValueLightVP = new Float32Array(value * 16);
  30139. this._shaderValueVPs.length = value;
  30140. for (var i = 0; i < value; i++)
  30141. this._shaderValueVPs[i] = new Float32Array(this._shaderValueLightVP.buffer, i * 64);
  30142. }
  30143. }
  30144. get shadowMapCount() {
  30145. return this._shadowMapCount;
  30146. }
  30147. _beginSampler(index, sceneCamera) {
  30148. if (index < 0 || index > this._shadowMapCount)
  30149. throw new Error("ParallelSplitShadowMap: beginSample invalid index");
  30150. this._currentPSSM = index;
  30151. this._update(sceneCamera);
  30152. }
  30153. endSampler(sceneCamera) {
  30154. this._currentPSSM = -1;
  30155. }
  30156. _calcAllLightCameraInfo(sceneCamera) {
  30157. if (this._shadowMapCount === 1) {
  30158. this._beginSampler(0, sceneCamera);
  30159. this.endSampler(sceneCamera);
  30160. }
  30161. else {
  30162. for (var i = 0, n = this._shadowMapCount + 1; i < n; i++) {
  30163. this._beginSampler(i, sceneCamera);
  30164. this.endSampler(sceneCamera);
  30165. }
  30166. }
  30167. }
  30168. _recalculate(nearPlane, fieldOfView, aspectRatio) {
  30169. this._calcSplitDistance(nearPlane);
  30170. this._calcBoundingBox(fieldOfView, aspectRatio);
  30171. this._rebuildRenderInfo();
  30172. }
  30173. _update(sceneCamera) {
  30174. var nearPlane = sceneCamera.nearPlane;
  30175. var fieldOfView = sceneCamera.fieldOfView;
  30176. var aspectRatio = sceneCamera.aspectRatio;
  30177. if (this._statesDirty || this.lastNearPlane !== nearPlane || this.lastFieldOfView !== fieldOfView || this.lastAspectRatio !== aspectRatio) {
  30178. this._recalculate(nearPlane, fieldOfView, aspectRatio);
  30179. this._uploadShaderValue();
  30180. this._statesDirty = false;
  30181. this.lastNearPlane = nearPlane;
  30182. this.lastFieldOfView = fieldOfView;
  30183. this.lastAspectRatio = aspectRatio;
  30184. }
  30185. this._calcLightViewProject(sceneCamera);
  30186. }
  30187. _uploadShaderValue() {
  30188. var sceneSV = this._scene._shaderValues;
  30189. switch (this._shadowMapCount) {
  30190. case 1:
  30191. sceneSV.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1);
  30192. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2);
  30193. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3);
  30194. break;
  30195. case 2:
  30196. sceneSV.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2);
  30197. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1);
  30198. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3);
  30199. break;
  30200. case 3:
  30201. sceneSV.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3);
  30202. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1);
  30203. sceneSV.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2);
  30204. break;
  30205. }
  30206. sceneSV.setVector(ILaya3D.Scene3D.SHADOWDISTANCE, this._shaderValueDistance);
  30207. sceneSV.setBuffer(ILaya3D.Scene3D.SHADOWLIGHTVIEWPROJECT, this._shaderValueLightVP);
  30208. sceneSV.setVector2(ILaya3D.Scene3D.SHADOWMAPPCFOFFSET, this._shadowPCFOffset);
  30209. switch (this._shadowMapCount) {
  30210. case 3:
  30211. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE1, this.cameras[1].renderTarget);
  30212. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE2, this.cameras[2].renderTarget);
  30213. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE3, this.cameras[3].renderTarget);
  30214. break;
  30215. case 2:
  30216. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE1, this.cameras[1].renderTarget);
  30217. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE2, this.cameras[2].renderTarget);
  30218. break;
  30219. case 1:
  30220. sceneSV.setTexture(ILaya3D.Scene3D.SHADOWMAPTEXTURE1, this.cameras[1].renderTarget);
  30221. break;
  30222. }
  30223. }
  30224. _calcSplitDistance(nearPlane) {
  30225. var far = this._maxDistance;
  30226. var invNumberOfPSSM = 1.0 / this._shadowMapCount;
  30227. var i;
  30228. for (i = 0; i <= this._shadowMapCount; i++) {
  30229. this._uniformDistance[i] = nearPlane + (far - nearPlane) * i * invNumberOfPSSM;
  30230. }
  30231. var farDivNear = far / nearPlane;
  30232. for (i = 0; i <= this._shadowMapCount; i++) {
  30233. var n = Math.pow(farDivNear, i * invNumberOfPSSM);
  30234. this._logDistance[i] = nearPlane * n;
  30235. }
  30236. for (i = 0; i <= this._shadowMapCount; i++) {
  30237. this._spiltDistance[i] = this._uniformDistance[i] * this._ratioOfDistance + this._logDistance[i] * (1.0 - this._ratioOfDistance);
  30238. }
  30239. this._shaderValueDistance.x = (this._spiltDistance[1] != undefined) && (this._spiltDistance[1]);
  30240. this._shaderValueDistance.y = (this._spiltDistance[2] != undefined) && (this._spiltDistance[2]);
  30241. this._shaderValueDistance.z = (this._spiltDistance[3] != undefined) && (this._spiltDistance[3]);
  30242. this._shaderValueDistance.w = (this._spiltDistance[4] != undefined) && (this._spiltDistance[4]);
  30243. }
  30244. _calcBoundingBox(fieldOfView, aspectRatio) {
  30245. var fov = 3.1415926 * fieldOfView / 180.0;
  30246. var halfTanValue = Math.tan(fov / 2.0);
  30247. var height;
  30248. var width;
  30249. var distance;
  30250. var i;
  30251. for (i = 0; i <= this._shadowMapCount; i++) {
  30252. distance = this._spiltDistance[i];
  30253. height = distance * halfTanValue;
  30254. width = height * aspectRatio;
  30255. var temp = this._frustumPos[i * 4 + 0];
  30256. temp.x = -width;
  30257. temp.y = -height;
  30258. temp.z = -distance;
  30259. temp = this._frustumPos[i * 4 + 1];
  30260. temp.x = width;
  30261. temp.y = -height;
  30262. temp.z = -distance;
  30263. temp = this._frustumPos[i * 4 + 2];
  30264. temp.x = -width;
  30265. temp.y = height;
  30266. temp.z = -distance;
  30267. temp = this._frustumPos[i * 4 + 3];
  30268. temp.x = width;
  30269. temp.y = height;
  30270. temp.z = -distance;
  30271. temp = this._dimension[i];
  30272. temp.x = width;
  30273. temp.y = height;
  30274. }
  30275. var d;
  30276. var min;
  30277. var max;
  30278. var center;
  30279. for (i = 1; i <= this._shadowMapCount; i++) {
  30280. d = this._dimension[i];
  30281. min = this._boundingBox[i].min;
  30282. min.x = -d.x;
  30283. min.y = -d.y;
  30284. min.z = -this._spiltDistance[i];
  30285. max = this._boundingBox[i].max;
  30286. max.x = d.x;
  30287. max.y = d.y;
  30288. max.z = -this._spiltDistance[i - 1];
  30289. center = this._boundingSphere[i].center;
  30290. center.x = (min.x + max.x) * 0.5;
  30291. center.y = (min.y + max.y) * 0.5;
  30292. center.z = (min.z + max.z) * 0.5;
  30293. this._boundingSphere[i].radius = Math.sqrt(Math.pow(max.x - min.x, 2) + Math.pow(max.y - min.y, 2) + Math.pow(max.z - min.z, 2)) * 0.5;
  30294. }
  30295. min = this._boundingBox[0].min;
  30296. d = this._dimension[this._shadowMapCount];
  30297. min.x = -d.x;
  30298. min.y = -d.y;
  30299. min.z = -this._spiltDistance[this._shadowMapCount];
  30300. max = this._boundingBox[0].max;
  30301. max.x = d.x;
  30302. max.y = d.y;
  30303. max.z = -this._spiltDistance[0];
  30304. center = this._boundingSphere[0].center;
  30305. center.x = (min.x + max.x) * 0.5;
  30306. center.y = (min.y + max.y) * 0.5;
  30307. center.z = (min.z + max.z) * 0.5;
  30308. this._boundingSphere[0].radius = Math.sqrt(Math.pow(max.x - min.x, 2) + Math.pow(max.y - min.y, 2) + Math.pow(max.z - min.z, 2)) * 0.5;
  30309. }
  30310. calcSplitFrustum(sceneCamera) {
  30311. if (this._currentPSSM > 0) {
  30312. Matrix4x4.createPerspective(3.1416 * sceneCamera.fieldOfView / 180.0, sceneCamera.aspectRatio, this._spiltDistance[this._currentPSSM - 1], this._spiltDistance[this._currentPSSM], this._tempMatrix44);
  30313. }
  30314. else {
  30315. Matrix4x4.createPerspective(3.1416 * sceneCamera.fieldOfView / 180.0, sceneCamera.aspectRatio, this._spiltDistance[0], this._spiltDistance[this._shadowMapCount], this._tempMatrix44);
  30316. }
  30317. Matrix4x4.multiply(this._tempMatrix44, sceneCamera.viewMatrix, this._tempMatrix44);
  30318. this._splitFrustumCulling.matrix = this._tempMatrix44;
  30319. }
  30320. _rebuildRenderInfo() {
  30321. var nNum = this._shadowMapCount + 1;
  30322. var i;
  30323. this.cameras.length = nNum;
  30324. for (i = 0; i < nNum; i++) {
  30325. if (!this.cameras[i]) {
  30326. var camera = new Camera();
  30327. camera.name = "lightCamera" + i;
  30328. camera.clearColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  30329. this.cameras[i] = camera;
  30330. }
  30331. var shadowMap = this.cameras[i].renderTarget;
  30332. if (shadowMap == null || shadowMap.width != this._shadowMapTextureSize || shadowMap.height != this._shadowMapTextureSize) {
  30333. (shadowMap) && (shadowMap.destroy());
  30334. shadowMap = new RenderTexture(this._shadowMapTextureSize, this._shadowMapTextureSize, Laya.RenderTextureFormat.R8G8B8A8, Laya.RenderTextureDepthFormat.DEPTH_16);
  30335. shadowMap.filterMode = Laya.BaseTexture.FILTERMODE_POINT;
  30336. this.cameras[i].renderTarget = shadowMap;
  30337. }
  30338. }
  30339. }
  30340. _calcLightViewProject(sceneCamera) {
  30341. var boundSphere = this._boundingSphere[this._currentPSSM];
  30342. var cameraMatViewInv = sceneCamera.transform.worldMatrix;
  30343. var radius = boundSphere.radius;
  30344. boundSphere.center.cloneTo(this._tempLookAt3);
  30345. Vector3.transformV3ToV4(this._tempLookAt3, cameraMatViewInv, this._tempLookAt4);
  30346. var lookAt3Element = this._tempLookAt3;
  30347. var lookAt4Element = this._tempLookAt4;
  30348. lookAt3Element.x = lookAt4Element.x;
  30349. lookAt3Element.y = lookAt4Element.y;
  30350. lookAt3Element.z = lookAt4Element.z;
  30351. var lightUpElement = this._tempLightUp;
  30352. sceneCamera.transform.worldMatrix.getForward(ParallelSplitShadowMap._tempVector30);
  30353. var sceneCameraDir = ParallelSplitShadowMap._tempVector30;
  30354. lightUpElement.x = sceneCameraDir.x;
  30355. lightUpElement.y = 1.0;
  30356. lightUpElement.z = sceneCameraDir.z;
  30357. Vector3.normalize(this._tempLightUp, this._tempLightUp);
  30358. Vector3.scale(this._globalParallelLightDir, boundSphere.radius * 4, this._tempPos);
  30359. Vector3.subtract(this._tempLookAt3, this._tempPos, this._tempPos);
  30360. var curLightCamera = this.cameras[this._currentPSSM];
  30361. curLightCamera.transform.position = this._tempPos;
  30362. curLightCamera.transform.lookAt(this._tempLookAt3, this._tempLightUp, false);
  30363. var tempMax = this._tempMax;
  30364. var tempMin = this._tempMin;
  30365. tempMax.x = tempMax.y = tempMax.z = -100000.0;
  30366. tempMax.w = 1.0;
  30367. tempMin.x = tempMin.y = tempMin.z = 100000.0;
  30368. tempMin.w = 1.0;
  30369. Matrix4x4.multiply(curLightCamera.viewMatrix, cameraMatViewInv, this._tempMatrix44);
  30370. var tempValueElement = this._tempValue;
  30371. var corners = [];
  30372. corners.length = 8;
  30373. this._boundingBox[this._currentPSSM].getCorners(corners);
  30374. for (var i = 0; i < 8; i++) {
  30375. var frustumPosElements = corners[i];
  30376. tempValueElement.x = frustumPosElements.x;
  30377. tempValueElement.y = frustumPosElements.y;
  30378. tempValueElement.z = frustumPosElements.z;
  30379. tempValueElement.w = 1.0;
  30380. Vector4.transformByM4x4(this._tempValue, this._tempMatrix44, this._tempValue);
  30381. tempMin.x = (tempValueElement.x < tempMin.x) ? tempValueElement.x : tempMin.x;
  30382. tempMin.y = (tempValueElement.y < tempMin.y) ? tempValueElement.y : tempMin.y;
  30383. tempMin.z = (tempValueElement.z < tempMin.z) ? tempValueElement.z : tempMin.z;
  30384. tempMax.x = (tempValueElement.x > tempMax.x) ? tempValueElement.x : tempMax.x;
  30385. tempMax.y = (tempValueElement.y > tempMax.y) ? tempValueElement.y : tempMax.y;
  30386. tempMax.z = (tempValueElement.z > tempMax.z) ? tempValueElement.z : tempMax.z;
  30387. }
  30388. Vector4.add(this._tempMax, this._tempMin, this._tempValue);
  30389. tempValueElement.x *= 0.5;
  30390. tempValueElement.y *= 0.5;
  30391. tempValueElement.z *= 0.5;
  30392. tempValueElement.w = 1;
  30393. Vector4.transformByM4x4(this._tempValue, curLightCamera.transform.worldMatrix, this._tempValue);
  30394. var distance = Math.abs(-this._tempMax.z);
  30395. var farPlane = distance > this._maxDistance ? distance : this._maxDistance;
  30396. Vector3.scale(this._globalParallelLightDir, farPlane, this._tempPos);
  30397. var tempPosElement = this._tempPos;
  30398. tempPosElement.x = tempValueElement.x - tempPosElement.x;
  30399. tempPosElement.y = tempValueElement.y - tempPosElement.y;
  30400. tempPosElement.z = tempValueElement.z - tempPosElement.z;
  30401. curLightCamera.transform.position = this._tempPos;
  30402. curLightCamera.transform.lookAt(this._tempLookAt3, this._tempLightUp, false);
  30403. Matrix4x4.createOrthoOffCenter(tempMin.x, tempMax.x, tempMin.y, tempMax.y, 1.0, farPlane + 0.5 * (tempMax.z - tempMin.z), curLightCamera.projectionMatrix);
  30404. var projectView = curLightCamera.projectionViewMatrix;
  30405. ParallelSplitShadowMap.multiplyMatrixOutFloat32Array(this._tempScaleMatrix44, projectView, this._shaderValueVPs[this._currentPSSM]);
  30406. this._scene._shaderValues.setBuffer(ILaya3D.Scene3D.SHADOWLIGHTVIEWPROJECT, this._shaderValueLightVP);
  30407. }
  30408. static multiplyMatrixOutFloat32Array(left, right, out) {
  30409. var i, a, b, ai0, ai1, ai2, ai3;
  30410. a = left.elements;
  30411. b = right.elements;
  30412. for (i = 0; i < 4; i++) {
  30413. ai0 = a[i];
  30414. ai1 = a[i + 4];
  30415. ai2 = a[i + 8];
  30416. ai3 = a[i + 12];
  30417. out[i] = ai0 * b[0] + ai1 * b[1] + ai2 * b[2] + ai3 * b[3];
  30418. out[i + 4] = ai0 * b[4] + ai1 * b[5] + ai2 * b[6] + ai3 * b[7];
  30419. out[i + 8] = ai0 * b[8] + ai1 * b[9] + ai2 * b[10] + ai3 * b[11];
  30420. out[i + 12] = ai0 * b[12] + ai1 * b[13] + ai2 * b[14] + ai3 * b[15];
  30421. }
  30422. }
  30423. setShadowMapTextureSize(size) {
  30424. if (size !== this._shadowMapTextureSize) {
  30425. this._shadowMapTextureSize = size;
  30426. this._shadowPCFOffset.x = 1 / this._shadowMapTextureSize;
  30427. this._shadowPCFOffset.y = 1 / this._shadowMapTextureSize;
  30428. this._statesDirty = true;
  30429. }
  30430. }
  30431. disposeAllRenderTarget() {
  30432. for (var i = 0, n = this._shadowMapCount + 1; i < n; i++) {
  30433. if (this.cameras[i].renderTarget) {
  30434. this.cameras[i].renderTarget.destroy();
  30435. this.cameras[i].renderTarget = null;
  30436. }
  30437. }
  30438. }
  30439. }
  30440. ParallelSplitShadowMap.MAX_PSSM_COUNT = 3;
  30441. ParallelSplitShadowMap._tempVector30 = new Vector3();
  30442. class LightSprite extends Sprite3D {
  30443. constructor() {
  30444. super();
  30445. this._isAlternate = false;
  30446. this._intensity = 1.0;
  30447. this._intensityColor = new Vector3();
  30448. this.color = new Vector3(1.0, 1.0, 1.0);
  30449. this._shadow = false;
  30450. this._shadowFarPlane = 8;
  30451. this._shadowMapSize = 512;
  30452. this._shadowMapCount = 1;
  30453. this._shadowMapPCFType = 0;
  30454. this._lightmapBakedType = LightSprite.LIGHTMAPBAKEDTYPE_REALTIME;
  30455. }
  30456. get intensity() {
  30457. return this._intensity;
  30458. }
  30459. set intensity(value) {
  30460. this._intensity = value;
  30461. }
  30462. get shadow() {
  30463. return this._shadow;
  30464. }
  30465. set shadow(value) {
  30466. throw new Error("LightSprite: must override it.");
  30467. }
  30468. get shadowDistance() {
  30469. return this._shadowFarPlane;
  30470. }
  30471. set shadowDistance(value) {
  30472. this._shadowFarPlane = value;
  30473. (this._parallelSplitShadowMap) && (this._parallelSplitShadowMap.setFarDistance(value));
  30474. }
  30475. get shadowResolution() {
  30476. return this._shadowMapSize;
  30477. }
  30478. set shadowResolution(value) {
  30479. this._shadowMapSize = value;
  30480. (this._parallelSplitShadowMap) && (this._parallelSplitShadowMap.setShadowMapTextureSize(value));
  30481. }
  30482. get shadowPSSMCount() {
  30483. return this._shadowMapCount;
  30484. }
  30485. set shadowPSSMCount(value) {
  30486. this._shadowMapCount = value;
  30487. (this._parallelSplitShadowMap) && (this._parallelSplitShadowMap.shadowMapCount = value);
  30488. }
  30489. get shadowPCFType() {
  30490. return this._shadowMapPCFType;
  30491. }
  30492. set shadowPCFType(value) {
  30493. this._shadowMapPCFType = value;
  30494. (this._parallelSplitShadowMap) && (this._parallelSplitShadowMap.setPCFType(value));
  30495. }
  30496. get lightmapBakedType() {
  30497. return this._lightmapBakedType;
  30498. }
  30499. set lightmapBakedType(value) {
  30500. if (this._lightmapBakedType !== value) {
  30501. this._lightmapBakedType = value;
  30502. if (this.activeInHierarchy) {
  30503. if (value !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED)
  30504. this._addToScene();
  30505. else
  30506. this._removeFromScene();
  30507. }
  30508. }
  30509. }
  30510. _parse(data, spriteMap) {
  30511. super._parse(data, spriteMap);
  30512. var colorData = data.color;
  30513. this.color.fromArray(colorData);
  30514. this.intensity = data.intensity;
  30515. this.lightmapBakedType = data.lightmapBakedType;
  30516. }
  30517. _addToScene() {
  30518. var scene = this._scene;
  30519. var maxLightCount = Config3D._config.maxLightCount;
  30520. if (scene._lightCount < maxLightCount) {
  30521. scene._lightCount++;
  30522. this._addToLightQueue();
  30523. this._isAlternate = false;
  30524. }
  30525. else {
  30526. scene._alternateLights.add(this);
  30527. this._isAlternate = true;
  30528. console.warn("LightSprite:light count has large than maxLightCount,the latest added light will be ignore.");
  30529. }
  30530. }
  30531. _removeFromScene() {
  30532. var scene = this._scene;
  30533. if (this._isAlternate) {
  30534. scene._alternateLights.remove(this);
  30535. }
  30536. else {
  30537. scene._lightCount--;
  30538. this._removeFromLightQueue();
  30539. if (scene._alternateLights._length > 0) {
  30540. var alternateLight = scene._alternateLights.shift();
  30541. alternateLight._addToLightQueue();
  30542. alternateLight._isAlternate = false;
  30543. scene._lightCount++;
  30544. }
  30545. }
  30546. }
  30547. _addToLightQueue() {
  30548. }
  30549. _removeFromLightQueue() {
  30550. }
  30551. _onActive() {
  30552. super._onActive();
  30553. (this.lightmapBakedType !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED) && (this._addToScene());
  30554. }
  30555. _onInActive() {
  30556. super._onInActive();
  30557. (this.lightmapBakedType !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED) && (this._removeFromScene());
  30558. }
  30559. _create() {
  30560. return new LightSprite();
  30561. }
  30562. get diffuseColor() {
  30563. console.log("LightSprite: discard property,please use color property instead.");
  30564. return this.color;
  30565. }
  30566. set diffuseColor(value) {
  30567. console.log("LightSprite: discard property,please use color property instead.");
  30568. this.color = value;
  30569. }
  30570. }
  30571. LightSprite.LIGHTMAPBAKEDTYPE_REALTIME = 0;
  30572. LightSprite.LIGHTMAPBAKEDTYPE_MIXED = 1;
  30573. LightSprite.LIGHTMAPBAKEDTYPE_BAKED = 2;
  30574. class DirectionLight extends LightSprite {
  30575. set shadow(value) {
  30576. if (this._shadow !== value) {
  30577. this._shadow = value;
  30578. (this.scene) && (this._initShadow());
  30579. }
  30580. }
  30581. constructor() {
  30582. super();
  30583. this._direction = new Vector3();
  30584. }
  30585. _initShadow() {
  30586. if (this._shadow) {
  30587. this._parallelSplitShadowMap = new ParallelSplitShadowMap();
  30588. this.scene.parallelSplitShadowMaps.push(this._parallelSplitShadowMap);
  30589. this.transform.worldMatrix.getForward(this._direction);
  30590. Vector3.normalize(this._direction, this._direction);
  30591. this._parallelSplitShadowMap.setInfo(this.scene, this._shadowFarPlane, this._direction, this._shadowMapSize, this._shadowMapCount, this._shadowMapPCFType);
  30592. }
  30593. else {
  30594. var defineDatas = this._scene._shaderValues;
  30595. var parallelSplitShadowMaps = this.scene.parallelSplitShadowMaps;
  30596. parallelSplitShadowMaps.splice(parallelSplitShadowMaps.indexOf(this._parallelSplitShadowMap), 1);
  30597. this._parallelSplitShadowMap.disposeAllRenderTarget();
  30598. this._parallelSplitShadowMap = null;
  30599. defineDatas.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM1);
  30600. defineDatas.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM2);
  30601. defineDatas.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_PSSM3);
  30602. }
  30603. }
  30604. _addToLightQueue() {
  30605. this._scene._directionLights.add(this);
  30606. }
  30607. _removeFromLightQueue() {
  30608. this._scene._directionLights.remove(this);
  30609. }
  30610. }
  30611. class PointLight extends LightSprite {
  30612. get range() {
  30613. return this._range;
  30614. }
  30615. set range(value) {
  30616. this._range = value;
  30617. }
  30618. constructor() {
  30619. super();
  30620. this._range = 6.0;
  30621. }
  30622. _addToLightQueue() {
  30623. this._scene._pointLights.add(this);
  30624. }
  30625. _removeFromLightQueue() {
  30626. this._scene._pointLights.remove(this);
  30627. }
  30628. _parse(data, spriteMap) {
  30629. super._parse(data, spriteMap);
  30630. this.range = data.range;
  30631. }
  30632. }
  30633. class SpotLight extends LightSprite {
  30634. get spotAngle() {
  30635. return this._spotAngle;
  30636. }
  30637. set spotAngle(value) {
  30638. this._spotAngle = Math.max(Math.min(value, 179), 0);
  30639. }
  30640. get range() {
  30641. return this._range;
  30642. }
  30643. set range(value) {
  30644. this._range = value;
  30645. }
  30646. constructor() {
  30647. super();
  30648. this._spotAngle = 30.0;
  30649. this._range = 10.0;
  30650. this._direction = new Vector3();
  30651. }
  30652. _addToLightQueue() {
  30653. this._scene._spotLights.add(this);
  30654. }
  30655. _removeFromLightQueue() {
  30656. this._scene._spotLights.remove(this);
  30657. }
  30658. _parse(data, spriteMap) {
  30659. super._parse(data, spriteMap);
  30660. this.range = data.range;
  30661. this.spotAngle = data.spotAngle;
  30662. }
  30663. }
  30664. class Scene3DUtils {
  30665. static _createSprite3DInstance(nodeData, spriteMap, outBatchSprites) {
  30666. var node;
  30667. switch (nodeData.type) {
  30668. case "Scene3D":
  30669. node = new Scene3D();
  30670. break;
  30671. case "Sprite3D":
  30672. node = new Sprite3D();
  30673. break;
  30674. case "MeshSprite3D":
  30675. node = new MeshSprite3D();
  30676. (outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(node));
  30677. break;
  30678. case "SkinnedMeshSprite3D":
  30679. node = new SkinnedMeshSprite3D();
  30680. break;
  30681. case "ShuriKenParticle3D":
  30682. node = new ShuriKenParticle3D();
  30683. break;
  30684. case "Camera":
  30685. node = new Camera();
  30686. break;
  30687. case "DirectionLight":
  30688. node = new DirectionLight();
  30689. break;
  30690. case "PointLight":
  30691. node = new PointLight();
  30692. break;
  30693. case "SpotLight":
  30694. node = new SpotLight();
  30695. break;
  30696. case "TrailSprite3D":
  30697. node = new TrailSprite3D();
  30698. break;
  30699. default:
  30700. throw new Error("Utils3D:unidentified class type in (.lh) file.");
  30701. }
  30702. var childData = nodeData.child;
  30703. if (childData) {
  30704. for (var i = 0, n = childData.length; i < n; i++) {
  30705. var child = Scene3DUtils._createSprite3DInstance(childData[i], spriteMap, outBatchSprites);
  30706. node.addChild(child);
  30707. }
  30708. }
  30709. spriteMap[nodeData.instanceID] = node;
  30710. return node;
  30711. }
  30712. static _createComponentInstance(nodeData, spriteMap) {
  30713. var node = spriteMap[nodeData.instanceID];
  30714. node._parse(nodeData.props, spriteMap);
  30715. var childData = nodeData.child;
  30716. if (childData) {
  30717. for (var i = 0, n = childData.length; i < n; i++)
  30718. Scene3DUtils._createComponentInstance(childData[i], spriteMap);
  30719. }
  30720. var componentsData = nodeData.components;
  30721. if (componentsData) {
  30722. for (var j = 0, m = componentsData.length; j < m; j++) {
  30723. var data = componentsData[j];
  30724. var clas = Laya.ClassUtils.getRegClass(data.type);
  30725. if (clas) {
  30726. var component = node.addComponent(clas);
  30727. component._parse(data);
  30728. }
  30729. else {
  30730. console.warn("Unkown component type.");
  30731. }
  30732. }
  30733. }
  30734. }
  30735. static _createNodeByJson02(nodeData, outBatchSprites) {
  30736. var spriteMap = {};
  30737. var node = Scene3DUtils._createSprite3DInstance(nodeData, spriteMap, outBatchSprites);
  30738. Scene3DUtils._createComponentInstance(nodeData, spriteMap);
  30739. return node;
  30740. }
  30741. static _parse(data, propertyParams = null, constructParams = null) {
  30742. var json = data.data;
  30743. var outBatchSprits = [];
  30744. var sprite;
  30745. switch (data.version) {
  30746. case "LAYAHIERARCHY:02":
  30747. sprite = Scene3DUtils._createNodeByJson02(json, outBatchSprits);
  30748. break;
  30749. default:
  30750. sprite = Scene3DUtils._createNodeByJson(json, outBatchSprits);
  30751. }
  30752. StaticBatchManager.combine(sprite, outBatchSprits);
  30753. return sprite;
  30754. }
  30755. static _parseScene(data, propertyParams = null, constructParams = null) {
  30756. var json = data.data;
  30757. var outBatchSprits = [];
  30758. var scene;
  30759. switch (data.version) {
  30760. case "LAYASCENE3D:02":
  30761. scene = Scene3DUtils._createNodeByJson02(json, outBatchSprits);
  30762. break;
  30763. default:
  30764. scene = Scene3DUtils._createNodeByJson(json, outBatchSprits);
  30765. }
  30766. StaticBatchManager.combine(null, outBatchSprits);
  30767. return scene;
  30768. }
  30769. static _createNodeByJson(nodeData, outBatchSprites) {
  30770. var node;
  30771. switch (nodeData.type) {
  30772. case "Scene3D":
  30773. node = new Scene3D();
  30774. break;
  30775. case "Sprite3D":
  30776. node = new Sprite3D();
  30777. break;
  30778. case "MeshSprite3D":
  30779. node = new MeshSprite3D();
  30780. (outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(node));
  30781. break;
  30782. case "SkinnedMeshSprite3D":
  30783. node = new SkinnedMeshSprite3D();
  30784. break;
  30785. case "ShuriKenParticle3D":
  30786. node = new ShuriKenParticle3D();
  30787. break;
  30788. case "Camera":
  30789. node = new Camera();
  30790. break;
  30791. case "DirectionLight":
  30792. node = new DirectionLight();
  30793. break;
  30794. case "PointLight":
  30795. node = new PointLight();
  30796. break;
  30797. case "SpotLight":
  30798. node = new SpotLight();
  30799. break;
  30800. case "TrailSprite3D":
  30801. node = new TrailSprite3D();
  30802. break;
  30803. default:
  30804. throw new Error("Utils3D:unidentified class type in (.lh) file.");
  30805. }
  30806. var childData = nodeData.child;
  30807. if (childData) {
  30808. for (var i = 0, n = childData.length; i < n; i++) {
  30809. var child = Scene3DUtils._createNodeByJson(childData[i], outBatchSprites);
  30810. node.addChild(child);
  30811. }
  30812. }
  30813. var componentsData = nodeData.components;
  30814. if (componentsData) {
  30815. for (var j = 0, m = componentsData.length; j < m; j++) {
  30816. var data = componentsData[j];
  30817. var clas = Laya.ClassUtils.getRegClass(data.type);
  30818. if (clas) {
  30819. var component = node.addComponent(clas);
  30820. component._parse(data);
  30821. }
  30822. else {
  30823. console.warn("Unkown component type.");
  30824. }
  30825. }
  30826. }
  30827. node._parse(nodeData.props, null);
  30828. return node;
  30829. }
  30830. }
  30831. class Laya3D {
  30832. constructor() {
  30833. }
  30834. static get enablePhysics() {
  30835. return Physics3D._enablePhysics;
  30836. }
  30837. static _cancelLoadByUrl(url) {
  30838. Laya.Laya.loader.cancelLoadByUrl(url);
  30839. Laya3D._innerFirstLevelLoaderManager.cancelLoadByUrl(url);
  30840. Laya3D._innerSecondLevelLoaderManager.cancelLoadByUrl(url);
  30841. Laya3D._innerThirdLevelLoaderManager.cancelLoadByUrl(url);
  30842. Laya3D._innerFourthLevelLoaderManager.cancelLoadByUrl(url);
  30843. }
  30844. static _changeWebGLSize(width, height) {
  30845. Laya.WebGL.onStageResize(width, height);
  30846. RenderContext3D.clientWidth = width;
  30847. RenderContext3D.clientHeight = height;
  30848. }
  30849. static __init__(width, height, config) {
  30850. Laya.Config.isAntialias = config.isAntialias;
  30851. Laya.Config.isAlpha = config.isAlpha;
  30852. Laya.Config.premultipliedAlpha = config.premultipliedAlpha;
  30853. Laya.Config.isStencil = config.isStencil;
  30854. if (!Laya.WebGL.enable()) {
  30855. alert("Laya3D init error,must support webGL!");
  30856. return;
  30857. }
  30858. Laya.RunDriver.changeWebGLSize = Laya3D._changeWebGLSize;
  30859. Laya.Render.is3DMode = true;
  30860. Laya.Laya.init(width, height);
  30861. if (!Laya.Render.supportWebGLPlusRendering) {
  30862. Laya.LayaGL.instance = Laya.WebGLContext.mainContext;
  30863. Laya.LayaGL.instance.createCommandEncoder = function (reserveSize = 128, adjustSize = 64, isSyncToRenderThread = false) {
  30864. return new Laya.CommandEncoder(this, reserveSize, adjustSize, isSyncToRenderThread);
  30865. };
  30866. }
  30867. config._multiLighting = config.enableMultiLight && SystemUtils.supportTextureFormat(Laya.TextureFormat.R32G32B32A32);
  30868. ILaya3D.Shader3D = Shader3D;
  30869. ILaya3D.Scene3D = Scene3D;
  30870. ILaya3D.MeshRenderStaticBatchManager = MeshRenderStaticBatchManager;
  30871. ILaya3D.MeshRenderDynamicBatchManager = MeshRenderDynamicBatchManager;
  30872. ILaya3D.SubMeshDynamicBatch = SubMeshDynamicBatch;
  30873. ILaya3D.Laya3D = Laya3D;
  30874. ILaya3D.Matrix4x4 = Matrix4x4;
  30875. Laya3D.enableNative3D();
  30876. VertexElementFormat.__init__();
  30877. VertexMesh.__init__();
  30878. VertexShurikenParticleBillboard.__init__();
  30879. VertexShurikenParticleMesh.__init__();
  30880. VertexPositionTexture0.__init__();
  30881. VertexTrail.__init__();
  30882. VertexPositionTerrain.__init__();
  30883. PixelLineVertex.__init__();
  30884. SubMeshInstanceBatch.__init__();
  30885. SubMeshDynamicBatch.__init__();
  30886. Physics3D._bullet = window.Physics3D;
  30887. if (Physics3D._bullet) {
  30888. StaticPlaneColliderShape.__init__();
  30889. ColliderShape.__init__();
  30890. CompoundColliderShape.__init__();
  30891. PhysicsComponent.__init__();
  30892. PhysicsSimulation.__init__();
  30893. BoxColliderShape.__init__();
  30894. CylinderColliderShape.__init__();
  30895. CharacterController.__init__();
  30896. Rigidbody3D.__init__();
  30897. }
  30898. ShaderInit3D.__init__();
  30899. Mesh.__init__();
  30900. PrimitiveMesh.__init__();
  30901. Sprite3D.__init__();
  30902. RenderableSprite3D.__init__();
  30903. MeshSprite3D.__init__();
  30904. SkinnedMeshSprite3D.__init__();
  30905. ShuriKenParticle3D.__init__();
  30906. TrailSprite3D.__init__();
  30907. PostProcess.__init__();
  30908. Scene3D.__init__();
  30909. MeshRenderStaticBatchManager.__init__();
  30910. Material.__initDefine__();
  30911. BaseMaterial.__initDefine__();
  30912. BlinnPhongMaterial.__initDefine__();
  30913. PBRStandardMaterial.__initDefine__();
  30914. PBRSpecularMaterial.__initDefine__();
  30915. SkyProceduralMaterial.__initDefine__();
  30916. UnlitMaterial.__initDefine__();
  30917. TrailMaterial.__initDefine__();
  30918. EffectMaterial.__initDefine__();
  30919. WaterPrimaryMaterial.__initDefine__();
  30920. ShurikenParticleMaterial.__initDefine__();
  30921. ExtendTerrainMaterial.__initDefine__();
  30922. PixelLineMaterial.__initDefine__();
  30923. SkyBoxMaterial.__initDefine__();
  30924. Command.__init__();
  30925. Laya.ClassUtils.regClass("Laya.EffectMaterial", EffectMaterial);
  30926. Laya.ClassUtils.regClass("Laya.UnlitMaterial", UnlitMaterial);
  30927. Laya.ClassUtils.regClass("Laya.BlinnPhongMaterial", BlinnPhongMaterial);
  30928. Laya.ClassUtils.regClass("Laya.SkyProceduralMaterial", SkyProceduralMaterial);
  30929. Laya.ClassUtils.regClass("Laya.PBRStandardMaterial", PBRStandardMaterial);
  30930. Laya.ClassUtils.regClass("Laya.PBRSpecularMaterial", PBRSpecularMaterial);
  30931. Laya.ClassUtils.regClass("Laya.SkyBoxMaterial", SkyBoxMaterial);
  30932. Laya.ClassUtils.regClass("Laya.WaterPrimaryMaterial", WaterPrimaryMaterial);
  30933. Laya.ClassUtils.regClass("Laya.ExtendTerrainMaterial", ExtendTerrainMaterial);
  30934. Laya.ClassUtils.regClass("Laya.ShurikenParticleMaterial", ShurikenParticleMaterial);
  30935. Laya.ClassUtils.regClass("Laya.TrailMaterial", TrailMaterial);
  30936. Laya.ClassUtils.regClass("Laya.PhysicsCollider", PhysicsCollider);
  30937. Laya.ClassUtils.regClass("Laya.Rigidbody3D", Rigidbody3D);
  30938. Laya.ClassUtils.regClass("Laya.CharacterController", CharacterController);
  30939. Laya.ClassUtils.regClass("Laya.Animator", Animator);
  30940. Laya.ClassUtils.regClass("PhysicsCollider", PhysicsCollider);
  30941. Laya.ClassUtils.regClass("CharacterController", CharacterController);
  30942. Laya.ClassUtils.regClass("Animator", Animator);
  30943. Laya.ClassUtils.regClass("Rigidbody3D", Rigidbody3D);
  30944. PixelLineMaterial.defaultMaterial = new PixelLineMaterial();
  30945. BlinnPhongMaterial.defaultMaterial = new BlinnPhongMaterial();
  30946. EffectMaterial.defaultMaterial = new EffectMaterial();
  30947. PBRStandardMaterial.defaultMaterial = new PBRStandardMaterial();
  30948. PBRSpecularMaterial.defaultMaterial = new PBRSpecularMaterial();
  30949. UnlitMaterial.defaultMaterial = new UnlitMaterial();
  30950. ShurikenParticleMaterial.defaultMaterial = new ShurikenParticleMaterial();
  30951. TrailMaterial.defaultMaterial = new TrailMaterial();
  30952. SkyProceduralMaterial.defaultMaterial = new SkyProceduralMaterial();
  30953. SkyBoxMaterial.defaultMaterial = new SkyBoxMaterial();
  30954. WaterPrimaryMaterial.defaultMaterial = new WaterPrimaryMaterial();
  30955. PixelLineMaterial.defaultMaterial.lock = true;
  30956. BlinnPhongMaterial.defaultMaterial.lock = true;
  30957. EffectMaterial.defaultMaterial.lock = true;
  30958. PBRStandardMaterial.defaultMaterial.lock = true;
  30959. PBRSpecularMaterial.defaultMaterial.lock = true;
  30960. UnlitMaterial.defaultMaterial.lock = true;
  30961. ShurikenParticleMaterial.defaultMaterial.lock = true;
  30962. TrailMaterial.defaultMaterial.lock = true;
  30963. SkyProceduralMaterial.defaultMaterial.lock = true;
  30964. SkyBoxMaterial.defaultMaterial.lock = true;
  30965. WaterPrimaryMaterial.defaultMaterial.lock = true;
  30966. Laya.Texture2D.__init__();
  30967. TextureCube.__init__();
  30968. SkyBox.__init__();
  30969. SkyDome.__init__();
  30970. ScreenQuad.__init__();
  30971. ScreenTriangle.__init__();
  30972. FrustumCulling.__init__();
  30973. HalfFloatUtils.__init__();
  30974. var createMap = Laya.LoaderManager.createMap;
  30975. createMap["lh"] = [Laya3D.HIERARCHY, Scene3DUtils._parse];
  30976. createMap["ls"] = [Laya3D.HIERARCHY, Scene3DUtils._parseScene];
  30977. createMap["lm"] = [Laya3D.MESH, Mesh._parse];
  30978. createMap["lmat"] = [Laya3D.MATERIAL, Material._parse];
  30979. createMap["ltc"] = [Laya3D.TEXTURECUBE, TextureCube._parse];
  30980. createMap["jpg"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30981. createMap["jpeg"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30982. createMap["bmp"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30983. createMap["gif"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30984. createMap["png"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30985. createMap["dds"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30986. createMap["ktx"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30987. createMap["pvr"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  30988. createMap["lani"] = [Laya3D.ANIMATIONCLIP, AnimationClip._parse];
  30989. createMap["lav"] = [Laya3D.AVATAR, Avatar._parse];
  30990. var parserMap = Laya.Loader.parserMap;
  30991. parserMap[Laya3D.HIERARCHY] = Laya3D._loadHierarchy;
  30992. parserMap[Laya3D.MESH] = Laya3D._loadMesh;
  30993. parserMap[Laya3D.MATERIAL] = Laya3D._loadMaterial;
  30994. parserMap[Laya3D.TEXTURECUBE] = Laya3D._loadTextureCube;
  30995. parserMap[Laya3D.TEXTURE2D] = Laya3D._loadTexture2D;
  30996. parserMap[Laya3D.ANIMATIONCLIP] = Laya3D._loadAnimationClip;
  30997. parserMap[Laya3D.AVATAR] = Laya3D._loadAvatar;
  30998. Laya3D._innerFirstLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  30999. Laya3D._innerSecondLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  31000. Laya3D._innerThirdLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  31001. Laya3D._innerFourthLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  31002. }
  31003. static enableNative3D() {
  31004. var shaderData = ShaderData;
  31005. var shader3D = ShaderInstance;
  31006. var skinnedMeshRender = SkinnedMeshRenderer;
  31007. var avatar = Avatar;
  31008. var frustumCulling = FrustumCulling;
  31009. if (Laya.Render.supportWebGLPlusRendering) {
  31010. shaderData.prototype._initData = shaderData.prototype._initDataForNative;
  31011. shaderData.prototype.setBool = shaderData.prototype.setBoolForNative;
  31012. shaderData.prototype.getBool = shaderData.prototype.getBoolForNative;
  31013. shaderData.prototype.setInt = shaderData.prototype.setIntForNative;
  31014. shaderData.prototype.getInt = shaderData.prototype.getIntForNative;
  31015. shaderData.prototype.setNumber = shaderData.prototype.setNumberForNative;
  31016. shaderData.prototype.getNumber = shaderData.prototype.getNumberForNative;
  31017. shaderData.prototype.setVector = shaderData.prototype.setVectorForNative;
  31018. shaderData.prototype.getVector = shaderData.prototype.getVectorForNative;
  31019. shaderData.prototype.setVector2 = shaderData.prototype.setVector2ForNative;
  31020. shaderData.prototype.getVector2 = shaderData.prototype.getVector2ForNative;
  31021. shaderData.prototype.setVector3 = shaderData.prototype.setVector3ForNative;
  31022. shaderData.prototype.getVector3 = shaderData.prototype.getVector3ForNative;
  31023. shaderData.prototype.setQuaternion = shaderData.prototype.setQuaternionForNative;
  31024. shaderData.prototype.getQuaternion = shaderData.prototype.getQuaternionForNative;
  31025. shaderData.prototype.setMatrix4x4 = shaderData.prototype.setMatrix4x4ForNative;
  31026. shaderData.prototype.getMatrix4x4 = shaderData.prototype.getMatrix4x4ForNative;
  31027. shaderData.prototype.setBuffer = shaderData.prototype.setBufferForNative;
  31028. shaderData.prototype.getBuffer = shaderData.prototype.getBufferForNative;
  31029. shaderData.prototype.setTexture = shaderData.prototype.setTextureForNative;
  31030. shaderData.prototype.getTexture = shaderData.prototype.getTextureForNative;
  31031. shaderData.prototype.setAttribute = shaderData.prototype.setAttributeForNative;
  31032. shaderData.prototype.getAttribute = shaderData.prototype.getAttributeForNative;
  31033. shaderData.prototype.cloneTo = shaderData.prototype.cloneToForNative;
  31034. shaderData.prototype.getData = shaderData.prototype.getDataForNative;
  31035. shader3D.prototype._uniformMatrix2fv = shader3D.prototype._uniformMatrix2fvForNative;
  31036. shader3D.prototype._uniformMatrix3fv = shader3D.prototype._uniformMatrix3fvForNative;
  31037. shader3D.prototype._uniformMatrix4fv = shader3D.prototype._uniformMatrix4fvForNative;
  31038. Laya.LayaGLRunner.uploadShaderUniforms = Laya.LayaGLRunner.uploadShaderUniformsForNative;
  31039. }
  31040. if (Laya.Render.supportWebGLPlusCulling) {
  31041. frustumCulling.renderObjectCulling = FrustumCulling.renderObjectCullingNative;
  31042. }
  31043. if (Laya.Render.supportWebGLPlusAnimation) {
  31044. avatar.prototype._cloneDatasToAnimator = avatar.prototype._cloneDatasToAnimatorNative;
  31045. var animationClip = AnimationClip;
  31046. animationClip.prototype._evaluateClipDatasRealTime = animationClip.prototype._evaluateClipDatasRealTimeForNative;
  31047. skinnedMeshRender.prototype._computeSkinnedData = skinnedMeshRender.prototype._computeSkinnedDataForNative;
  31048. }
  31049. }
  31050. static formatRelativePath(base, value) {
  31051. var path;
  31052. path = base + value;
  31053. var char1 = value.charAt(0);
  31054. if (char1 === ".") {
  31055. var parts = path.split("/");
  31056. for (var i = 0, len = parts.length; i < len; i++) {
  31057. if (parts[i] == '..') {
  31058. var index = i - 1;
  31059. if (index > 0 && parts[index] !== '..') {
  31060. parts.splice(index, 2);
  31061. i -= 2;
  31062. }
  31063. }
  31064. }
  31065. path = parts.join('/');
  31066. }
  31067. return path;
  31068. }
  31069. static _endLoad(loader, content = null, subResous = null) {
  31070. if (subResous) {
  31071. for (var i = 0, n = subResous.length; i < n; i++) {
  31072. var resou = Laya.Loader.getRes(subResous[i]);
  31073. (resou) && (resou._removeReference());
  31074. }
  31075. }
  31076. loader.endLoad(content);
  31077. }
  31078. static _eventLoadManagerError(msg) {
  31079. Laya.Laya.loader.event(Laya.Event.ERROR, msg);
  31080. }
  31081. static _addHierarchyInnerUrls(urls, urlMap, urlVersion, hierarchyBasePath, path, type, constructParams = null, propertyParams = null) {
  31082. var formatUrl = Laya3D.formatRelativePath(hierarchyBasePath, path);
  31083. (urlVersion) && (formatUrl = formatUrl + urlVersion);
  31084. urls.push({ url: formatUrl, type: type, constructParams: constructParams, propertyParams: propertyParams });
  31085. urlMap.push(formatUrl);
  31086. return formatUrl;
  31087. }
  31088. static _getSprite3DHierarchyInnerUrls(node, firstLevelUrls, secondLevelUrls, thirdLevelUrls, fourthLelUrls, subUrls, urlVersion, hierarchyBasePath) {
  31089. var i, n;
  31090. var props = node.props;
  31091. switch (node.type) {
  31092. case "Scene3D":
  31093. var lightmaps = props.lightmaps;
  31094. for (i = 0, n = lightmaps.length; i < n; i++) {
  31095. var lightMap = lightmaps[i];
  31096. lightMap.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, lightMap.path, Laya3D.TEXTURE2D, lightMap.constructParams, lightMap.propertyParams);
  31097. }
  31098. var reflectionTextureData = props.reflectionTexture;
  31099. (reflectionTextureData) && (props.reflectionTexture = Laya3D._addHierarchyInnerUrls(thirdLevelUrls, subUrls, urlVersion, hierarchyBasePath, reflectionTextureData, Laya3D.TEXTURECUBE));
  31100. if (props.sky) {
  31101. var skyboxMaterial = props.sky.material;
  31102. (skyboxMaterial) && (skyboxMaterial.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, skyboxMaterial.path, Laya3D.MATERIAL));
  31103. }
  31104. break;
  31105. case "Camera":
  31106. var skyboxMatData = props.skyboxMaterial;
  31107. (skyboxMatData) && (skyboxMatData.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, skyboxMatData.path, Laya3D.MATERIAL));
  31108. break;
  31109. case "TrailSprite3D":
  31110. case "MeshSprite3D":
  31111. case "SkinnedMeshSprite3D":
  31112. var meshPath = props.meshPath;
  31113. (meshPath) && (props.meshPath = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, meshPath, Laya3D.MESH));
  31114. var materials = props.materials;
  31115. if (materials)
  31116. for (i = 0, n = materials.length; i < n; i++)
  31117. materials[i].path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, materials[i].path, Laya3D.MATERIAL);
  31118. break;
  31119. case "ShuriKenParticle3D":
  31120. if (props.main) {
  31121. var resources = props.renderer.resources;
  31122. var mesh = resources.mesh;
  31123. var material = resources.material;
  31124. (mesh) && (resources.mesh = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, mesh, Laya3D.MESH));
  31125. (material) && (resources.material = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, material, Laya3D.MATERIAL));
  31126. }
  31127. else {
  31128. var parMeshPath = props.meshPath;
  31129. (parMeshPath) && (props.meshPath = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, parMeshPath, Laya3D.MESH));
  31130. props.material.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, props.material.path, Laya3D.MATERIAL);
  31131. }
  31132. break;
  31133. case "Terrain":
  31134. Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, props.dataPath, Laya3D.TERRAINRES);
  31135. break;
  31136. }
  31137. var components = node.components;
  31138. if (components) {
  31139. for (var k = 0, p = components.length; k < p; k++) {
  31140. var component = components[k];
  31141. switch (component.type) {
  31142. case "Animator":
  31143. var avatarPath = component.avatarPath;
  31144. var avatarData = component.avatar;
  31145. (avatarData) && (avatarData.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, avatarData.path, Laya3D.AVATAR));
  31146. var clipPaths = component.clipPaths;
  31147. if (!clipPaths) {
  31148. var layersData = component.layers;
  31149. for (i = 0; i < layersData.length; i++) {
  31150. var states = layersData[i].states;
  31151. for (var j = 0, m = states.length; j < m; j++) {
  31152. var clipPath = states[j].clipPath;
  31153. (clipPath) && (states[j].clipPath = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, clipPath, Laya3D.ANIMATIONCLIP));
  31154. }
  31155. }
  31156. }
  31157. else {
  31158. for (i = 0, n = clipPaths.length; i < n; i++)
  31159. clipPaths[i] = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, clipPaths[i], Laya3D.ANIMATIONCLIP);
  31160. }
  31161. break;
  31162. case "PhysicsCollider":
  31163. case "Rigidbody3D":
  31164. case "CharacterController":
  31165. var shapes = component.shapes;
  31166. for (i = 0; i < shapes.length; i++) {
  31167. var shape = shapes[i];
  31168. if (shape.type === "MeshColliderShape") {
  31169. var mesh = shape.mesh;
  31170. (mesh) && (shape.mesh = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, mesh, Laya3D.MESH));
  31171. }
  31172. }
  31173. break;
  31174. }
  31175. }
  31176. }
  31177. var children = node.child;
  31178. for (i = 0, n = children.length; i < n; i++)
  31179. Laya3D._getSprite3DHierarchyInnerUrls(children[i], firstLevelUrls, secondLevelUrls, thirdLevelUrls, fourthLelUrls, subUrls, urlVersion, hierarchyBasePath);
  31180. }
  31181. static _loadHierarchy(loader) {
  31182. loader.on(Laya.Event.LOADED, null, Laya3D._onHierarchylhLoaded, [loader]);
  31183. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  31184. }
  31185. static _onHierarchylhLoaded(loader, lhData) {
  31186. var url = loader.url;
  31187. var urlVersion = Utils3D.getURLVerion(url);
  31188. var hierarchyBasePath = Laya.URL.getPath(url);
  31189. var firstLevUrls = [];
  31190. var secondLevUrls = [];
  31191. var thirdLevUrls = [];
  31192. var forthLevUrls = [];
  31193. var subUrls = [];
  31194. Laya3D._getSprite3DHierarchyInnerUrls(lhData.data, firstLevUrls, secondLevUrls, thirdLevUrls, forthLevUrls, subUrls, urlVersion, hierarchyBasePath);
  31195. var urlCount = firstLevUrls.length + secondLevUrls.length + forthLevUrls.length;
  31196. var totalProcessCount = urlCount + 1;
  31197. var weight = 1 / totalProcessCount;
  31198. Laya3D._onProcessChange(loader, 0, weight, 1.0);
  31199. if (forthLevUrls.length > 0) {
  31200. var processCeil = urlCount / totalProcessCount;
  31201. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, weight, processCeil], false);
  31202. Laya3D._innerFourthLevelLoaderManager._create(forthLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerForthLevResouLoaded, [loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, weight + processCeil * forthLevUrls.length, processCeil]), processHandler, null, null, null, 1, true);
  31203. }
  31204. else {
  31205. Laya3D._onHierarchyInnerForthLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, weight, processCeil);
  31206. }
  31207. }
  31208. static _onHierarchyInnerForthLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, processOffset, processCeil) {
  31209. (processHandler) && (processHandler.recover());
  31210. if (thirdLevUrls.length > 0) {
  31211. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  31212. Laya3D._innerThirdLevelLoaderManager._create(thirdLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerThirdLevResouLoaded, [loader, process, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset + processCeil * secondLevUrls.length, processCeil]), processHandler, null, null, null, 1, true);
  31213. }
  31214. else {
  31215. Laya3D._onHierarchyInnerThirdLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset, processCeil);
  31216. }
  31217. }
  31218. static _onHierarchyInnerThirdLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset, processCeil) {
  31219. (processHandler) && (processHandler.recover());
  31220. if (secondLevUrls.length > 0) {
  31221. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  31222. Laya3D._innerSecondLevelLoaderManager._create(secondLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerSecondLevResouLoaded, [loader, process, lhData, subUrls, firstLevUrls, processOffset + processCeil * secondLevUrls.length, processCeil]), processHandler, null, null, null, 1, true);
  31223. }
  31224. else {
  31225. Laya3D._onHierarchyInnerSecondLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, processOffset, processCeil);
  31226. }
  31227. }
  31228. static _onHierarchyInnerSecondLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, processOffset, processCeil) {
  31229. (processHandler) && (processHandler.recover());
  31230. if (firstLevUrls.length > 0) {
  31231. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  31232. Laya3D._innerFirstLevelLoaderManager._create(firstLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerFirstLevResouLoaded, [loader, process, lhData, subUrls]), processHandler, null, null, null, 1, true);
  31233. }
  31234. else {
  31235. Laya3D._onHierarchyInnerFirstLevResouLoaded(loader, null, lhData, subUrls);
  31236. }
  31237. }
  31238. static _onHierarchyInnerFirstLevResouLoaded(loader, processHandler, lhData, subUrls) {
  31239. (processHandler) && (processHandler.recover());
  31240. loader._cache = loader._createCache;
  31241. var item = lhData.data.type === "Scene3D" ? Scene3DUtils._parseScene(lhData, loader._propertyParams, loader._constructParams) : Scene3DUtils._parse(lhData, loader._propertyParams, loader._constructParams);
  31242. Laya3D._endLoad(loader, item, subUrls);
  31243. }
  31244. static _loadMesh(loader) {
  31245. loader.on(Laya.Event.LOADED, null, Laya3D._onMeshLmLoaded, [loader]);
  31246. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  31247. }
  31248. static _onMeshLmLoaded(loader, lmData) {
  31249. loader._cache = loader._createCache;
  31250. var mesh = Mesh._parse(lmData, loader._propertyParams, loader._constructParams);
  31251. Laya3D._endLoad(loader, mesh);
  31252. }
  31253. static _loadMaterial(loader) {
  31254. loader.on(Laya.Event.LOADED, null, Laya3D._onMaterilLmatLoaded, [loader]);
  31255. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  31256. }
  31257. static _onMaterilLmatLoaded(loader, lmatData) {
  31258. var url = loader.url;
  31259. var urlVersion = Utils3D.getURLVerion(url);
  31260. var materialBasePath = Laya.URL.getPath(url);
  31261. var urls = [];
  31262. var subUrls = [];
  31263. var customProps = lmatData.customProps;
  31264. var formatSubUrl;
  31265. var version = lmatData.version;
  31266. switch (version) {
  31267. case "LAYAMATERIAL:01":
  31268. case "LAYAMATERIAL:02":
  31269. var i, n;
  31270. var textures = lmatData.props.textures;
  31271. if (textures) {
  31272. for (i = 0, n = textures.length; i < n; i++) {
  31273. var tex2D = textures[i];
  31274. var tex2DPath = tex2D.path;
  31275. if (tex2DPath) {
  31276. formatSubUrl = Laya3D.formatRelativePath(materialBasePath, tex2DPath);
  31277. (urlVersion) && (formatSubUrl = formatSubUrl + urlVersion);
  31278. urls.push({ url: formatSubUrl, constructParams: tex2D.constructParams, propertyParams: tex2D.propertyParams });
  31279. subUrls.push(formatSubUrl);
  31280. tex2D.path = formatSubUrl;
  31281. }
  31282. }
  31283. }
  31284. break;
  31285. default:
  31286. throw new Error("Laya3D:unkonwn version.");
  31287. }
  31288. var urlCount = urls.length;
  31289. var totalProcessCount = urlCount + 1;
  31290. var lmatWeight = 1 / totalProcessCount;
  31291. Laya3D._onProcessChange(loader, 0, lmatWeight, 1.0);
  31292. if (urlCount > 0) {
  31293. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, lmatWeight, urlCount / totalProcessCount], false);
  31294. Laya3D._innerFourthLevelLoaderManager._create(urls, false, Laya.Handler.create(null, Laya3D._onMateialTexturesLoaded, [loader, processHandler, lmatData, subUrls]), processHandler, null, null, null, 1, true);
  31295. }
  31296. else {
  31297. Laya3D._onMateialTexturesLoaded(loader, null, lmatData, null);
  31298. }
  31299. }
  31300. static _onMateialTexturesLoaded(loader, processHandler, lmatData, subUrls) {
  31301. loader._cache = loader._createCache;
  31302. var mat = Material._parse(lmatData, loader._propertyParams, loader._constructParams);
  31303. Laya3D._endLoad(loader, mat, subUrls);
  31304. (processHandler) && (processHandler.recover());
  31305. }
  31306. static _loadAvatar(loader) {
  31307. loader.on(Laya.Event.LOADED, null, function (data) {
  31308. loader._cache = loader._createCache;
  31309. var avatar = Avatar._parse(data, loader._propertyParams, loader._constructParams);
  31310. Laya3D._endLoad(loader, avatar);
  31311. });
  31312. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  31313. }
  31314. static _loadAnimationClip(loader) {
  31315. loader.on(Laya.Event.LOADED, null, function (data) {
  31316. loader._cache = loader._createCache;
  31317. var clip = AnimationClip._parse(data, loader._propertyParams, loader._constructParams);
  31318. Laya3D._endLoad(loader, clip);
  31319. });
  31320. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  31321. }
  31322. static _loadTexture2D(loader) {
  31323. var url = loader.url;
  31324. var index = url.lastIndexOf('.') + 1;
  31325. var verIndex = url.indexOf('?');
  31326. var endIndex = verIndex == -1 ? url.length : verIndex;
  31327. var ext = url.substr(index, endIndex - index);
  31328. var type;
  31329. switch (ext) {
  31330. case "jpg":
  31331. case "jpeg":
  31332. case "bmp":
  31333. case "gif":
  31334. case "png":
  31335. type = "nativeimage";
  31336. break;
  31337. case "dds":
  31338. case "ktx":
  31339. case "pvr":
  31340. type = Laya.Loader.BUFFER;
  31341. break;
  31342. }
  31343. loader.on(Laya.Event.LOADED, null, function (image) {
  31344. loader._cache = loader._createCache;
  31345. var tex = Laya.Texture2D._parse(image, loader._propertyParams, loader._constructParams);
  31346. Laya3D._endLoad(loader, tex);
  31347. });
  31348. loader.load(loader.url, type, false, null, true);
  31349. }
  31350. static _loadTextureCube(loader) {
  31351. loader.on(Laya.Event.LOADED, null, Laya3D._onTextureCubeLtcLoaded, [loader]);
  31352. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  31353. }
  31354. static _onTextureCubeLtcLoaded(loader, ltcData) {
  31355. var ltcBasePath = Laya.URL.getPath(loader.url);
  31356. var urls = [Laya3D.formatRelativePath(ltcBasePath, ltcData.front), Laya3D.formatRelativePath(ltcBasePath, ltcData.back), Laya3D.formatRelativePath(ltcBasePath, ltcData.left), Laya3D.formatRelativePath(ltcBasePath, ltcData.right), Laya3D.formatRelativePath(ltcBasePath, ltcData.up), Laya3D.formatRelativePath(ltcBasePath, ltcData.down)];
  31357. var ltcWeight = 1.0 / 7.0;
  31358. Laya3D._onProcessChange(loader, 0, ltcWeight, 1.0);
  31359. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, ltcWeight, 6 / 7], false);
  31360. Laya3D._innerFourthLevelLoaderManager.load(urls, Laya.Handler.create(null, Laya3D._onTextureCubeImagesLoaded, [loader, urls, processHandler]), processHandler, "nativeimage");
  31361. }
  31362. static _onTextureCubeImagesLoaded(loader, urls, processHandler) {
  31363. var images = new Array(6);
  31364. for (var i = 0; i < 6; i++)
  31365. images[i] = Laya.Loader.getRes(urls[i]);
  31366. loader._cache = loader._createCache;
  31367. var tex = TextureCube._parse(images, loader._propertyParams, loader._constructParams);
  31368. processHandler.recover();
  31369. for (i = 0; i < 6; i++)
  31370. Laya.Loader.clearRes(urls[i]);
  31371. Laya3D._endLoad(loader, tex);
  31372. }
  31373. static _onProcessChange(loader, offset, weight, process) {
  31374. process = offset + process * weight;
  31375. (process < 1.0) && (loader.event(Laya.Event.PROGRESS, process));
  31376. }
  31377. static init(width, height, config = null, compolete = null) {
  31378. if (Laya3D._isInit) {
  31379. compolete && compolete.run();
  31380. return;
  31381. }
  31382. Laya3D._isInit = true;
  31383. (config) && (config.cloneTo(Config3D._config));
  31384. config = Config3D._config;
  31385. FrustumCulling.debugFrustumCulling = config.debugFrustumCulling;
  31386. Laya3D._editerEnvironment = config._editerEnvironment;
  31387. Scene3D.octreeCulling = config.octreeCulling;
  31388. Scene3D.octreeInitialSize = config.octreeInitialSize;
  31389. Scene3D.octreeInitialCenter = config.octreeInitialCenter;
  31390. Scene3D.octreeMinNodeSize = config.octreeMinNodeSize;
  31391. Scene3D.octreeLooseness = config.octreeLooseness;
  31392. var physics3D = window.Physics3D;
  31393. if (physics3D == null) {
  31394. Physics3D._enablePhysics = false;
  31395. Laya3D.__init__(width, height, config);
  31396. compolete && compolete.run();
  31397. }
  31398. else {
  31399. Physics3D._enablePhysics = true;
  31400. physics3D(config.defaultPhysicsMemory * 16, BulletInteractive._interactive).then(function () {
  31401. Laya3D.__init__(width, height, config);
  31402. compolete && compolete.run();
  31403. });
  31404. }
  31405. }
  31406. }
  31407. Laya3D.HIERARCHY = "HIERARCHY";
  31408. Laya3D.MESH = "MESH";
  31409. Laya3D.MATERIAL = "MATERIAL";
  31410. Laya3D.TEXTURE2D = "TEXTURE2D";
  31411. Laya3D.TEXTURECUBE = "TEXTURECUBE";
  31412. Laya3D.ANIMATIONCLIP = "ANIMATIONCLIP";
  31413. Laya3D.AVATAR = "AVATAR";
  31414. Laya3D.TERRAINHEIGHTDATA = "TERRAINHEIGHTDATA";
  31415. Laya3D.TERRAINRES = "TERRAIN";
  31416. Laya3D._innerFirstLevelLoaderManager = new Laya.LoaderManager();
  31417. Laya3D._innerSecondLevelLoaderManager = new Laya.LoaderManager();
  31418. Laya3D._innerThirdLevelLoaderManager = new Laya.LoaderManager();
  31419. Laya3D._innerFourthLevelLoaderManager = new Laya.LoaderManager();
  31420. Laya3D._isInit = false;
  31421. Laya3D._editerEnvironment = false;
  31422. Laya3D.physicsSettings = new PhysicsSettings();
  31423. window.Laya3D = Laya3D;
  31424. class CastShadowList extends SingletonList {
  31425. constructor() {
  31426. super();
  31427. }
  31428. add(element) {
  31429. var index = element._indexInCastShadowList;
  31430. if (index !== -1)
  31431. throw "CastShadowList:element has in CastShadowList.";
  31432. this._add(element);
  31433. element._indexInCastShadowList = this.length++;
  31434. }
  31435. remove(element) {
  31436. var index = element._indexInCastShadowList;
  31437. this.length--;
  31438. if (index !== this.length) {
  31439. var end = this.elements[this.length];
  31440. this.elements[index] = end;
  31441. end._indexInCastShadowList = index;
  31442. }
  31443. element._indexInCastShadowList = -1;
  31444. }
  31445. }
  31446. class AnimatorStateScript {
  31447. constructor() {
  31448. }
  31449. onStateEnter() {
  31450. }
  31451. onStateUpdate() {
  31452. }
  31453. onStateExit() {
  31454. }
  31455. }
  31456. class Script3D extends Laya.Component {
  31457. constructor() {
  31458. super(...arguments);
  31459. this._indexInPool = -1;
  31460. }
  31461. get isSingleton() {
  31462. return false;
  31463. }
  31464. _checkProcessTriggers() {
  31465. var prototype = Script3D.prototype;
  31466. if (this.onTriggerEnter !== prototype.onTriggerEnter)
  31467. return true;
  31468. if (this.onTriggerStay !== prototype.onTriggerStay)
  31469. return true;
  31470. if (this.onTriggerExit !== prototype.onTriggerExit)
  31471. return true;
  31472. return false;
  31473. }
  31474. _checkProcessCollisions() {
  31475. var prototype = Script3D.prototype;
  31476. if (this.onCollisionEnter !== prototype.onCollisionEnter)
  31477. return true;
  31478. if (this.onCollisionStay !== prototype.onCollisionStay)
  31479. return true;
  31480. if (this.onCollisionExit !== prototype.onCollisionExit)
  31481. return true;
  31482. return false;
  31483. }
  31484. _onAwake() {
  31485. this.onAwake();
  31486. if (this.onStart !== Script3D.prototype.onStart)
  31487. Laya.Laya.startTimer.callLater(this, this.onStart);
  31488. }
  31489. _onEnable() {
  31490. this.owner._scene._addScript(this);
  31491. var proto = Script3D.prototype;
  31492. if (this.onKeyDown !== proto.onKeyDown)
  31493. Laya.Laya.stage.on(Laya.Event.KEY_DOWN, this, this.onKeyDown);
  31494. if (this.onKeyPress !== proto.onKeyPress)
  31495. Laya.Laya.stage.on(Laya.Event.KEY_PRESS, this, this.onKeyUp);
  31496. if (this.onKeyUp !== proto.onKeyUp)
  31497. Laya.Laya.stage.on(Laya.Event.KEY_UP, this, this.onKeyUp);
  31498. this.onEnable();
  31499. }
  31500. _onDisable() {
  31501. this.owner._scene._removeScript(this);
  31502. this.owner.offAllCaller(this);
  31503. Laya.Laya.stage.offAllCaller(this);
  31504. this.onDisable();
  31505. }
  31506. _isScript() {
  31507. return true;
  31508. }
  31509. _onAdded() {
  31510. var sprite = this.owner;
  31511. var scripts = sprite._scripts;
  31512. scripts || (sprite._scripts = scripts = []);
  31513. scripts.push(this);
  31514. if (!sprite._needProcessCollisions)
  31515. sprite._needProcessCollisions = this._checkProcessCollisions();
  31516. if (!sprite._needProcessTriggers)
  31517. sprite._needProcessTriggers = this._checkProcessTriggers();
  31518. }
  31519. _onDestroy() {
  31520. var scripts = this.owner._scripts;
  31521. scripts.splice(scripts.indexOf(this), 1);
  31522. var sprite = this.owner;
  31523. sprite._needProcessTriggers = false;
  31524. for (var i = 0, n = scripts.length; i < n; i++) {
  31525. if (scripts[i]._checkProcessTriggers()) {
  31526. sprite._needProcessTriggers = true;
  31527. break;
  31528. }
  31529. }
  31530. sprite._needProcessCollisions = false;
  31531. for (i = 0, n = scripts.length; i < n; i++) {
  31532. if (scripts[i]._checkProcessCollisions()) {
  31533. sprite._needProcessCollisions = true;
  31534. break;
  31535. }
  31536. }
  31537. this.onDestroy();
  31538. }
  31539. onAwake() {
  31540. }
  31541. onEnable() {
  31542. }
  31543. onStart() {
  31544. }
  31545. onTriggerEnter(other) {
  31546. }
  31547. onTriggerStay(other) {
  31548. }
  31549. onTriggerExit(other) {
  31550. }
  31551. onCollisionEnter(collision) {
  31552. }
  31553. onCollisionStay(collision) {
  31554. }
  31555. onCollisionExit(collision) {
  31556. }
  31557. onMouseDown() {
  31558. }
  31559. onMouseDrag() {
  31560. }
  31561. onMouseClick() {
  31562. }
  31563. onMouseUp() {
  31564. }
  31565. onMouseEnter() {
  31566. }
  31567. onMouseOver() {
  31568. }
  31569. onMouseOut() {
  31570. }
  31571. onKeyDown(e) {
  31572. }
  31573. onKeyPress(e) {
  31574. }
  31575. onKeyUp(e) {
  31576. }
  31577. onUpdate() {
  31578. }
  31579. onLateUpdate() {
  31580. }
  31581. onPreRender() {
  31582. }
  31583. onPostRender() {
  31584. }
  31585. onDisable() {
  31586. }
  31587. onDestroy() {
  31588. }
  31589. }
  31590. class HeightMap {
  31591. constructor(width, height, minHeight, maxHeight) {
  31592. this._datas = [];
  31593. this._w = width;
  31594. this._h = height;
  31595. this._minHeight = minHeight;
  31596. this._maxHeight = maxHeight;
  31597. }
  31598. static creatFromMesh(mesh, width, height, outCellSize) {
  31599. var vertices = [];
  31600. var indexs = [];
  31601. var submesheCount = mesh.subMeshCount;
  31602. for (var i = 0; i < submesheCount; i++) {
  31603. var subMesh = mesh.getSubMesh(i);
  31604. var vertexBuffer = subMesh._vertexBuffer;
  31605. var verts = vertexBuffer.getFloat32Data();
  31606. var subMeshVertices = [];
  31607. for (var j = 0; j < verts.length; j += vertexBuffer.vertexDeclaration.vertexStride / 4) {
  31608. var position = new Vector3(verts[j + 0], verts[j + 1], verts[j + 2]);
  31609. subMeshVertices.push(position);
  31610. }
  31611. vertices.push(subMeshVertices);
  31612. var ib = subMesh._indexBuffer;
  31613. indexs.push(ib.getData());
  31614. }
  31615. var bounds = mesh.bounds;
  31616. var minX = bounds.getMin().x;
  31617. var minZ = bounds.getMin().z;
  31618. var maxX = bounds.getMax().x;
  31619. var maxZ = bounds.getMax().z;
  31620. var minY = bounds.getMin().y;
  31621. var maxY = bounds.getMax().y;
  31622. var widthSize = maxX - minX;
  31623. var heightSize = maxZ - minZ;
  31624. var cellWidth = outCellSize.x = widthSize / (width - 1);
  31625. var cellHeight = outCellSize.y = heightSize / (height - 1);
  31626. var heightMap = new HeightMap(width, height, minY, maxY);
  31627. var ray = HeightMap._tempRay;
  31628. var rayDir = ray.direction;
  31629. rayDir.x = 0;
  31630. rayDir.y = -1;
  31631. rayDir.z = 0;
  31632. const heightOffset = 0.1;
  31633. var rayY = maxY + heightOffset;
  31634. ray.origin.y = rayY;
  31635. for (var h = 0; h < height; h++) {
  31636. var posZ = minZ + h * cellHeight;
  31637. heightMap._datas[h] = [];
  31638. for (var w = 0; w < width; w++) {
  31639. var posX = minX + w * cellWidth;
  31640. var rayOri = ray.origin;
  31641. rayOri.x = posX;
  31642. rayOri.z = posZ;
  31643. var closestIntersection = HeightMap._getPosition(ray, vertices, indexs);
  31644. heightMap._datas[h][w] = (closestIntersection === Number.MAX_VALUE) ? NaN : rayY - closestIntersection;
  31645. }
  31646. }
  31647. return heightMap;
  31648. }
  31649. static createFromImage(texture, minHeight, maxHeight) {
  31650. var textureWidth = texture.width;
  31651. var textureHeight = texture.height;
  31652. var heightMap = new HeightMap(textureWidth, textureHeight, minHeight, maxHeight);
  31653. var compressionRatio = (maxHeight - minHeight) / 254;
  31654. var pixelsInfo = texture.getPixels();
  31655. var index = 0;
  31656. for (var h = 0; h < textureHeight; h++) {
  31657. var colDatas = heightMap._datas[h] = [];
  31658. for (var w = 0; w < textureWidth; w++) {
  31659. var r = pixelsInfo[index++];
  31660. var g = pixelsInfo[index++];
  31661. var b = pixelsInfo[index++];
  31662. var a = pixelsInfo[index++];
  31663. if (r == 255 && g == 255 && b == 255 && a == 255)
  31664. colDatas[w] = NaN;
  31665. else {
  31666. colDatas[w] = (r + g + b) / 3 * compressionRatio + minHeight;
  31667. }
  31668. }
  31669. }
  31670. return heightMap;
  31671. }
  31672. static _getPosition(ray, vertices, indexs) {
  31673. var closestIntersection = Number.MAX_VALUE;
  31674. for (var i = 0; i < vertices.length; i++) {
  31675. var subMeshVertices = vertices[i];
  31676. var subMeshIndexes = indexs[i];
  31677. for (var j = 0; j < subMeshIndexes.length; j += 3) {
  31678. var vertex1 = subMeshVertices[subMeshIndexes[j + 0]];
  31679. var vertex2 = subMeshVertices[subMeshIndexes[j + 1]];
  31680. var vertex3 = subMeshVertices[subMeshIndexes[j + 2]];
  31681. var intersection = Picker.rayIntersectsTriangle(ray, vertex1, vertex2, vertex3);
  31682. if (!isNaN(intersection) && intersection < closestIntersection) {
  31683. closestIntersection = intersection;
  31684. }
  31685. }
  31686. }
  31687. return closestIntersection;
  31688. }
  31689. get width() {
  31690. return this._w;
  31691. }
  31692. get height() {
  31693. return this._h;
  31694. }
  31695. get maxHeight() {
  31696. return this._maxHeight;
  31697. }
  31698. get minHeight() {
  31699. return this._minHeight;
  31700. }
  31701. _inBounds(row, col) {
  31702. return row >= 0 && row < this._h && col >= 0 && col < this._w;
  31703. }
  31704. getHeight(row, col) {
  31705. if (this._inBounds(row, col))
  31706. return this._datas[row][col];
  31707. else
  31708. return NaN;
  31709. }
  31710. }
  31711. HeightMap._tempRay = new Ray(new Vector3(), new Vector3());
  31712. class MeshTerrainSprite3D extends MeshSprite3D {
  31713. constructor(mesh, heightMap, name = null) {
  31714. super(mesh, name);
  31715. this._heightMap = heightMap;
  31716. this._cellSize = new Vector2();
  31717. }
  31718. static createFromMesh(mesh, heightMapWidth, heightMapHeight, name = null) {
  31719. var meshTerrainSprite3D = new MeshTerrainSprite3D(mesh, null, name);
  31720. meshTerrainSprite3D._initCreateFromMesh(heightMapWidth, heightMapHeight);
  31721. return meshTerrainSprite3D;
  31722. }
  31723. static createFromMeshAndHeightMap(mesh, texture, minHeight, maxHeight, name = null) {
  31724. var meshTerrainSprite3D = new MeshTerrainSprite3D(mesh, null, name);
  31725. meshTerrainSprite3D._initCreateFromMeshHeightMap(texture, minHeight, maxHeight);
  31726. return meshTerrainSprite3D;
  31727. }
  31728. get minX() {
  31729. var worldMat = this.transform.worldMatrix;
  31730. var worldMatE = worldMat.elements;
  31731. return this._minX * this._getScaleX() + worldMatE[12];
  31732. }
  31733. get minZ() {
  31734. var worldMat = this.transform.worldMatrix;
  31735. var worldMatE = worldMat.elements;
  31736. return this._minZ * this._getScaleZ() + worldMatE[14];
  31737. }
  31738. get width() {
  31739. return (this._heightMap.width - 1) * this._cellSize.x * this._getScaleX();
  31740. }
  31741. get depth() {
  31742. return (this._heightMap.height - 1) * this._cellSize.y * this._getScaleZ();
  31743. }
  31744. _disableRotation() {
  31745. var rotation = this.transform.rotation;
  31746. rotation.x = 0;
  31747. rotation.y = 0;
  31748. rotation.z = 0;
  31749. rotation.w = 1;
  31750. this.transform.rotation = rotation;
  31751. }
  31752. _getScaleX() {
  31753. var worldMat = this.transform.worldMatrix;
  31754. var worldMatE = worldMat.elements;
  31755. var m11 = worldMatE[0];
  31756. var m12 = worldMatE[1];
  31757. var m13 = worldMatE[2];
  31758. return Math.sqrt((m11 * m11) + (m12 * m12) + (m13 * m13));
  31759. }
  31760. _getScaleZ() {
  31761. var worldMat = this.transform.worldMatrix;
  31762. var worldMatE = worldMat.elements;
  31763. var m31 = worldMatE[8];
  31764. var m32 = worldMatE[9];
  31765. var m33 = worldMatE[10];
  31766. return Math.sqrt((m31 * m31) + (m32 * m32) + (m33 * m33));
  31767. }
  31768. _initCreateFromMesh(heightMapWidth, heightMapHeight) {
  31769. this._heightMap = HeightMap.creatFromMesh(this.meshFilter.sharedMesh, heightMapWidth, heightMapHeight, this._cellSize);
  31770. var boundingBox = this.meshFilter.sharedMesh.bounds;
  31771. var min = boundingBox.getMin();
  31772. var max = boundingBox.getMax();
  31773. this._minX = min.x;
  31774. this._minZ = min.z;
  31775. }
  31776. _initCreateFromMeshHeightMap(texture, minHeight, maxHeight) {
  31777. var boundingBox = this.meshFilter.sharedMesh.bounds;
  31778. this._heightMap = HeightMap.createFromImage(texture, minHeight, maxHeight);
  31779. this._computeCellSize(boundingBox);
  31780. var min = boundingBox.getMin();
  31781. var max = boundingBox.getMax();
  31782. this._minX = min.x;
  31783. this._minZ = min.z;
  31784. }
  31785. _computeCellSize(boundingBox) {
  31786. var min = boundingBox.getMin();
  31787. var max = boundingBox.getMax();
  31788. var minX = min.x;
  31789. var minZ = min.z;
  31790. var maxX = max.x;
  31791. var maxZ = max.z;
  31792. var widthSize = maxX - minX;
  31793. var heightSize = maxZ - minZ;
  31794. this._cellSize.x = widthSize / (this._heightMap.width - 1);
  31795. this._cellSize.y = heightSize / (this._heightMap.height - 1);
  31796. }
  31797. _update(state) {
  31798. this._disableRotation();
  31799. }
  31800. getHeight(x, z) {
  31801. MeshTerrainSprite3D._tempVector3.x = x;
  31802. MeshTerrainSprite3D._tempVector3.y = 0;
  31803. MeshTerrainSprite3D._tempVector3.z = z;
  31804. this._disableRotation();
  31805. var worldMat = this.transform.worldMatrix;
  31806. worldMat.invert(MeshTerrainSprite3D._tempMatrix4x4);
  31807. Vector3.transformCoordinate(MeshTerrainSprite3D._tempVector3, MeshTerrainSprite3D._tempMatrix4x4, MeshTerrainSprite3D._tempVector3);
  31808. x = MeshTerrainSprite3D._tempVector3.x;
  31809. z = MeshTerrainSprite3D._tempVector3.z;
  31810. var c = (x - this._minX) / this._cellSize.x;
  31811. var d = (z - this._minZ) / this._cellSize.y;
  31812. var row = Math.floor(d);
  31813. var col = Math.floor(c);
  31814. var s = c - col;
  31815. var t = d - row;
  31816. var uy;
  31817. var vy;
  31818. var worldMatE = worldMat.elements;
  31819. var m21 = worldMatE[4];
  31820. var m22 = worldMatE[5];
  31821. var m23 = worldMatE[6];
  31822. var scaleY = Math.sqrt((m21 * m21) + (m22 * m22) + (m23 * m23));
  31823. var translateY = worldMatE[13];
  31824. var h01 = this._heightMap.getHeight(row, col + 1);
  31825. var h10 = this._heightMap.getHeight((row + 1), col);
  31826. if (isNaN(h01) || isNaN(h10))
  31827. return NaN;
  31828. if (s + t <= 1.0) {
  31829. var h00 = this._heightMap.getHeight(row, col);
  31830. if (isNaN(h00))
  31831. return NaN;
  31832. uy = h01 - h00;
  31833. vy = h10 - h00;
  31834. return (h00 + s * uy + t * vy) * scaleY + translateY;
  31835. }
  31836. else {
  31837. var h11 = this._heightMap.getHeight((row + 1), col + 1);
  31838. if (isNaN(h11))
  31839. return NaN;
  31840. uy = h10 - h11;
  31841. vy = h01 - h11;
  31842. return (h11 + (1.0 - s) * uy + (1.0 - t) * vy) * scaleY + translateY;
  31843. }
  31844. }
  31845. }
  31846. MeshTerrainSprite3D._tempVector3 = new Vector3();
  31847. MeshTerrainSprite3D._tempMatrix4x4 = new Matrix4x4();
  31848. class GradientDataVector2 {
  31849. constructor() {
  31850. this._currentLength = 0;
  31851. this._elements = new Float32Array(12);
  31852. }
  31853. get gradientCount() {
  31854. return this._currentLength / 3;
  31855. }
  31856. add(key, value) {
  31857. if (this._currentLength < 8) {
  31858. if ((this._currentLength === 6) && ((key !== 1))) {
  31859. key = 1;
  31860. console.log("GradientDataVector2 warning:the forth key is be force set to 1.");
  31861. }
  31862. this._elements[this._currentLength++] = key;
  31863. this._elements[this._currentLength++] = value.x;
  31864. this._elements[this._currentLength++] = value.y;
  31865. }
  31866. else {
  31867. console.log("GradientDataVector2 warning:data count must lessEqual than 4");
  31868. }
  31869. }
  31870. cloneTo(destObject) {
  31871. var destGradientDataVector2 = destObject;
  31872. destGradientDataVector2._currentLength = this._currentLength;
  31873. var destElements = destGradientDataVector2._elements;
  31874. for (var i = 0, n = this._elements.length; i < n; i++) {
  31875. destElements[i] = this._elements[i];
  31876. }
  31877. }
  31878. clone() {
  31879. var destGradientDataVector2 = new GradientDataVector2();
  31880. this.cloneTo(destGradientDataVector2);
  31881. return destGradientDataVector2;
  31882. }
  31883. }
  31884. class PixelLineData {
  31885. constructor() {
  31886. this.startPosition = new Vector3();
  31887. this.endPosition = new Vector3();
  31888. this.startColor = new Color();
  31889. this.endColor = new Color();
  31890. }
  31891. cloneTo(destObject) {
  31892. this.startPosition.cloneTo(destObject.startPosition);
  31893. this.endPosition.cloneTo(destObject.endPosition);
  31894. this.startColor.cloneTo(destObject.startColor);
  31895. this.endColor.cloneTo(destObject.endColor);
  31896. }
  31897. }
  31898. class PostProcessEffect {
  31899. constructor() {
  31900. }
  31901. render(context) {
  31902. }
  31903. }
  31904. class BloomEffect extends PostProcessEffect {
  31905. constructor() {
  31906. super();
  31907. this._shader = null;
  31908. this._shaderData = new ShaderData();
  31909. this._linearColor = new Color();
  31910. this._bloomTextureTexelSize = new Vector4();
  31911. this._shaderThreshold = new Vector4();
  31912. this._shaderParams = new Vector4();
  31913. this._pyramid = null;
  31914. this._intensity = 0.0;
  31915. this._threshold = 1.0;
  31916. this._softKnee = 0.5;
  31917. this._diffusion = 7.0;
  31918. this._anamorphicRatio = 0.0;
  31919. this._dirtIntensity = 0.0;
  31920. this._shaderSetting = new Vector4();
  31921. this._dirtTileOffset = new Vector4();
  31922. this.clamp = 65472.0;
  31923. this.color = new Color(1.0, 1.0, 1.0, 1.0);
  31924. this.fastMode = false;
  31925. this.dirtTexture = null;
  31926. this._shader = Shader3D.find("PostProcessBloom");
  31927. this._pyramid = new Array(BloomEffect.MAXPYRAMIDSIZE * 2);
  31928. }
  31929. get intensity() {
  31930. return this._intensity;
  31931. }
  31932. set intensity(value) {
  31933. this._intensity = Math.max(value, 0.0);
  31934. }
  31935. get threshold() {
  31936. return this._threshold;
  31937. }
  31938. set threshold(value) {
  31939. this._threshold = Math.max(value, 0.0);
  31940. }
  31941. get softKnee() {
  31942. return this._softKnee;
  31943. }
  31944. set softKnee(value) {
  31945. this._softKnee = Math.min(Math.max(value, 0.0), 1.0);
  31946. }
  31947. get diffusion() {
  31948. return this._diffusion;
  31949. }
  31950. set diffusion(value) {
  31951. this._diffusion = Math.min(Math.max(value, 1), 10);
  31952. }
  31953. get anamorphicRatio() {
  31954. return this._anamorphicRatio;
  31955. }
  31956. set anamorphicRatio(value) {
  31957. this._anamorphicRatio = Math.min(Math.max(value, -1.0), 1.0);
  31958. }
  31959. get dirtIntensity() {
  31960. return this._dirtIntensity;
  31961. }
  31962. set dirtIntensity(value) {
  31963. this._dirtIntensity = Math.max(value, 0.0);
  31964. }
  31965. render(context) {
  31966. var cmd = context.command;
  31967. var viewport = context.camera.viewport;
  31968. this._shaderData.setTexture(BloomEffect.SHADERVALUE_AUTOEXPOSURETEX, Laya.Texture2D.whiteTexture);
  31969. var ratio = this._anamorphicRatio;
  31970. var rw = ratio < 0 ? -ratio : 0;
  31971. var rh = ratio > 0 ? ratio : 0;
  31972. var tw = Math.floor(viewport.width / (2 - rw));
  31973. var th = Math.floor(viewport.height / (2 - rh));
  31974. var s = Math.max(tw, th);
  31975. var logs;
  31976. logs = Math.log2(s) + this._diffusion - 10;
  31977. var logsInt = Math.floor(logs);
  31978. var iterations = Math.min(Math.max(logsInt, 1), BloomEffect.MAXPYRAMIDSIZE);
  31979. var sampleScale = 0.5 + logs - logsInt;
  31980. this._shaderData.setNumber(BloomEffect.SHADERVALUE_SAMPLESCALE, sampleScale);
  31981. var lthresh = Color.gammaToLinearSpace(this.threshold);
  31982. var knee = lthresh * this._softKnee + 1e-5;
  31983. this._shaderThreshold.setValue(lthresh, lthresh - knee, knee * 2, 0.25 / knee);
  31984. this._shaderData.setVector(BloomEffect.SHADERVALUE_THRESHOLD, this._shaderThreshold);
  31985. var lclamp = Color.gammaToLinearSpace(this.clamp);
  31986. this._shaderParams.setValue(lclamp, 0, 0, 0);
  31987. this._shaderData.setVector(BloomEffect.SHADERVALUE_PARAMS, this._shaderParams);
  31988. var qualityOffset = this.fastMode ? 1 : 0;
  31989. var lastDownTexture = context.source;
  31990. for (var i = 0; i < iterations; i++) {
  31991. var downIndex = i * 2;
  31992. var upIndex = downIndex + 1;
  31993. var subShader = i == 0 ? BloomEffect.SUBSHADER_PREFILTER13 + qualityOffset : BloomEffect.SUBSHADER_DOWNSAMPLE13 + qualityOffset;
  31994. var mipDownTexture = RenderTexture.createFromPool(tw, th, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE, Laya.BaseTexture.FILTERMODE_BILINEAR);
  31995. this._pyramid[downIndex] = mipDownTexture;
  31996. if (i !== iterations - 1) {
  31997. var mipUpTexture = RenderTexture.createFromPool(tw, th, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE, Laya.BaseTexture.FILTERMODE_BILINEAR);
  31998. this._pyramid[upIndex] = mipUpTexture;
  31999. }
  32000. cmd.blitScreenTriangle(lastDownTexture, mipDownTexture, null, this._shader, this._shaderData, subShader);
  32001. lastDownTexture = mipDownTexture;
  32002. tw = Math.max(Math.floor(tw / 2), 1);
  32003. th = Math.max(Math.floor(th / 2), 1);
  32004. }
  32005. var lastUpTexture = this._pyramid[(iterations - 1) * 2];
  32006. for (i = iterations - 2; i >= 0; i--) {
  32007. downIndex = i * 2;
  32008. upIndex = downIndex + 1;
  32009. mipDownTexture = this._pyramid[downIndex];
  32010. mipUpTexture = this._pyramid[upIndex];
  32011. cmd.setShaderDataTexture(this._shaderData, BloomEffect.SHADERVALUE_BLOOMTEX, mipDownTexture);
  32012. cmd.blitScreenTriangle(lastUpTexture, mipUpTexture, null, this._shader, this._shaderData, BloomEffect.SUBSHADER_UPSAMPLETENT + qualityOffset);
  32013. lastUpTexture = mipUpTexture;
  32014. }
  32015. var linearColor = this._linearColor;
  32016. this.color.toLinear(linearColor);
  32017. var intensity = Math.pow(2, this._intensity / 10.0) - 1.0;
  32018. var shaderSettings = this._shaderSetting;
  32019. this._shaderSetting.setValue(sampleScale, intensity, this._dirtIntensity, iterations);
  32020. var dirtTexture = this.dirtTexture ? this.dirtTexture : Laya.Texture2D.blackTexture;
  32021. var dirtRatio = dirtTexture.width / dirtTexture.height;
  32022. var screenRatio = viewport.width / viewport.height;
  32023. var dirtTileOffset = this._dirtTileOffset;
  32024. if (dirtRatio > screenRatio)
  32025. dirtTileOffset.setValue(screenRatio / dirtRatio, 1.0, (1.0 - dirtTileOffset.x) * 0.5, 0.0);
  32026. else if (dirtRatio < screenRatio)
  32027. dirtTileOffset.setValue(1.0, dirtRatio / screenRatio, 0.0, (1.0 - dirtTileOffset.y) * 0.5);
  32028. var compositeShaderData = context.compositeShaderData;
  32029. if (this.fastMode)
  32030. compositeShaderData.addDefine(PostProcess.SHADERDEFINE_BLOOM_LOW);
  32031. else
  32032. compositeShaderData.addDefine(PostProcess.SHADERDEFINE_BLOOM);
  32033. this._bloomTextureTexelSize.setValue(1.0 / lastUpTexture.width, 1.0 / lastUpTexture.height, lastUpTexture.width, lastUpTexture.height);
  32034. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_DIRTTILEOFFSET, dirtTileOffset);
  32035. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_SETTINGS, shaderSettings);
  32036. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_COLOR, new Vector4(linearColor.r, linearColor.g, linearColor.b, linearColor.a));
  32037. compositeShaderData.setTexture(PostProcess.SHADERVALUE_BLOOM_DIRTTEX, dirtTexture);
  32038. compositeShaderData.setTexture(PostProcess.SHADERVALUE_BLOOMTEX, lastUpTexture);
  32039. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOMTEX_TEXELSIZE, this._bloomTextureTexelSize);
  32040. for (i = 0; i < iterations; i++) {
  32041. downIndex = i * 2;
  32042. upIndex = downIndex + 1;
  32043. RenderTexture.recoverToPool(this._pyramid[downIndex]);
  32044. (i !== 0 && i !== iterations - 1) && (RenderTexture.recoverToPool(this._pyramid[upIndex]));
  32045. }
  32046. context.deferredReleaseTextures.push(lastUpTexture);
  32047. }
  32048. }
  32049. BloomEffect.SHADERVALUE_MAINTEX = Shader3D.propertyNameToID("u_MainTex");
  32050. BloomEffect.SHADERVALUE_AUTOEXPOSURETEX = Shader3D.propertyNameToID("u_AutoExposureTex");
  32051. BloomEffect.SHADERVALUE_SAMPLESCALE = Shader3D.propertyNameToID("u_SampleScale");
  32052. BloomEffect.SHADERVALUE_THRESHOLD = Shader3D.propertyNameToID("u_Threshold");
  32053. BloomEffect.SHADERVALUE_PARAMS = Shader3D.propertyNameToID("u_Params");
  32054. BloomEffect.SHADERVALUE_BLOOMTEX = Shader3D.propertyNameToID("u_BloomTex");
  32055. BloomEffect.SUBSHADER_PREFILTER13 = 0;
  32056. BloomEffect.SUBSHADER_PREFILTER4 = 1;
  32057. BloomEffect.SUBSHADER_DOWNSAMPLE13 = 2;
  32058. BloomEffect.SUBSHADER_DOWNSAMPLE4 = 3;
  32059. BloomEffect.SUBSHADER_UPSAMPLETENT = 4;
  32060. BloomEffect.SUBSHADER_UPSAMPLEBOX = 5;
  32061. BloomEffect.MAXPYRAMIDSIZE = 16;
  32062. class SceneManager {
  32063. constructor() {
  32064. }
  32065. }
  32066. class RandX {
  32067. constructor(seed) {
  32068. if (!(seed instanceof Array) || seed.length !== 4)
  32069. throw new Error('Rand:Seed must be an array with 4 numbers');
  32070. this._state0U = seed[0] | 0;
  32071. this._state0L = seed[1] | 0;
  32072. this._state1U = seed[2] | 0;
  32073. this._state1L = seed[3] | 0;
  32074. }
  32075. randomint() {
  32076. var s1U = this._state0U, s1L = this._state0L;
  32077. var s0U = this._state1U, s0L = this._state1L;
  32078. var sumL = (s0L >>> 0) + (s1L >>> 0);
  32079. var resU = (s0U + s1U + (sumL / 2 >>> 31)) >>> 0;
  32080. var resL = sumL >>> 0;
  32081. this._state0U = s0U;
  32082. this._state0L = s0L;
  32083. var t1U = 0, t1L = 0;
  32084. var t2U = 0, t2L = 0;
  32085. var a1 = 23;
  32086. var m1 = 0xFFFFFFFF << (32 - a1);
  32087. t1U = (s1U << a1) | ((s1L & m1) >>> (32 - a1));
  32088. t1L = s1L << a1;
  32089. s1U = s1U ^ t1U;
  32090. s1L = s1L ^ t1L;
  32091. t1U = s1U ^ s0U;
  32092. t1L = s1L ^ s0L;
  32093. var a2 = 18;
  32094. var m2 = 0xFFFFFFFF >>> (32 - a2);
  32095. t2U = s1U >>> a2;
  32096. t2L = (s1L >>> a2) | ((s1U & m2) << (32 - a2));
  32097. t1U = t1U ^ t2U;
  32098. t1L = t1L ^ t2L;
  32099. var a3 = 5;
  32100. var m3 = 0xFFFFFFFF >>> (32 - a3);
  32101. t2U = s0U >>> a3;
  32102. t2L = (s0L >>> a3) | ((s0U & m3) << (32 - a3));
  32103. t1U = t1U ^ t2U;
  32104. t1L = t1L ^ t2L;
  32105. this._state1U = t1U;
  32106. this._state1L = t1L;
  32107. return [resU, resL];
  32108. }
  32109. random() {
  32110. var t2 = this.randomint();
  32111. var t2U = t2[0];
  32112. var t2L = t2[1];
  32113. var eU = 0x3FF << (52 - 32);
  32114. var eL = 0;
  32115. var a1 = 12;
  32116. var m1 = 0xFFFFFFFF >>> (32 - a1);
  32117. var sU = t2U >>> a1;
  32118. var sL = (t2L >>> a1) | ((t2U & m1) << (32 - a1));
  32119. var xU = eU | sU;
  32120. var xL = eL | sL;
  32121. RandX._CONVERTION_BUFFER.setUint32(0, xU, false);
  32122. RandX._CONVERTION_BUFFER.setUint32(4, xL, false);
  32123. var d = RandX._CONVERTION_BUFFER.getFloat64(0, false);
  32124. return d - 1;
  32125. }
  32126. }
  32127. RandX._CONVERTION_BUFFER = new DataView(new ArrayBuffer(8));
  32128. RandX.defaultRand = new RandX([0, Date.now() / 65536, 0, Date.now() % 65536]);
  32129. class Constraint3D {
  32130. constructor() {
  32131. }
  32132. }
  32133. class ConstraintComponent extends Laya.Component {
  32134. constructor() {
  32135. super();
  32136. this._feedbackEnabled = false;
  32137. }
  32138. get enabled() {
  32139. return super.enabled;
  32140. }
  32141. set enabled(value) {
  32142. this._btConstraint.IsEnabled = value;
  32143. super.enabled = value;
  32144. }
  32145. get breakingImpulseThreshold() {
  32146. return this._breakingImpulseThreshold;
  32147. }
  32148. set breakingImpulseThreshold(value) {
  32149. this._btConstraint.BreakingImpulseThreshold = value;
  32150. this._breakingImpulseThreshold = value;
  32151. }
  32152. get appliedImpulse() {
  32153. if (!this._feedbackEnabled) {
  32154. this._btConstraint.EnableFeedback(true);
  32155. this._feedbackEnabled = true;
  32156. }
  32157. return this._btConstraint.AppliedImpulse;
  32158. }
  32159. get connectedBody() {
  32160. return this._connectedBody;
  32161. }
  32162. set connectedBody(value) {
  32163. this._connectedBody = value;
  32164. }
  32165. _onDestroy() {
  32166. var physics3D = Physics3D._bullet;
  32167. physics3D.destroy(this._btConstraint);
  32168. this._btConstraint = null;
  32169. }
  32170. }
  32171. class Point2PointConstraint {
  32172. constructor() {
  32173. this._pivotInA = new Vector3();
  32174. this._pivotInB = new Vector3();
  32175. }
  32176. get pivotInA() {
  32177. return this._pivotInA;
  32178. }
  32179. set pivotInA(value) {
  32180. this._pivotInA = value;
  32181. }
  32182. get pivotInB() {
  32183. return this._pivotInB;
  32184. }
  32185. set pivotInB(value) {
  32186. this._pivotInB = value;
  32187. }
  32188. get damping() {
  32189. return this._damping;
  32190. }
  32191. set damping(value) {
  32192. this._damping = value;
  32193. }
  32194. get impulseClamp() {
  32195. return this._impulseClamp;
  32196. }
  32197. set impulseClamp(value) {
  32198. this._impulseClamp = value;
  32199. }
  32200. get tau() {
  32201. return this._tau;
  32202. }
  32203. set tau(value) {
  32204. this._tau = value;
  32205. }
  32206. }
  32207. class HeightfieldColliderShape {
  32208. constructor() {
  32209. }
  32210. }
  32211. class TextMesh {
  32212. get text() {
  32213. return this._text;
  32214. }
  32215. set text(value) {
  32216. this._text = value;
  32217. }
  32218. get fontSize() {
  32219. return this._fontSize;
  32220. }
  32221. set fontSize(value) {
  32222. this._fontSize = value;
  32223. }
  32224. get color() {
  32225. return this._color;
  32226. }
  32227. set color(value) {
  32228. this._color = value;
  32229. }
  32230. constructor() {
  32231. }
  32232. _createVertexBuffer(charCount) {
  32233. }
  32234. _resizeVertexBuffer(charCount) {
  32235. }
  32236. _addChar() {
  32237. }
  32238. }
  32239. class Size {
  32240. constructor(width, height) {
  32241. this._width = 0;
  32242. this._height = 0;
  32243. this._width = width;
  32244. this._height = height;
  32245. }
  32246. static get fullScreen() {
  32247. return new Size(-1, -1);
  32248. }
  32249. get width() {
  32250. if (this._width === -1)
  32251. return RenderContext3D.clientWidth;
  32252. return this._width;
  32253. }
  32254. get height() {
  32255. if (this._height === -1)
  32256. return RenderContext3D.clientHeight;
  32257. return this._height;
  32258. }
  32259. }
  32260. exports.AlternateLightQueue = AlternateLightQueue;
  32261. exports.AnimationClip = AnimationClip;
  32262. exports.AnimationClipParser03 = AnimationClipParser03;
  32263. exports.AnimationClipParser04 = AnimationClipParser04;
  32264. exports.AnimationEvent = AnimationEvent;
  32265. exports.AnimationNode = AnimationNode;
  32266. exports.AnimationTransform3D = AnimationTransform3D;
  32267. exports.Animator = Animator;
  32268. exports.AnimatorControllerLayer = AnimatorControllerLayer;
  32269. exports.AnimatorPlayState = AnimatorPlayState;
  32270. exports.AnimatorState = AnimatorState;
  32271. exports.AnimatorStateScript = AnimatorStateScript;
  32272. exports.Avatar = Avatar;
  32273. exports.BaseCamera = BaseCamera;
  32274. exports.BaseMaterial = BaseMaterial;
  32275. exports.BaseRender = BaseRender;
  32276. exports.BaseShape = BaseShape;
  32277. exports.BatchMark = BatchMark;
  32278. exports.BlinnPhongMaterial = BlinnPhongMaterial;
  32279. exports.BlitScreenQuadCMD = BlitScreenQuadCMD;
  32280. exports.BloomEffect = BloomEffect;
  32281. exports.BoundBox = BoundBox;
  32282. exports.BoundFrustum = BoundFrustum;
  32283. exports.BoundSphere = BoundSphere;
  32284. exports.Bounds = Bounds;
  32285. exports.BoundsOctree = BoundsOctree;
  32286. exports.BoundsOctreeNode = BoundsOctreeNode;
  32287. exports.BoxColliderShape = BoxColliderShape;
  32288. exports.BoxShape = BoxShape;
  32289. exports.BufferState = BufferState;
  32290. exports.BulletInteractive = BulletInteractive;
  32291. exports.Burst = Burst;
  32292. exports.Camera = Camera;
  32293. exports.CapsuleColliderShape = CapsuleColliderShape;
  32294. exports.CastShadowList = CastShadowList;
  32295. exports.CharacterController = CharacterController;
  32296. exports.CircleShape = CircleShape;
  32297. exports.Cluster = Cluster;
  32298. exports.ColliderShape = ColliderShape;
  32299. exports.Collision = Collision;
  32300. exports.CollisionTool = CollisionTool;
  32301. exports.CollisionUtils = CollisionUtils;
  32302. exports.Color = Color;
  32303. exports.ColorOverLifetime = ColorOverLifetime;
  32304. exports.Command = Command;
  32305. exports.CommandBuffer = CommandBuffer;
  32306. exports.CompoundColliderShape = CompoundColliderShape;
  32307. exports.ConchQuaternion = ConchQuaternion;
  32308. exports.ConchVector3 = ConchVector3;
  32309. exports.ConchVector4 = ConchVector4;
  32310. exports.ConeColliderShape = ConeColliderShape;
  32311. exports.ConeShape = ConeShape;
  32312. exports.Config3D = Config3D;
  32313. exports.Constraint3D = Constraint3D;
  32314. exports.ConstraintComponent = ConstraintComponent;
  32315. exports.ContactPoint = ContactPoint;
  32316. exports.ContainmentType = ContainmentType;
  32317. exports.CylinderColliderShape = CylinderColliderShape;
  32318. exports.DefineDatas = DefineDatas;
  32319. exports.DirectionLight = DirectionLight;
  32320. exports.DirectionLightQueue = DirectionLightQueue;
  32321. exports.DynamicBatchManager = DynamicBatchManager;
  32322. exports.EffectMaterial = EffectMaterial;
  32323. exports.Emission = Emission;
  32324. exports.ExtendTerrainMaterial = ExtendTerrainMaterial;
  32325. exports.FloatKeyframe = FloatKeyframe;
  32326. exports.FrameOverTime = FrameOverTime;
  32327. exports.FrustumCulling = FrustumCulling;
  32328. exports.GeometryElement = GeometryElement;
  32329. exports.Gradient = Gradient;
  32330. exports.GradientAngularVelocity = GradientAngularVelocity;
  32331. exports.GradientColor = GradientColor;
  32332. exports.GradientDataInt = GradientDataInt;
  32333. exports.GradientDataNumber = GradientDataNumber;
  32334. exports.GradientDataVector2 = GradientDataVector2;
  32335. exports.GradientMode = GradientMode;
  32336. exports.GradientSize = GradientSize;
  32337. exports.GradientVelocity = GradientVelocity;
  32338. exports.HalfFloatUtils = HalfFloatUtils;
  32339. exports.HeightMap = HeightMap;
  32340. exports.HeightfieldColliderShape = HeightfieldColliderShape;
  32341. exports.HemisphereShape = HemisphereShape;
  32342. exports.HitResult = HitResult;
  32343. exports.ILaya3D = ILaya3D;
  32344. exports.IndexBuffer3D = IndexBuffer3D;
  32345. exports.Input3D = Input3D;
  32346. exports.Keyframe = Keyframe;
  32347. exports.KeyframeNode = KeyframeNode;
  32348. exports.KeyframeNodeList = KeyframeNodeList;
  32349. exports.KeyframeNodeOwner = KeyframeNodeOwner;
  32350. exports.Laya3D = Laya3D;
  32351. exports.LightQueue = LightQueue;
  32352. exports.LightSprite = LightSprite;
  32353. exports.LoadModelV04 = LoadModelV04;
  32354. exports.LoadModelV05 = LoadModelV05;
  32355. exports.Material = Material;
  32356. exports.MathUtils3D = MathUtils3D;
  32357. exports.Matrix3x3 = Matrix3x3;
  32358. exports.Matrix4x4 = Matrix4x4;
  32359. exports.Mesh = Mesh;
  32360. exports.MeshColliderShape = MeshColliderShape;
  32361. exports.MeshFilter = MeshFilter;
  32362. exports.MeshReader = MeshReader;
  32363. exports.MeshRenderDynamicBatchManager = MeshRenderDynamicBatchManager;
  32364. exports.MeshRenderStaticBatchManager = MeshRenderStaticBatchManager;
  32365. exports.MeshRenderer = MeshRenderer;
  32366. exports.MeshSprite3D = MeshSprite3D;
  32367. exports.MeshSprite3DShaderDeclaration = MeshSprite3DShaderDeclaration;
  32368. exports.MeshTerrainSprite3D = MeshTerrainSprite3D;
  32369. exports.MouseTouch = MouseTouch;
  32370. exports.OctreeMotionList = OctreeMotionList;
  32371. exports.PBRSpecularMaterial = PBRSpecularMaterial;
  32372. exports.PBRStandardMaterial = PBRStandardMaterial;
  32373. exports.ParallelSplitShadowMap = ParallelSplitShadowMap;
  32374. exports.Physics3D = Physics3D;
  32375. exports.Physics3DUtils = Physics3DUtils;
  32376. exports.PhysicsCollider = PhysicsCollider;
  32377. exports.PhysicsComponent = PhysicsComponent;
  32378. exports.PhysicsSettings = PhysicsSettings;
  32379. exports.PhysicsSimulation = PhysicsSimulation;
  32380. exports.PhysicsTriggerComponent = PhysicsTriggerComponent;
  32381. exports.PhysicsUpdateList = PhysicsUpdateList;
  32382. exports.Picker = Picker;
  32383. exports.PixelLineData = PixelLineData;
  32384. exports.PixelLineFilter = PixelLineFilter;
  32385. exports.PixelLineMaterial = PixelLineMaterial;
  32386. exports.PixelLineRenderer = PixelLineRenderer;
  32387. exports.PixelLineSprite3D = PixelLineSprite3D;
  32388. exports.PixelLineVertex = PixelLineVertex;
  32389. exports.Plane = Plane;
  32390. exports.Point2PointConstraint = Point2PointConstraint;
  32391. exports.PointLight = PointLight;
  32392. exports.PostProcess = PostProcess;
  32393. exports.PostProcessEffect = PostProcessEffect;
  32394. exports.PostProcessRenderContext = PostProcessRenderContext;
  32395. exports.PrimitiveMesh = PrimitiveMesh;
  32396. exports.Quaternion = Quaternion;
  32397. exports.QuaternionKeyframe = QuaternionKeyframe;
  32398. exports.Rand = Rand;
  32399. exports.RandX = RandX;
  32400. exports.Ray = Ray;
  32401. exports.RenderContext3D = RenderContext3D;
  32402. exports.RenderElement = RenderElement;
  32403. exports.RenderQueue = RenderQueue;
  32404. exports.RenderState = RenderState;
  32405. exports.RenderTexture = RenderTexture;
  32406. exports.RenderableSprite3D = RenderableSprite3D;
  32407. exports.Rigidbody3D = Rigidbody3D;
  32408. exports.RotationOverLifetime = RotationOverLifetime;
  32409. exports.Scene3D = Scene3D;
  32410. exports.Scene3DShaderDeclaration = Scene3DShaderDeclaration;
  32411. exports.Scene3DUtils = Scene3DUtils;
  32412. exports.SceneManager = SceneManager;
  32413. exports.ScreenQuad = ScreenQuad;
  32414. exports.ScreenTriangle = ScreenTriangle;
  32415. exports.Script3D = Script3D;
  32416. exports.SetRenderTargetCMD = SetRenderTargetCMD;
  32417. exports.SetShaderDataTextureCMD = SetShaderDataTextureCMD;
  32418. exports.Shader3D = Shader3D;
  32419. exports.ShaderData = ShaderData;
  32420. exports.ShaderDefine = ShaderDefine;
  32421. exports.ShaderInit3D = ShaderInit3D;
  32422. exports.ShaderInstance = ShaderInstance;
  32423. exports.ShaderPass = ShaderPass;
  32424. exports.ShaderVariable = ShaderVariable;
  32425. exports.ShaderVariant = ShaderVariant;
  32426. exports.ShaderVariantCollection = ShaderVariantCollection;
  32427. exports.ShapeUtils = ShapeUtils;
  32428. exports.ShuriKenParticle3D = ShuriKenParticle3D;
  32429. exports.ShuriKenParticle3DShaderDeclaration = ShuriKenParticle3DShaderDeclaration;
  32430. exports.ShurikenParticleData = ShurikenParticleData;
  32431. exports.ShurikenParticleMaterial = ShurikenParticleMaterial;
  32432. exports.ShurikenParticleRenderer = ShurikenParticleRenderer;
  32433. exports.ShurikenParticleSystem = ShurikenParticleSystem;
  32434. exports.SimpleSingletonList = SimpleSingletonList;
  32435. exports.SingletonList = SingletonList;
  32436. exports.Size = Size;
  32437. exports.SizeOverLifetime = SizeOverLifetime;
  32438. exports.SkinnedMeshRenderer = SkinnedMeshRenderer;
  32439. exports.SkinnedMeshSprite3D = SkinnedMeshSprite3D;
  32440. exports.SkinnedMeshSprite3DShaderDeclaration = SkinnedMeshSprite3DShaderDeclaration;
  32441. exports.SkyBox = SkyBox;
  32442. exports.SkyBoxMaterial = SkyBoxMaterial;
  32443. exports.SkyDome = SkyDome;
  32444. exports.SkyMesh = SkyMesh;
  32445. exports.SkyProceduralMaterial = SkyProceduralMaterial;
  32446. exports.SkyRenderer = SkyRenderer;
  32447. exports.SphereColliderShape = SphereColliderShape;
  32448. exports.SphereShape = SphereShape;
  32449. exports.SpotLight = SpotLight;
  32450. exports.Sprite3D = Sprite3D;
  32451. exports.StartFrame = StartFrame;
  32452. exports.StaticBatchManager = StaticBatchManager;
  32453. exports.StaticPlaneColliderShape = StaticPlaneColliderShape;
  32454. exports.SubMesh = SubMesh;
  32455. exports.SubMeshDynamicBatch = SubMeshDynamicBatch;
  32456. exports.SubMeshInstanceBatch = SubMeshInstanceBatch;
  32457. exports.SubMeshRenderElement = SubMeshRenderElement;
  32458. exports.SubMeshStaticBatch = SubMeshStaticBatch;
  32459. exports.SubShader = SubShader;
  32460. exports.SystemUtils = SystemUtils;
  32461. exports.TextMesh = TextMesh;
  32462. exports.TextureCube = TextureCube;
  32463. exports.TextureGenerator = TextureGenerator;
  32464. exports.TextureMode = TextureMode;
  32465. exports.TextureSheetAnimation = TextureSheetAnimation;
  32466. exports.Touch = Touch;
  32467. exports.TrailFilter = TrailFilter;
  32468. exports.TrailGeometry = TrailGeometry;
  32469. exports.TrailMaterial = TrailMaterial;
  32470. exports.TrailRenderer = TrailRenderer;
  32471. exports.TrailSprite3D = TrailSprite3D;
  32472. exports.Transform3D = Transform3D;
  32473. exports.UnlitMaterial = UnlitMaterial;
  32474. exports.Utils3D = Utils3D;
  32475. exports.Vector2 = Vector2;
  32476. exports.Vector3 = Vector3;
  32477. exports.Vector3Keyframe = Vector3Keyframe;
  32478. exports.Vector4 = Vector4;
  32479. exports.VelocityOverLifetime = VelocityOverLifetime;
  32480. exports.VertexBuffer3D = VertexBuffer3D;
  32481. exports.VertexDeclaration = VertexDeclaration;
  32482. exports.VertexElement = VertexElement;
  32483. exports.VertexElementFormat = VertexElementFormat;
  32484. exports.VertexMesh = VertexMesh;
  32485. exports.VertexPositionTerrain = VertexPositionTerrain;
  32486. exports.VertexPositionTexture0 = VertexPositionTexture0;
  32487. exports.VertexShuriKenParticle = VertexShuriKenParticle;
  32488. exports.VertexShurikenParticleBillboard = VertexShurikenParticleBillboard;
  32489. exports.VertexShurikenParticleMesh = VertexShurikenParticleMesh;
  32490. exports.VertexTrail = VertexTrail;
  32491. exports.Viewport = Viewport;
  32492. exports.WaterPrimaryMaterial = WaterPrimaryMaterial;
  32493. }(window.Laya = window.Laya || {}, Laya));