laya.d3.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627
  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. MathUtils3D.Deg2Rad = Math.PI / 180;
  24. class Vector2 {
  25. constructor(x = 0, y = 0) {
  26. this.x = x;
  27. this.y = y;
  28. }
  29. setValue(x, y) {
  30. this.x = x;
  31. this.y = y;
  32. }
  33. static scale(a, b, out) {
  34. out.x = a.x * b;
  35. out.y = a.y * b;
  36. }
  37. fromArray(array, offset = 0) {
  38. this.x = array[offset + 0];
  39. this.y = array[offset + 1];
  40. }
  41. cloneTo(destObject) {
  42. var destVector2 = destObject;
  43. destVector2.x = this.x;
  44. destVector2.y = this.y;
  45. }
  46. static dot(a, b) {
  47. return (a.x * b.x) + (a.y * b.y);
  48. }
  49. static normalize(s, out) {
  50. var x = s.x, y = s.y;
  51. var len = x * x + y * y;
  52. if (len > 0) {
  53. len = 1 / Math.sqrt(len);
  54. out.x = x * len;
  55. out.y = y * len;
  56. }
  57. }
  58. static scalarLength(a) {
  59. var x = a.x, y = a.y;
  60. return Math.sqrt(x * x + y * y);
  61. }
  62. clone() {
  63. var destVector2 = new Vector2();
  64. this.cloneTo(destVector2);
  65. return destVector2;
  66. }
  67. forNativeElement(nativeElements = null) {
  68. if (nativeElements) {
  69. this.elements = nativeElements;
  70. this.elements[0] = this.x;
  71. this.elements[1] = this.y;
  72. }
  73. else {
  74. this.elements = new Float32Array([this.x, this.y]);
  75. }
  76. Vector2.rewriteNumProperty(this, "x", 0);
  77. Vector2.rewriteNumProperty(this, "y", 1);
  78. }
  79. static rewriteNumProperty(proto, name, index) {
  80. Object["defineProperty"](proto, name, {
  81. "get": function () {
  82. return this.elements[index];
  83. },
  84. "set": function (v) {
  85. this.elements[index] = v;
  86. }
  87. });
  88. }
  89. }
  90. Vector2.ZERO = new Vector2(0.0, 0.0);
  91. Vector2.ONE = new Vector2(1.0, 1.0);
  92. class Vector4 {
  93. constructor(x = 0, y = 0, z = 0, w = 0) {
  94. this.x = x;
  95. this.y = y;
  96. this.z = z;
  97. this.w = w;
  98. }
  99. setValue(x, y, z, w) {
  100. this.x = x;
  101. this.y = y;
  102. this.z = z;
  103. this.w = w;
  104. }
  105. fromArray(array, offset = 0) {
  106. this.x = array[offset + 0];
  107. this.y = array[offset + 1];
  108. this.z = array[offset + 2];
  109. this.w = array[offset + 3];
  110. }
  111. cloneTo(destObject) {
  112. var destVector4 = destObject;
  113. destVector4.x = this.x;
  114. destVector4.y = this.y;
  115. destVector4.z = this.z;
  116. destVector4.w = this.w;
  117. }
  118. clone() {
  119. var destVector4 = new Vector4();
  120. this.cloneTo(destVector4);
  121. return destVector4;
  122. }
  123. static lerp(a, b, t, out) {
  124. var ax = a.x, ay = a.y, az = a.z, aw = a.w;
  125. out.x = ax + t * (b.x - ax);
  126. out.y = ay + t * (b.y - ay);
  127. out.z = az + t * (b.z - az);
  128. out.w = aw + t * (b.w - aw);
  129. }
  130. static transformByM4x4(vector4, m4x4, out) {
  131. var vx = vector4.x;
  132. var vy = vector4.y;
  133. var vz = vector4.z;
  134. var vw = vector4.w;
  135. var me = m4x4.elements;
  136. out.x = vx * me[0] + vy * me[4] + vz * me[8] + vw * me[12];
  137. out.y = vx * me[1] + vy * me[5] + vz * me[9] + vw * me[13];
  138. out.z = vx * me[2] + vy * me[6] + vz * me[10] + vw * me[14];
  139. out.w = vx * me[3] + vy * me[7] + vz * me[11] + vw * me[15];
  140. }
  141. static equals(a, b) {
  142. 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));
  143. }
  144. length() {
  145. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  146. }
  147. lengthSquared() {
  148. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  149. }
  150. static normalize(s, out) {
  151. var len = s.length();
  152. if (len > 0) {
  153. var inverse = 1.0 / len;
  154. out.x = s.x * inverse;
  155. out.y = s.y * inverse;
  156. out.z = s.z * inverse;
  157. out.w = s.w * inverse;
  158. }
  159. }
  160. static add(a, b, out) {
  161. out.x = a.x + b.x;
  162. out.y = a.y + b.y;
  163. out.z = a.z + b.z;
  164. out.w = a.w + b.w;
  165. }
  166. static subtract(a, b, out) {
  167. out.x = a.x - b.x;
  168. out.y = a.y - b.y;
  169. out.z = a.z - b.z;
  170. out.w = a.w - b.w;
  171. }
  172. static multiply(a, b, out) {
  173. out.x = a.x * b.x;
  174. out.y = a.y * b.y;
  175. out.z = a.z * b.z;
  176. out.w = a.w * b.w;
  177. }
  178. static scale(a, b, out) {
  179. out.x = a.x * b;
  180. out.y = a.y * b;
  181. out.z = a.z * b;
  182. out.w = a.w * b;
  183. }
  184. static Clamp(value, min, max, out) {
  185. var x = value.x;
  186. var y = value.y;
  187. var z = value.z;
  188. var w = value.w;
  189. var mineX = min.x;
  190. var mineY = min.y;
  191. var mineZ = min.z;
  192. var mineW = min.w;
  193. var maxeX = max.x;
  194. var maxeY = max.y;
  195. var maxeZ = max.z;
  196. var maxeW = max.w;
  197. x = (x > maxeX) ? maxeX : x;
  198. x = (x < mineX) ? mineX : x;
  199. y = (y > maxeY) ? maxeY : y;
  200. y = (y < mineY) ? mineY : y;
  201. z = (z > maxeZ) ? maxeZ : z;
  202. z = (z < mineZ) ? mineZ : z;
  203. w = (w > maxeW) ? maxeW : w;
  204. w = (w < mineW) ? mineW : w;
  205. out.x = x;
  206. out.y = y;
  207. out.z = z;
  208. out.w = w;
  209. }
  210. static distanceSquared(value1, value2) {
  211. var x = value1.x - value2.x;
  212. var y = value1.y - value2.y;
  213. var z = value1.z - value2.z;
  214. var w = value1.w - value2.w;
  215. return (x * x) + (y * y) + (z * z) + (w * w);
  216. }
  217. static distance(value1, value2) {
  218. var x = value1.x - value2.x;
  219. var y = value1.y - value2.y;
  220. var z = value1.z - value2.z;
  221. var w = value1.w - value2.w;
  222. return Math.sqrt((x * x) + (y * y) + (z * z) + (w * w));
  223. }
  224. static dot(a, b) {
  225. return (a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.w * b.w);
  226. }
  227. static min(a, b, out) {
  228. out.x = Math.min(a.x, b.x);
  229. out.y = Math.min(a.y, b.y);
  230. out.z = Math.min(a.z, b.z);
  231. out.w = Math.min(a.w, b.w);
  232. }
  233. static max(a, b, out) {
  234. out.x = Math.max(a.x, b.x);
  235. out.y = Math.max(a.y, b.y);
  236. out.z = Math.max(a.z, b.z);
  237. out.w = Math.max(a.w, b.w);
  238. }
  239. forNativeElement(nativeElements = null) {
  240. if (nativeElements) {
  241. this.elements = nativeElements;
  242. this.elements[0] = this.x;
  243. this.elements[1] = this.y;
  244. this.elements[2] = this.z;
  245. this.elements[3] = this.w;
  246. }
  247. else {
  248. this.elements = new Float32Array([this.x, this.y, this.z, this.w]);
  249. }
  250. Vector2.rewriteNumProperty(this, "x", 0);
  251. Vector2.rewriteNumProperty(this, "y", 1);
  252. Vector2.rewriteNumProperty(this, "z", 2);
  253. Vector2.rewriteNumProperty(this, "w", 3);
  254. }
  255. }
  256. Vector4.ZERO = new Vector4();
  257. Vector4.ONE = new Vector4(1.0, 1.0, 1.0, 1.0);
  258. Vector4.UnitX = new Vector4(1.0, 0.0, 0.0, 0.0);
  259. Vector4.UnitY = new Vector4(0.0, 1.0, 0.0, 0.0);
  260. Vector4.UnitZ = new Vector4(0.0, 0.0, 1.0, 0.0);
  261. Vector4.UnitW = new Vector4(0.0, 0.0, 0.0, 1.0);
  262. class Vector3 {
  263. constructor(x = 0, y = 0, z = 0, nativeElements = null) {
  264. this.x = x;
  265. this.y = y;
  266. this.z = z;
  267. }
  268. static distanceSquared(value1, value2) {
  269. var x = value1.x - value2.x;
  270. var y = value1.y - value2.y;
  271. var z = value1.z - value2.z;
  272. return (x * x) + (y * y) + (z * z);
  273. }
  274. static distance(value1, value2) {
  275. var x = value1.x - value2.x;
  276. var y = value1.y - value2.y;
  277. var z = value1.z - value2.z;
  278. return Math.sqrt((x * x) + (y * y) + (z * z));
  279. }
  280. static min(a, b, out) {
  281. out.x = Math.min(a.x, b.x);
  282. out.y = Math.min(a.y, b.y);
  283. out.z = Math.min(a.z, b.z);
  284. }
  285. static max(a, b, out) {
  286. out.x = Math.max(a.x, b.x);
  287. out.y = Math.max(a.y, b.y);
  288. out.z = Math.max(a.z, b.z);
  289. }
  290. static transformQuat(source, rotation, out) {
  291. 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;
  292. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  293. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  294. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  295. }
  296. static scalarLength(a) {
  297. var x = a.x, y = a.y, z = a.z;
  298. return Math.sqrt(x * x + y * y + z * z);
  299. }
  300. static scalarLengthSquared(a) {
  301. var x = a.x, y = a.y, z = a.z;
  302. return x * x + y * y + z * z;
  303. }
  304. static normalize(s, out) {
  305. var x = s.x, y = s.y, z = s.z;
  306. var len = x * x + y * y + z * z;
  307. if (len > 0) {
  308. len = 1 / Math.sqrt(len);
  309. out.x = x * len;
  310. out.y = y * len;
  311. out.z = z * len;
  312. }
  313. }
  314. static multiply(a, b, out) {
  315. out.x = a.x * b.x;
  316. out.y = a.y * b.y;
  317. out.z = a.z * b.z;
  318. }
  319. static scale(a, b, out) {
  320. out.x = a.x * b;
  321. out.y = a.y * b;
  322. out.z = a.z * b;
  323. }
  324. static lerp(a, b, t, out) {
  325. var ax = a.x, ay = a.y, az = a.z;
  326. out.x = ax + t * (b.x - ax);
  327. out.y = ay + t * (b.y - ay);
  328. out.z = az + t * (b.z - az);
  329. }
  330. static transformV3ToV3(vector, transform, result) {
  331. var intermediate = Vector3._tempVector4;
  332. Vector3.transformV3ToV4(vector, transform, intermediate);
  333. result.x = intermediate.x;
  334. result.y = intermediate.y;
  335. result.z = intermediate.z;
  336. }
  337. static transformV3ToV4(vector, transform, result) {
  338. var vectorX = vector.x;
  339. var vectorY = vector.y;
  340. var vectorZ = vector.z;
  341. var transformElem = transform.elements;
  342. result.x = (vectorX * transformElem[0]) + (vectorY * transformElem[4]) + (vectorZ * transformElem[8]) + transformElem[12];
  343. result.y = (vectorX * transformElem[1]) + (vectorY * transformElem[5]) + (vectorZ * transformElem[9]) + transformElem[13];
  344. result.z = (vectorX * transformElem[2]) + (vectorY * transformElem[6]) + (vectorZ * transformElem[10]) + transformElem[14];
  345. result.w = (vectorX * transformElem[3]) + (vectorY * transformElem[7]) + (vectorZ * transformElem[11]) + transformElem[15];
  346. }
  347. static TransformNormal(normal, transform, result) {
  348. var normalX = normal.x;
  349. var normalY = normal.y;
  350. var normalZ = normal.z;
  351. var transformElem = transform.elements;
  352. result.x = (normalX * transformElem[0]) + (normalY * transformElem[4]) + (normalZ * transformElem[8]);
  353. result.y = (normalX * transformElem[1]) + (normalY * transformElem[5]) + (normalZ * transformElem[9]);
  354. result.z = (normalX * transformElem[2]) + (normalY * transformElem[6]) + (normalZ * transformElem[10]);
  355. }
  356. static transformCoordinate(coordinate, transform, result) {
  357. var coordinateX = coordinate.x;
  358. var coordinateY = coordinate.y;
  359. var coordinateZ = coordinate.z;
  360. var transformElem = transform.elements;
  361. var w = coordinateX * transformElem[3] + coordinateY * transformElem[7] + coordinateZ * transformElem[11] + transformElem[15];
  362. result.x = (coordinateX * transformElem[0] + coordinateY * transformElem[4] + coordinateZ * transformElem[8] + transformElem[12]) / w;
  363. result.y = (coordinateX * transformElem[1] + coordinateY * transformElem[5] + coordinateZ * transformElem[9] + transformElem[13]) / w;
  364. result.z = (coordinateX * transformElem[2] + coordinateY * transformElem[6] + coordinateZ * transformElem[10] + transformElem[14]) / w;
  365. }
  366. static Clamp(value, min, max, out) {
  367. var x = value.x;
  368. var y = value.y;
  369. var z = value.z;
  370. var mineX = min.x;
  371. var mineY = min.y;
  372. var mineZ = min.z;
  373. var maxeX = max.x;
  374. var maxeY = max.y;
  375. var maxeZ = max.z;
  376. x = (x > maxeX) ? maxeX : x;
  377. x = (x < mineX) ? mineX : x;
  378. y = (y > maxeY) ? maxeY : y;
  379. y = (y < mineY) ? mineY : y;
  380. z = (z > maxeZ) ? maxeZ : z;
  381. z = (z < mineZ) ? mineZ : z;
  382. out.x = x;
  383. out.y = y;
  384. out.z = z;
  385. }
  386. static add(a, b, out) {
  387. out.x = a.x + b.x;
  388. out.y = a.y + b.y;
  389. out.z = a.z + b.z;
  390. }
  391. static subtract(a, b, o) {
  392. o.x = a.x - b.x;
  393. o.y = a.y - b.y;
  394. o.z = a.z - b.z;
  395. }
  396. static cross(a, b, o) {
  397. var ax = a.x, ay = a.y, az = a.z, bx = b.x, by = b.y, bz = b.z;
  398. o.x = ay * bz - az * by;
  399. o.y = az * bx - ax * bz;
  400. o.z = ax * by - ay * bx;
  401. }
  402. static dot(a, b) {
  403. return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
  404. }
  405. static equals(a, b) {
  406. return MathUtils3D.nearEqual(a.x, b.x) && MathUtils3D.nearEqual(a.y, b.y) && MathUtils3D.nearEqual(a.z, b.z);
  407. }
  408. setValue(x, y, z) {
  409. this.x = x;
  410. this.y = y;
  411. this.z = z;
  412. }
  413. fromArray(array, offset = 0) {
  414. this.x = array[offset + 0];
  415. this.y = array[offset + 1];
  416. this.z = array[offset + 2];
  417. }
  418. cloneTo(destObject) {
  419. var destVector3 = destObject;
  420. destVector3.x = this.x;
  421. destVector3.y = this.y;
  422. destVector3.z = this.z;
  423. }
  424. clone() {
  425. var destVector3 = new Vector3();
  426. this.cloneTo(destVector3);
  427. return destVector3;
  428. }
  429. toDefault() {
  430. this.x = 0;
  431. this.y = 0;
  432. this.z = 0;
  433. }
  434. forNativeElement(nativeElements = null) {
  435. if (nativeElements) {
  436. this.elements = nativeElements;
  437. this.elements[0] = this.x;
  438. this.elements[1] = this.y;
  439. this.elements[2] = this.z;
  440. }
  441. else {
  442. this.elements = new Float32Array([this.x, this.y, this.z]);
  443. }
  444. Vector2.rewriteNumProperty(this, "x", 0);
  445. Vector2.rewriteNumProperty(this, "y", 1);
  446. Vector2.rewriteNumProperty(this, "z", 2);
  447. }
  448. }
  449. Vector3._tempVector4 = new Vector4();
  450. Vector3._ZERO = new Vector3(0.0, 0.0, 0.0);
  451. Vector3._ONE = new Vector3(1.0, 1.0, 1.0);
  452. Vector3._NegativeUnitX = new Vector3(-1, 0, 0);
  453. Vector3._UnitX = new Vector3(1, 0, 0);
  454. Vector3._UnitY = new Vector3(0, 1, 0);
  455. Vector3._UnitZ = new Vector3(0, 0, 1);
  456. Vector3._ForwardRH = new Vector3(0, 0, -1);
  457. Vector3._ForwardLH = new Vector3(0, 0, 1);
  458. Vector3._Up = new Vector3(0, 1, 0);
  459. (function (PBRRenderQuality) {
  460. PBRRenderQuality[PBRRenderQuality["High"] = 0] = "High";
  461. PBRRenderQuality[PBRRenderQuality["Low"] = 1] = "Low";
  462. })(exports.PBRRenderQuality || (exports.PBRRenderQuality = {}));
  463. class Matrix3x3 {
  464. constructor() {
  465. var e = this.elements = new Float32Array(9);
  466. e[0] = 1;
  467. e[1] = 0;
  468. e[2] = 0;
  469. e[3] = 0;
  470. e[4] = 1;
  471. e[5] = 0;
  472. e[6] = 0;
  473. e[7] = 0;
  474. e[8] = 1;
  475. }
  476. static createRotationQuaternion(rotation, out) {
  477. var rotX = rotation.x;
  478. var rotY = rotation.y;
  479. var rotZ = rotation.z;
  480. var rotW = rotation.w;
  481. var xx = rotX * rotX;
  482. var yy = rotY * rotY;
  483. var zz = rotZ * rotZ;
  484. var xy = rotX * rotY;
  485. var zw = rotZ * rotW;
  486. var zx = rotZ * rotX;
  487. var yw = rotY * rotW;
  488. var yz = rotY * rotZ;
  489. var xw = rotX * rotW;
  490. var resultE = out.elements;
  491. resultE[0] = 1.0 - (2.0 * (yy + zz));
  492. resultE[1] = 2.0 * (xy + zw);
  493. resultE[2] = 2.0 * (zx - yw);
  494. resultE[3] = 2.0 * (xy - zw);
  495. resultE[4] = 1.0 - (2.0 * (zz + xx));
  496. resultE[5] = 2.0 * (yz + xw);
  497. resultE[6] = 2.0 * (zx + yw);
  498. resultE[7] = 2.0 * (yz - xw);
  499. resultE[8] = 1.0 - (2.0 * (yy + xx));
  500. }
  501. static createFromTranslation(trans, out) {
  502. var e = out.elements;
  503. e[0] = 1;
  504. e[1] = 0;
  505. e[2] = 0;
  506. e[3] = 0;
  507. e[4] = 1;
  508. e[5] = 0;
  509. e[6] = trans.x;
  510. e[7] = trans.y;
  511. e[8] = 1;
  512. }
  513. static createFromRotation(rad, out) {
  514. var e = out.elements;
  515. var s = Math.sin(rad), c = Math.cos(rad);
  516. e[0] = c;
  517. e[1] = s;
  518. e[2] = 0;
  519. e[3] = -s;
  520. e[4] = c;
  521. e[5] = 0;
  522. e[6] = 0;
  523. e[7] = 0;
  524. e[8] = 1;
  525. }
  526. static createFromScaling(scale, out) {
  527. var e = out.elements;
  528. e[0] = scale.x;
  529. e[1] = 0;
  530. e[2] = 0;
  531. e[3] = 0;
  532. e[4] = scale.y;
  533. e[5] = 0;
  534. e[6] = 0;
  535. e[7] = 0;
  536. e[8] = scale.z;
  537. }
  538. static createFromMatrix4x4(sou, out) {
  539. var souE = sou.elements;
  540. var outE = out.elements;
  541. outE[0] = souE[0];
  542. outE[1] = souE[1];
  543. outE[2] = souE[2];
  544. outE[3] = souE[4];
  545. outE[4] = souE[5];
  546. outE[5] = souE[6];
  547. outE[6] = souE[8];
  548. outE[7] = souE[9];
  549. outE[8] = souE[10];
  550. }
  551. static multiply(left, right, out) {
  552. var l = left.elements;
  553. var r = right.elements;
  554. var e = out.elements;
  555. var l11 = l[0], l12 = l[1], l13 = l[2];
  556. var l21 = l[3], l22 = l[4], l23 = l[5];
  557. var l31 = l[6], l32 = l[7], l33 = l[8];
  558. var r11 = r[0], r12 = r[1], r13 = r[2];
  559. var r21 = r[3], r22 = r[4], r23 = r[5];
  560. var r31 = r[6], r32 = r[7], r33 = r[8];
  561. e[0] = r11 * l11 + r12 * l21 + r13 * l31;
  562. e[1] = r11 * l12 + r12 * l22 + r13 * r32;
  563. e[2] = r11 * l13 + r12 * l23 + r13 * l33;
  564. e[3] = r21 * l11 + r22 * l21 + r23 * l31;
  565. e[4] = r21 * l12 + r22 * l22 + r23 * l32;
  566. e[5] = r21 * l13 + r22 * l23 + r23 * l33;
  567. e[6] = r31 * l11 + r32 * l21 + r33 * l31;
  568. e[7] = r31 * l12 + r32 * l22 + r33 * l32;
  569. e[8] = r31 * l13 + r32 * l23 + r33 * l33;
  570. }
  571. determinant() {
  572. var f = this.elements;
  573. var a00 = f[0], a01 = f[1], a02 = f[2];
  574. var a10 = f[3], a11 = f[4], a12 = f[5];
  575. var a20 = f[6], a21 = f[7], a22 = f[8];
  576. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  577. }
  578. translate(trans, out) {
  579. var e = out.elements;
  580. var f = this.elements;
  581. var a00 = f[0], a01 = f[1], a02 = f[2];
  582. var a10 = f[3], a11 = f[4], a12 = f[5];
  583. var a20 = f[6], a21 = f[7], a22 = f[8];
  584. var x = trans.x, y = trans.y;
  585. e[0] = a00;
  586. e[1] = a01;
  587. e[2] = a02;
  588. e[3] = a10;
  589. e[4] = a11;
  590. e[5] = a12;
  591. e[6] = x * a00 + y * a10 + a20;
  592. e[7] = x * a01 + y * a11 + a21;
  593. e[8] = x * a02 + y * a12 + a22;
  594. }
  595. rotate(rad, out) {
  596. var e = out.elements;
  597. var f = this.elements;
  598. var a00 = f[0], a01 = f[1], a02 = f[2];
  599. var a10 = f[3], a11 = f[4], a12 = f[5];
  600. var a20 = f[6], a21 = f[7], a22 = f[8];
  601. var s = Math.sin(rad);
  602. var c = Math.cos(rad);
  603. e[0] = c * a00 + s * a10;
  604. e[1] = c * a01 + s * a11;
  605. e[2] = c * a02 + s * a12;
  606. e[3] = c * a10 - s * a00;
  607. e[4] = c * a11 - s * a01;
  608. e[5] = c * a12 - s * a02;
  609. e[6] = a20;
  610. e[7] = a21;
  611. e[8] = a22;
  612. }
  613. scale(scale, out) {
  614. var e = out.elements;
  615. var f = this.elements;
  616. var x = scale.x, y = scale.y;
  617. e[0] = x * f[0];
  618. e[1] = x * f[1];
  619. e[2] = x * f[2];
  620. e[3] = y * f[3];
  621. e[4] = y * f[4];
  622. e[5] = y * f[5];
  623. e[6] = f[6];
  624. e[7] = f[7];
  625. e[8] = f[8];
  626. }
  627. invert(out) {
  628. var e = out.elements;
  629. var f = this.elements;
  630. var a00 = f[0], a01 = f[1], a02 = f[2];
  631. var a10 = f[3], a11 = f[4], a12 = f[5];
  632. var a20 = f[6], a21 = f[7], a22 = f[8];
  633. var b01 = a22 * a11 - a12 * a21;
  634. var b11 = -a22 * a10 + a12 * a20;
  635. var b21 = a21 * a10 - a11 * a20;
  636. var det = a00 * b01 + a01 * b11 + a02 * b21;
  637. if (!det) {
  638. out = null;
  639. }
  640. det = 1.0 / det;
  641. e[0] = b01 * det;
  642. e[1] = (-a22 * a01 + a02 * a21) * det;
  643. e[2] = (a12 * a01 - a02 * a11) * det;
  644. e[3] = b11 * det;
  645. e[4] = (a22 * a00 - a02 * a20) * det;
  646. e[5] = (-a12 * a00 + a02 * a10) * det;
  647. e[6] = b21 * det;
  648. e[7] = (-a21 * a00 + a01 * a20) * det;
  649. e[8] = (a11 * a00 - a01 * a10) * det;
  650. }
  651. transpose(out) {
  652. var e = out.elements;
  653. var f = this.elements;
  654. if (out === this) {
  655. var a01 = f[1], a02 = f[2], a12 = f[5];
  656. e[1] = f[3];
  657. e[2] = f[6];
  658. e[3] = a01;
  659. e[5] = f[7];
  660. e[6] = a02;
  661. e[7] = a12;
  662. }
  663. else {
  664. e[0] = f[0];
  665. e[1] = f[3];
  666. e[2] = f[6];
  667. e[3] = f[1];
  668. e[4] = f[4];
  669. e[5] = f[7];
  670. e[6] = f[2];
  671. e[7] = f[5];
  672. e[8] = f[8];
  673. }
  674. }
  675. identity() {
  676. var e = this.elements;
  677. e[0] = 1;
  678. e[1] = 0;
  679. e[2] = 0;
  680. e[3] = 0;
  681. e[4] = 1;
  682. e[5] = 0;
  683. e[6] = 0;
  684. e[7] = 0;
  685. e[8] = 1;
  686. }
  687. cloneTo(destObject) {
  688. var i, s, d;
  689. s = this.elements;
  690. d = destObject.elements;
  691. if (s === d) {
  692. return;
  693. }
  694. for (i = 0; i < 9; ++i) {
  695. d[i] = s[i];
  696. }
  697. }
  698. clone() {
  699. var dest = new Matrix3x3();
  700. this.cloneTo(dest);
  701. return dest;
  702. }
  703. static lookAt(eye, target, up, out) {
  704. Vector3.subtract(eye, target, Matrix3x3._tempV30);
  705. Vector3.normalize(Matrix3x3._tempV30, Matrix3x3._tempV30);
  706. Vector3.cross(up, Matrix3x3._tempV30, Matrix3x3._tempV31);
  707. Vector3.normalize(Matrix3x3._tempV31, Matrix3x3._tempV31);
  708. Vector3.cross(Matrix3x3._tempV30, Matrix3x3._tempV31, Matrix3x3._tempV32);
  709. var v0 = Matrix3x3._tempV30;
  710. var v1 = Matrix3x3._tempV31;
  711. var v2 = Matrix3x3._tempV32;
  712. var me = out.elements;
  713. me[0] = v1.x;
  714. me[3] = v1.y;
  715. me[6] = v1.z;
  716. me[1] = v2.x;
  717. me[4] = v2.y;
  718. me[7] = v2.z;
  719. me[2] = v0.x;
  720. me[5] = v0.y;
  721. me[8] = v0.z;
  722. }
  723. }
  724. Matrix3x3.DEFAULT = new Matrix3x3();
  725. Matrix3x3._tempV30 = new Vector3();
  726. Matrix3x3._tempV31 = new Vector3();
  727. Matrix3x3._tempV32 = new Vector3();
  728. class ILaya3D {
  729. }
  730. ILaya3D.Shader3D = null;
  731. ILaya3D.Scene3D = null;
  732. ILaya3D.MeshRenderStaticBatchManager = null;
  733. ILaya3D.MeshRenderDynamicBatchManager = null;
  734. ILaya3D.SubMeshDynamicBatch = null;
  735. ILaya3D.Laya3D = null;
  736. ILaya3D.Matrix4x4 = null;
  737. ILaya3D.Physics3D = null;
  738. ILaya3D.ShadowLightType = null;
  739. class Quaternion {
  740. constructor(x = 0, y = 0, z = 0, w = 1, nativeElements = null) {
  741. this.x = x;
  742. this.y = y;
  743. this.z = z;
  744. this.w = w;
  745. }
  746. static createFromYawPitchRoll(yaw, pitch, roll, out) {
  747. var halfRoll = roll * 0.5;
  748. var halfPitch = pitch * 0.5;
  749. var halfYaw = yaw * 0.5;
  750. var sinRoll = Math.sin(halfRoll);
  751. var cosRoll = Math.cos(halfRoll);
  752. var sinPitch = Math.sin(halfPitch);
  753. var cosPitch = Math.cos(halfPitch);
  754. var sinYaw = Math.sin(halfYaw);
  755. var cosYaw = Math.cos(halfYaw);
  756. out.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  757. out.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  758. out.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  759. out.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  760. }
  761. static multiply(left, right, out) {
  762. var lx = left.x;
  763. var ly = left.y;
  764. var lz = left.z;
  765. var lw = left.w;
  766. var rx = right.x;
  767. var ry = right.y;
  768. var rz = right.z;
  769. var rw = right.w;
  770. var a = (ly * rz - lz * ry);
  771. var b = (lz * rx - lx * rz);
  772. var c = (lx * ry - ly * rx);
  773. var d = (lx * rx + ly * ry + lz * rz);
  774. out.x = (lx * rw + rx * lw) + a;
  775. out.y = (ly * rw + ry * lw) + b;
  776. out.z = (lz * rw + rz * lw) + c;
  777. out.w = lw * rw - d;
  778. }
  779. static arcTanAngle(x, y) {
  780. if (x == 0) {
  781. if (y == 1)
  782. return Math.PI / 2;
  783. return -Math.PI / 2;
  784. }
  785. if (x > 0)
  786. return Math.atan(y / x);
  787. if (x < 0) {
  788. if (y > 0)
  789. return Math.atan(y / x) + Math.PI;
  790. return Math.atan(y / x) - Math.PI;
  791. }
  792. return 0;
  793. }
  794. static angleTo(from, location, angle) {
  795. Vector3.subtract(location, from, Quaternion.TEMPVector30);
  796. Vector3.normalize(Quaternion.TEMPVector30, Quaternion.TEMPVector30);
  797. angle.x = Math.asin(Quaternion.TEMPVector30.y);
  798. angle.y = Quaternion.arcTanAngle(-Quaternion.TEMPVector30.z, -Quaternion.TEMPVector30.x);
  799. }
  800. static createFromAxisAngle(axis, rad, out) {
  801. rad = rad * 0.5;
  802. var s = Math.sin(rad);
  803. out.x = s * axis.x;
  804. out.y = s * axis.y;
  805. out.z = s * axis.z;
  806. out.w = Math.cos(rad);
  807. }
  808. static createFromMatrix4x4(mat, out) {
  809. var me = mat.elements;
  810. var sqrt;
  811. var half;
  812. var scale = me[0] + me[5] + me[10];
  813. if (scale > 0.0) {
  814. sqrt = Math.sqrt(scale + 1.0);
  815. out.w = sqrt * 0.5;
  816. sqrt = 0.5 / sqrt;
  817. out.x = (me[6] - me[9]) * sqrt;
  818. out.y = (me[8] - me[2]) * sqrt;
  819. out.z = (me[1] - me[4]) * sqrt;
  820. }
  821. else if ((me[0] >= me[5]) && (me[0] >= me[10])) {
  822. sqrt = Math.sqrt(1.0 + me[0] - me[5] - me[10]);
  823. half = 0.5 / sqrt;
  824. out.x = 0.5 * sqrt;
  825. out.y = (me[1] + me[4]) * half;
  826. out.z = (me[2] + me[8]) * half;
  827. out.w = (me[6] - me[9]) * half;
  828. }
  829. else if (me[5] > me[10]) {
  830. sqrt = Math.sqrt(1.0 + me[5] - me[0] - me[10]);
  831. half = 0.5 / sqrt;
  832. out.x = (me[4] + me[1]) * half;
  833. out.y = 0.5 * sqrt;
  834. out.z = (me[9] + me[6]) * half;
  835. out.w = (me[8] - me[2]) * half;
  836. }
  837. else {
  838. sqrt = Math.sqrt(1.0 + me[10] - me[0] - me[5]);
  839. half = 0.5 / sqrt;
  840. out.x = (me[8] + me[2]) * half;
  841. out.y = (me[9] + me[6]) * half;
  842. out.z = 0.5 * sqrt;
  843. out.w = (me[1] - me[4]) * half;
  844. }
  845. }
  846. static slerp(left, right, t, out) {
  847. 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;
  848. var omega, cosom, sinom, scale0, scale1;
  849. cosom = ax * bx + ay * by + az * bz + aw * bw;
  850. if (cosom < 0.0) {
  851. cosom = -cosom;
  852. bx = -bx;
  853. by = -by;
  854. bz = -bz;
  855. bw = -bw;
  856. }
  857. if ((1.0 - cosom) > 0.000001) {
  858. omega = Math.acos(cosom);
  859. sinom = Math.sin(omega);
  860. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  861. scale1 = Math.sin(t * omega) / sinom;
  862. }
  863. else {
  864. scale0 = 1.0 - t;
  865. scale1 = t;
  866. }
  867. out.x = scale0 * ax + scale1 * bx;
  868. out.y = scale0 * ay + scale1 * by;
  869. out.z = scale0 * az + scale1 * bz;
  870. out.w = scale0 * aw + scale1 * bw;
  871. return out;
  872. }
  873. static lerp(left, right, amount, out) {
  874. var inverse = 1.0 - amount;
  875. if (Quaternion.dot(left, right) >= 0) {
  876. out.x = (inverse * left.x) + (amount * right.x);
  877. out.y = (inverse * left.y) + (amount * right.y);
  878. out.z = (inverse * left.z) + (amount * right.z);
  879. out.w = (inverse * left.w) + (amount * right.w);
  880. }
  881. else {
  882. out.x = (inverse * left.x) - (amount * right.x);
  883. out.y = (inverse * left.y) - (amount * right.y);
  884. out.z = (inverse * left.z) - (amount * right.z);
  885. out.w = (inverse * left.w) - (amount * right.w);
  886. }
  887. out.normalize(out);
  888. }
  889. static add(left, right, out) {
  890. out.x = left.x + right.x;
  891. out.y = left.y + right.y;
  892. out.z = left.z + right.z;
  893. out.w = left.w + right.w;
  894. }
  895. static dot(left, right) {
  896. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  897. }
  898. scaling(scaling, out) {
  899. out.x = this.x * scaling;
  900. out.y = this.y * scaling;
  901. out.z = this.z * scaling;
  902. out.w = this.w * scaling;
  903. }
  904. normalize(out) {
  905. var len = this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  906. if (len > 0) {
  907. len = 1 / Math.sqrt(len);
  908. out.x = this.x * len;
  909. out.y = this.y * len;
  910. out.z = this.z * len;
  911. out.w = this.w * len;
  912. }
  913. }
  914. length() {
  915. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  916. }
  917. rotateX(rad, out) {
  918. rad *= 0.5;
  919. var bx = Math.sin(rad), bw = Math.cos(rad);
  920. out.x = this.x * bw + this.w * bx;
  921. out.y = this.y * bw + this.z * bx;
  922. out.z = this.z * bw - this.y * bx;
  923. out.w = this.w * bw - this.x * bx;
  924. }
  925. rotateY(rad, out) {
  926. rad *= 0.5;
  927. var by = Math.sin(rad), bw = Math.cos(rad);
  928. out.x = this.x * bw - this.z * by;
  929. out.y = this.y * bw + this.w * by;
  930. out.z = this.z * bw + this.x * by;
  931. out.w = this.w * bw - this.y * by;
  932. }
  933. rotateZ(rad, out) {
  934. rad *= 0.5;
  935. var bz = Math.sin(rad), bw = Math.cos(rad);
  936. out.x = this.x * bw + this.y * bz;
  937. out.y = this.y * bw - this.x * bz;
  938. out.z = this.z * bw + this.w * bz;
  939. out.w = this.w * bw - this.z * bz;
  940. }
  941. getYawPitchRoll(out) {
  942. Vector3.transformQuat(Vector3._ForwardRH, this, Quaternion.TEMPVector31);
  943. Vector3.transformQuat(Vector3._Up, this, Quaternion.TEMPVector32);
  944. var upe = Quaternion.TEMPVector32;
  945. Quaternion.angleTo(Vector3._ZERO, Quaternion.TEMPVector31, Quaternion.TEMPVector33);
  946. var angle = Quaternion.TEMPVector33;
  947. if (angle.x == Math.PI / 2) {
  948. angle.y = Quaternion.arcTanAngle(upe.z, upe.x);
  949. angle.z = 0;
  950. }
  951. else if (angle.x == -Math.PI / 2) {
  952. angle.y = Quaternion.arcTanAngle(-upe.z, -upe.x);
  953. angle.z = 0;
  954. }
  955. else {
  956. ILaya3D.Matrix4x4.createRotationY(-angle.y, ILaya3D.Matrix4x4.TEMPMatrix0);
  957. ILaya3D.Matrix4x4.createRotationX(-angle.x, ILaya3D.Matrix4x4.TEMPMatrix1);
  958. Vector3.transformCoordinate(Quaternion.TEMPVector32, ILaya3D.Matrix4x4.TEMPMatrix0, Quaternion.TEMPVector32);
  959. Vector3.transformCoordinate(Quaternion.TEMPVector32, ILaya3D.Matrix4x4.TEMPMatrix1, Quaternion.TEMPVector32);
  960. angle.z = Quaternion.arcTanAngle(upe.y, -upe.x);
  961. }
  962. if (angle.y <= -Math.PI)
  963. angle.y = Math.PI;
  964. if (angle.z <= -Math.PI)
  965. angle.z = Math.PI;
  966. if (angle.y >= Math.PI && angle.z >= Math.PI) {
  967. angle.y = 0;
  968. angle.z = 0;
  969. angle.x = Math.PI - angle.x;
  970. }
  971. var oe = out;
  972. oe.x = angle.y;
  973. oe.y = angle.x;
  974. oe.z = angle.z;
  975. }
  976. invert(out) {
  977. var a0 = this.x, a1 = this.y, a2 = this.z, a3 = this.w;
  978. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  979. var invDot = dot ? 1.0 / dot : 0;
  980. out.x = -a0 * invDot;
  981. out.y = -a1 * invDot;
  982. out.z = -a2 * invDot;
  983. out.w = a3 * invDot;
  984. }
  985. identity() {
  986. this.x = 0;
  987. this.y = 0;
  988. this.z = 0;
  989. this.w = 1;
  990. }
  991. fromArray(array, offset = 0) {
  992. this.x = array[offset + 0];
  993. this.y = array[offset + 1];
  994. this.z = array[offset + 2];
  995. this.w = array[offset + 3];
  996. }
  997. cloneTo(destObject) {
  998. if (this === destObject) {
  999. return;
  1000. }
  1001. destObject.x = this.x;
  1002. destObject.y = this.y;
  1003. destObject.z = this.z;
  1004. destObject.w = this.w;
  1005. }
  1006. clone() {
  1007. var dest = new Quaternion();
  1008. this.cloneTo(dest);
  1009. return dest;
  1010. }
  1011. equals(b) {
  1012. 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);
  1013. }
  1014. static rotationLookAt(forward, up, out) {
  1015. Quaternion.lookAt(Vector3._ZERO, forward, up, out);
  1016. }
  1017. static lookAt(eye, target, up, out) {
  1018. Matrix3x3.lookAt(eye, target, up, Quaternion._tempMatrix3x3);
  1019. Quaternion.rotationMatrix(Quaternion._tempMatrix3x3, out);
  1020. }
  1021. lengthSquared() {
  1022. return (this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w);
  1023. }
  1024. static invert(value, out) {
  1025. var lengthSq = value.lengthSquared();
  1026. if (!MathUtils3D.isZero(lengthSq)) {
  1027. lengthSq = 1.0 / lengthSq;
  1028. out.x = -value.x * lengthSq;
  1029. out.y = -value.y * lengthSq;
  1030. out.z = -value.z * lengthSq;
  1031. out.w = value.w * lengthSq;
  1032. }
  1033. }
  1034. static rotationMatrix(matrix3x3, out) {
  1035. var me = matrix3x3.elements;
  1036. var m11 = me[0];
  1037. var m12 = me[1];
  1038. var m13 = me[2];
  1039. var m21 = me[3];
  1040. var m22 = me[4];
  1041. var m23 = me[5];
  1042. var m31 = me[6];
  1043. var m32 = me[7];
  1044. var m33 = me[8];
  1045. var sqrt, half;
  1046. var scale = m11 + m22 + m33;
  1047. if (scale > 0) {
  1048. sqrt = Math.sqrt(scale + 1);
  1049. out.w = sqrt * 0.5;
  1050. sqrt = 0.5 / sqrt;
  1051. out.x = (m23 - m32) * sqrt;
  1052. out.y = (m31 - m13) * sqrt;
  1053. out.z = (m12 - m21) * sqrt;
  1054. }
  1055. else if ((m11 >= m22) && (m11 >= m33)) {
  1056. sqrt = Math.sqrt(1 + m11 - m22 - m33);
  1057. half = 0.5 / sqrt;
  1058. out.x = 0.5 * sqrt;
  1059. out.y = (m12 + m21) * half;
  1060. out.z = (m13 + m31) * half;
  1061. out.w = (m23 - m32) * half;
  1062. }
  1063. else if (m22 > m33) {
  1064. sqrt = Math.sqrt(1 + m22 - m11 - m33);
  1065. half = 0.5 / sqrt;
  1066. out.x = (m21 + m12) * half;
  1067. out.y = 0.5 * sqrt;
  1068. out.z = (m32 + m23) * half;
  1069. out.w = (m31 - m13) * half;
  1070. }
  1071. else {
  1072. sqrt = Math.sqrt(1 + m33 - m11 - m22);
  1073. half = 0.5 / sqrt;
  1074. out.x = (m31 + m13) * half;
  1075. out.y = (m32 + m23) * half;
  1076. out.z = 0.5 * sqrt;
  1077. out.w = (m12 - m21) * half;
  1078. }
  1079. }
  1080. forNativeElement(nativeElements = null) {
  1081. if (nativeElements) {
  1082. this.elements = nativeElements;
  1083. this.elements[0] = this.x;
  1084. this.elements[1] = this.y;
  1085. this.elements[2] = this.z;
  1086. this.elements[3] = this.w;
  1087. }
  1088. else {
  1089. this.elements = new Float32Array([this.x, this.y, this.z, this.w]);
  1090. }
  1091. Vector2.rewriteNumProperty(this, "x", 0);
  1092. Vector2.rewriteNumProperty(this, "y", 1);
  1093. Vector2.rewriteNumProperty(this, "z", 2);
  1094. Vector2.rewriteNumProperty(this, "w", 3);
  1095. }
  1096. }
  1097. Quaternion.TEMPVector30 = new Vector3();
  1098. Quaternion.TEMPVector31 = new Vector3();
  1099. Quaternion.TEMPVector32 = new Vector3();
  1100. Quaternion.TEMPVector33 = new Vector3();
  1101. Quaternion._tempMatrix3x3 = new Matrix3x3();
  1102. Quaternion.DEFAULT = new Quaternion();
  1103. Quaternion.NAN = new Quaternion(NaN, NaN, NaN, NaN);
  1104. class Matrix4x4 {
  1105. 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) {
  1106. var e = elements ? this.elements = elements : this.elements = new Float32Array(16);
  1107. e[0] = m11;
  1108. e[1] = m12;
  1109. e[2] = m13;
  1110. e[3] = m14;
  1111. e[4] = m21;
  1112. e[5] = m22;
  1113. e[6] = m23;
  1114. e[7] = m24;
  1115. e[8] = m31;
  1116. e[9] = m32;
  1117. e[10] = m33;
  1118. e[11] = m34;
  1119. e[12] = m41;
  1120. e[13] = m42;
  1121. e[14] = m43;
  1122. e[15] = m44;
  1123. }
  1124. static createRotationX(rad, out) {
  1125. var oe = out.elements;
  1126. var s = Math.sin(rad), c = Math.cos(rad);
  1127. oe[1] = oe[2] = oe[3] = oe[4] = oe[7] = oe[8] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1128. oe[0] = oe[15] = 1;
  1129. oe[5] = oe[10] = c;
  1130. oe[6] = s;
  1131. oe[9] = -s;
  1132. }
  1133. static createRotationY(rad, out) {
  1134. var oe = out.elements;
  1135. var s = Math.sin(rad), c = Math.cos(rad);
  1136. oe[1] = oe[3] = oe[4] = oe[6] = oe[7] = oe[9] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1137. oe[5] = oe[15] = 1;
  1138. oe[0] = oe[10] = c;
  1139. oe[2] = -s;
  1140. oe[8] = s;
  1141. }
  1142. static createRotationZ(rad, out) {
  1143. var oe = out.elements;
  1144. var s = Math.sin(rad), c = Math.cos(rad);
  1145. oe[2] = oe[3] = oe[6] = oe[7] = oe[8] = oe[9] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1146. oe[10] = oe[15] = 1;
  1147. oe[0] = oe[5] = c;
  1148. oe[1] = s;
  1149. oe[4] = -s;
  1150. }
  1151. static createRotationYawPitchRoll(yaw, pitch, roll, result) {
  1152. Quaternion.createFromYawPitchRoll(yaw, pitch, roll, Matrix4x4._tempQuaternion);
  1153. Matrix4x4.createRotationQuaternion(Matrix4x4._tempQuaternion, result);
  1154. }
  1155. static createRotationAxis(axis, angle, result) {
  1156. var x = axis.x;
  1157. var y = axis.y;
  1158. var z = axis.z;
  1159. var cos = Math.cos(angle);
  1160. var sin = Math.sin(angle);
  1161. var xx = x * x;
  1162. var yy = y * y;
  1163. var zz = z * z;
  1164. var xy = x * y;
  1165. var xz = x * z;
  1166. var yz = y * z;
  1167. var resultE = result.elements;
  1168. resultE[3] = resultE[7] = resultE[11] = resultE[12] = resultE[13] = resultE[14] = 0;
  1169. resultE[15] = 1.0;
  1170. resultE[0] = xx + (cos * (1.0 - xx));
  1171. resultE[1] = (xy - (cos * xy)) + (sin * z);
  1172. resultE[2] = (xz - (cos * xz)) - (sin * y);
  1173. resultE[4] = (xy - (cos * xy)) - (sin * z);
  1174. resultE[5] = yy + (cos * (1.0 - yy));
  1175. resultE[6] = (yz - (cos * yz)) + (sin * x);
  1176. resultE[8] = (xz - (cos * xz)) + (sin * y);
  1177. resultE[9] = (yz - (cos * yz)) - (sin * x);
  1178. resultE[10] = zz + (cos * (1.0 - zz));
  1179. }
  1180. setRotation(rotation) {
  1181. var rotationX = rotation.x;
  1182. var rotationY = rotation.y;
  1183. var rotationZ = rotation.z;
  1184. var rotationW = rotation.w;
  1185. var xx = rotationX * rotationX;
  1186. var yy = rotationY * rotationY;
  1187. var zz = rotationZ * rotationZ;
  1188. var xy = rotationX * rotationY;
  1189. var zw = rotationZ * rotationW;
  1190. var zx = rotationZ * rotationX;
  1191. var yw = rotationY * rotationW;
  1192. var yz = rotationY * rotationZ;
  1193. var xw = rotationX * rotationW;
  1194. var e = this.elements;
  1195. e[0] = 1.0 - (2.0 * (yy + zz));
  1196. e[1] = 2.0 * (xy + zw);
  1197. e[2] = 2.0 * (zx - yw);
  1198. e[4] = 2.0 * (xy - zw);
  1199. e[5] = 1.0 - (2.0 * (zz + xx));
  1200. e[6] = 2.0 * (yz + xw);
  1201. e[8] = 2.0 * (zx + yw);
  1202. e[9] = 2.0 * (yz - xw);
  1203. e[10] = 1.0 - (2.0 * (yy + xx));
  1204. }
  1205. setPosition(position) {
  1206. var e = this.elements;
  1207. e[12] = position.x;
  1208. e[13] = position.y;
  1209. e[14] = position.z;
  1210. }
  1211. static createRotationQuaternion(rotation, result) {
  1212. var resultE = result.elements;
  1213. var rotationX = rotation.x;
  1214. var rotationY = rotation.y;
  1215. var rotationZ = rotation.z;
  1216. var rotationW = rotation.w;
  1217. var xx = rotationX * rotationX;
  1218. var yy = rotationY * rotationY;
  1219. var zz = rotationZ * rotationZ;
  1220. var xy = rotationX * rotationY;
  1221. var zw = rotationZ * rotationW;
  1222. var zx = rotationZ * rotationX;
  1223. var yw = rotationY * rotationW;
  1224. var yz = rotationY * rotationZ;
  1225. var xw = rotationX * rotationW;
  1226. resultE[3] = resultE[7] = resultE[11] = resultE[12] = resultE[13] = resultE[14] = 0;
  1227. resultE[15] = 1.0;
  1228. resultE[0] = 1.0 - (2.0 * (yy + zz));
  1229. resultE[1] = 2.0 * (xy + zw);
  1230. resultE[2] = 2.0 * (zx - yw);
  1231. resultE[4] = 2.0 * (xy - zw);
  1232. resultE[5] = 1.0 - (2.0 * (zz + xx));
  1233. resultE[6] = 2.0 * (yz + xw);
  1234. resultE[8] = 2.0 * (zx + yw);
  1235. resultE[9] = 2.0 * (yz - xw);
  1236. resultE[10] = 1.0 - (2.0 * (yy + xx));
  1237. }
  1238. static createTranslate(trans, out) {
  1239. var oe = out.elements;
  1240. oe[4] = oe[8] = oe[1] = oe[9] = oe[2] = oe[6] = oe[3] = oe[7] = oe[11] = 0;
  1241. oe[0] = oe[5] = oe[10] = oe[15] = 1;
  1242. oe[12] = trans.x;
  1243. oe[13] = trans.y;
  1244. oe[14] = trans.z;
  1245. }
  1246. static createScaling(scale, out) {
  1247. var oe = out.elements;
  1248. oe[0] = scale.x;
  1249. oe[5] = scale.y;
  1250. oe[10] = scale.z;
  1251. 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;
  1252. oe[15] = 1;
  1253. }
  1254. static multiply(left, right, out) {
  1255. var l = right.elements;
  1256. var r = left.elements;
  1257. var e = out.elements;
  1258. var l11 = l[0], l12 = l[1], l13 = l[2], l14 = l[3];
  1259. var l21 = l[4], l22 = l[5], l23 = l[6], l24 = l[7];
  1260. var l31 = l[8], l32 = l[9], l33 = l[10], l34 = l[11];
  1261. var l41 = l[12], l42 = l[13], l43 = l[14], l44 = l[15];
  1262. var r11 = r[0], r12 = r[1], r13 = r[2], r14 = r[3];
  1263. var r21 = r[4], r22 = r[5], r23 = r[6], r24 = r[7];
  1264. var r31 = r[8], r32 = r[9], r33 = r[10], r34 = r[11];
  1265. var r41 = r[12], r42 = r[13], r43 = r[14], r44 = r[15];
  1266. e[0] = (l11 * r11) + (l12 * r21) + (l13 * r31) + (l14 * r41);
  1267. e[1] = (l11 * r12) + (l12 * r22) + (l13 * r32) + (l14 * r42);
  1268. e[2] = (l11 * r13) + (l12 * r23) + (l13 * r33) + (l14 * r43);
  1269. e[3] = (l11 * r14) + (l12 * r24) + (l13 * r34) + (l14 * r44);
  1270. e[4] = (l21 * r11) + (l22 * r21) + (l23 * r31) + (l24 * r41);
  1271. e[5] = (l21 * r12) + (l22 * r22) + (l23 * r32) + (l24 * r42);
  1272. e[6] = (l21 * r13) + (l22 * r23) + (l23 * r33) + (l24 * r43);
  1273. e[7] = (l21 * r14) + (l22 * r24) + (l23 * r34) + (l24 * r44);
  1274. e[8] = (l31 * r11) + (l32 * r21) + (l33 * r31) + (l34 * r41);
  1275. e[9] = (l31 * r12) + (l32 * r22) + (l33 * r32) + (l34 * r42);
  1276. e[10] = (l31 * r13) + (l32 * r23) + (l33 * r33) + (l34 * r43);
  1277. e[11] = (l31 * r14) + (l32 * r24) + (l33 * r34) + (l34 * r44);
  1278. e[12] = (l41 * r11) + (l42 * r21) + (l43 * r31) + (l44 * r41);
  1279. e[13] = (l41 * r12) + (l42 * r22) + (l43 * r32) + (l44 * r42);
  1280. e[14] = (l41 * r13) + (l42 * r23) + (l43 * r33) + (l44 * r43);
  1281. e[15] = (l41 * r14) + (l42 * r24) + (l43 * r34) + (l44 * r44);
  1282. }
  1283. static multiplyForNative(left, right, out) {
  1284. Laya.LayaGL.instance.matrix4x4Multiply(left.elements, right.elements, out.elements);
  1285. }
  1286. static createFromQuaternion(rotation, out) {
  1287. var e = out.elements;
  1288. var x = rotation.x, y = rotation.y, z = rotation.z, w = rotation.w;
  1289. var x2 = x + x;
  1290. var y2 = y + y;
  1291. var z2 = z + z;
  1292. var xx = x * x2;
  1293. var yx = y * x2;
  1294. var yy = y * y2;
  1295. var zx = z * x2;
  1296. var zy = z * y2;
  1297. var zz = z * z2;
  1298. var wx = w * x2;
  1299. var wy = w * y2;
  1300. var wz = w * z2;
  1301. e[0] = 1 - yy - zz;
  1302. e[1] = yx + wz;
  1303. e[2] = zx - wy;
  1304. e[3] = 0;
  1305. e[4] = yx - wz;
  1306. e[5] = 1 - xx - zz;
  1307. e[6] = zy + wx;
  1308. e[7] = 0;
  1309. e[8] = zx + wy;
  1310. e[9] = zy - wx;
  1311. e[10] = 1 - xx - yy;
  1312. e[11] = 0;
  1313. e[12] = 0;
  1314. e[13] = 0;
  1315. e[14] = 0;
  1316. e[15] = 1;
  1317. }
  1318. static createAffineTransformation(trans, rot, scale, out) {
  1319. var oe = out.elements;
  1320. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  1321. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  1322. var wx = w * x2, wy = w * y2, wz = w * z2, sx = scale.x, sy = scale.y, sz = scale.z;
  1323. oe[0] = (1 - (yy + zz)) * sx;
  1324. oe[1] = (xy + wz) * sx;
  1325. oe[2] = (xz - wy) * sx;
  1326. oe[3] = 0;
  1327. oe[4] = (xy - wz) * sy;
  1328. oe[5] = (1 - (xx + zz)) * sy;
  1329. oe[6] = (yz + wx) * sy;
  1330. oe[7] = 0;
  1331. oe[8] = (xz + wy) * sz;
  1332. oe[9] = (yz - wx) * sz;
  1333. oe[10] = (1 - (xx + yy)) * sz;
  1334. oe[11] = 0;
  1335. oe[12] = trans.x;
  1336. oe[13] = trans.y;
  1337. oe[14] = trans.z;
  1338. oe[15] = 1;
  1339. }
  1340. static createLookAt(eye, target, up, out) {
  1341. var oE = out.elements;
  1342. var xaxis = Matrix4x4._tempVector0;
  1343. var yaxis = Matrix4x4._tempVector1;
  1344. var zaxis = Matrix4x4._tempVector2;
  1345. Vector3.subtract(eye, target, zaxis);
  1346. Vector3.normalize(zaxis, zaxis);
  1347. Vector3.cross(up, zaxis, xaxis);
  1348. Vector3.normalize(xaxis, xaxis);
  1349. Vector3.cross(zaxis, xaxis, yaxis);
  1350. oE[3] = oE[7] = oE[11] = 0;
  1351. oE[15] = 1;
  1352. oE[0] = xaxis.x;
  1353. oE[4] = xaxis.y;
  1354. oE[8] = xaxis.z;
  1355. oE[1] = yaxis.x;
  1356. oE[5] = yaxis.y;
  1357. oE[9] = yaxis.z;
  1358. oE[2] = zaxis.x;
  1359. oE[6] = zaxis.y;
  1360. oE[10] = zaxis.z;
  1361. oE[12] = -Vector3.dot(xaxis, eye);
  1362. oE[13] = -Vector3.dot(yaxis, eye);
  1363. oE[14] = -Vector3.dot(zaxis, eye);
  1364. }
  1365. static createPerspective(fov, aspect, znear, zfar, out) {
  1366. var yScale = 1.0 / Math.tan(fov * 0.5);
  1367. var xScale = yScale / aspect;
  1368. var halfWidth = znear / xScale;
  1369. var halfHeight = znear / yScale;
  1370. Matrix4x4.createPerspectiveOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, znear, zfar, out);
  1371. }
  1372. static createPerspectiveOffCenter(left, right, bottom, top, znear, zfar, out) {
  1373. var oe = out.elements;
  1374. var zRange = zfar / (zfar - znear);
  1375. oe[1] = oe[2] = oe[3] = oe[4] = oe[6] = oe[7] = oe[12] = oe[13] = oe[15] = 0;
  1376. oe[0] = 2.0 * znear / (right - left);
  1377. oe[5] = 2.0 * znear / (top - bottom);
  1378. oe[8] = (left + right) / (right - left);
  1379. oe[9] = (top + bottom) / (top - bottom);
  1380. oe[10] = -zRange;
  1381. oe[11] = -1.0;
  1382. oe[14] = -znear * zRange;
  1383. }
  1384. static createOrthoOffCenter(left, right, bottom, top, znear, zfar, out) {
  1385. var oe = out.elements;
  1386. var zRange = 1.0 / (zfar - znear);
  1387. oe[1] = oe[2] = oe[3] = oe[4] = oe[6] = oe[8] = oe[7] = oe[9] = oe[11] = 0;
  1388. oe[15] = 1;
  1389. oe[0] = 2.0 / (right - left);
  1390. oe[5] = 2.0 / (top - bottom);
  1391. oe[10] = -zRange;
  1392. oe[12] = (left + right) / (left - right);
  1393. oe[13] = (top + bottom) / (bottom - top);
  1394. oe[14] = -znear * zRange;
  1395. }
  1396. getElementByRowColumn(row, column) {
  1397. if (row < 0 || row > 3)
  1398. throw new Error("row Rows and columns for matrices run from 0 to 3, inclusive.");
  1399. if (column < 0 || column > 3)
  1400. throw new Error("column Rows and columns for matrices run from 0 to 3, inclusive.");
  1401. return this.elements[(row * 4) + column];
  1402. }
  1403. setElementByRowColumn(row, column, value) {
  1404. if (row < 0 || row > 3)
  1405. throw new Error("row Rows and columns for matrices run from 0 to 3, inclusive.");
  1406. if (column < 0 || column > 3)
  1407. throw new Error("column Rows and columns for matrices run from 0 to 3, inclusive.");
  1408. this.elements[(row * 4) + column] = value;
  1409. }
  1410. equalsOtherMatrix(other) {
  1411. var e = this.elements;
  1412. var oe = other.elements;
  1413. 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]));
  1414. }
  1415. decomposeTransRotScale(translation, rotation, scale) {
  1416. var rotationMatrix = Matrix4x4._tempMatrix4x4;
  1417. if (this.decomposeTransRotMatScale(translation, rotationMatrix, scale)) {
  1418. Quaternion.createFromMatrix4x4(rotationMatrix, rotation);
  1419. return true;
  1420. }
  1421. else {
  1422. rotation.identity();
  1423. return false;
  1424. }
  1425. }
  1426. decomposeTransRotMatScale(translation, rotationMatrix, scale) {
  1427. var e = this.elements;
  1428. var te = translation;
  1429. var re = rotationMatrix.elements;
  1430. var se = scale;
  1431. te.x = e[12];
  1432. te.y = e[13];
  1433. te.z = e[14];
  1434. var m11 = e[0], m12 = e[1], m13 = e[2];
  1435. var m21 = e[4], m22 = e[5], m23 = e[6];
  1436. var m31 = e[8], m32 = e[9], m33 = e[10];
  1437. var sX = se.x = Math.sqrt((m11 * m11) + (m12 * m12) + (m13 * m13));
  1438. var sY = se.y = Math.sqrt((m21 * m21) + (m22 * m22) + (m23 * m23));
  1439. var sZ = se.z = Math.sqrt((m31 * m31) + (m32 * m32) + (m33 * m33));
  1440. if (MathUtils3D.isZero(sX) || MathUtils3D.isZero(sY) || MathUtils3D.isZero(sZ)) {
  1441. 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;
  1442. re[0] = re[5] = re[10] = re[15] = 1;
  1443. return false;
  1444. }
  1445. var at = Matrix4x4._tempVector0;
  1446. at.x = m31 / sZ;
  1447. at.y = m32 / sZ;
  1448. at.z = m33 / sZ;
  1449. var tempRight = Matrix4x4._tempVector1;
  1450. tempRight.x = m11 / sX;
  1451. tempRight.y = m12 / sX;
  1452. tempRight.z = m13 / sX;
  1453. var up = Matrix4x4._tempVector2;
  1454. Vector3.cross(at, tempRight, up);
  1455. var right = Matrix4x4._tempVector1;
  1456. Vector3.cross(up, at, right);
  1457. re[3] = re[7] = re[11] = re[12] = re[13] = re[14] = 0;
  1458. re[15] = 1;
  1459. re[0] = right.x;
  1460. re[1] = right.y;
  1461. re[2] = right.z;
  1462. re[4] = up.x;
  1463. re[5] = up.y;
  1464. re[6] = up.z;
  1465. re[8] = at.x;
  1466. re[9] = at.y;
  1467. re[10] = at.z;
  1468. ((re[0] * m11 + re[1] * m12 + re[2] * m13) < 0.0) && (se.x = -sX);
  1469. ((re[4] * m21 + re[5] * m22 + re[6] * m23) < 0.0) && (se.y = -sY);
  1470. ((re[8] * m31 + re[9] * m32 + re[10] * m33) < 0.0) && (se.z = -sZ);
  1471. return true;
  1472. }
  1473. decomposeYawPitchRoll(yawPitchRoll) {
  1474. var pitch = Math.asin(-this.elements[9]);
  1475. yawPitchRoll.y = pitch;
  1476. var test = Math.cos(pitch);
  1477. if (test > MathUtils3D.zeroTolerance) {
  1478. yawPitchRoll.z = Math.atan2(this.elements[1], this.elements[5]);
  1479. yawPitchRoll.x = Math.atan2(this.elements[8], this.elements[10]);
  1480. }
  1481. else {
  1482. yawPitchRoll.z = Math.atan2(-this.elements[4], this.elements[0]);
  1483. yawPitchRoll.x = 0.0;
  1484. }
  1485. }
  1486. normalize() {
  1487. var v = this.elements;
  1488. var c = v[0], d = v[1], e = v[2], g = Math.sqrt(c * c + d * d + e * e);
  1489. if (g) {
  1490. if (g == 1)
  1491. return;
  1492. }
  1493. else {
  1494. v[0] = 0;
  1495. v[1] = 0;
  1496. v[2] = 0;
  1497. return;
  1498. }
  1499. g = 1 / g;
  1500. v[0] = c * g;
  1501. v[1] = d * g;
  1502. v[2] = e * g;
  1503. }
  1504. transpose() {
  1505. var e, t;
  1506. e = this.elements;
  1507. t = e[1];
  1508. e[1] = e[4];
  1509. e[4] = t;
  1510. t = e[2];
  1511. e[2] = e[8];
  1512. e[8] = t;
  1513. t = e[3];
  1514. e[3] = e[12];
  1515. e[12] = t;
  1516. t = e[6];
  1517. e[6] = e[9];
  1518. e[9] = t;
  1519. t = e[7];
  1520. e[7] = e[13];
  1521. e[13] = t;
  1522. t = e[11];
  1523. e[11] = e[14];
  1524. e[14] = t;
  1525. return this;
  1526. }
  1527. invert(out) {
  1528. var ae = this.elements;
  1529. var oe = out.elements;
  1530. 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;
  1531. if (Math.abs(det) === 0.0) {
  1532. return;
  1533. }
  1534. det = 1.0 / det;
  1535. oe[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  1536. oe[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  1537. oe[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  1538. oe[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  1539. oe[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  1540. oe[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  1541. oe[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  1542. oe[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  1543. oe[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  1544. oe[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  1545. oe[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  1546. oe[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  1547. oe[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  1548. oe[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  1549. oe[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  1550. oe[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  1551. }
  1552. static billboard(objectPosition, cameraPosition, cameraRight, cameraUp, cameraForward, mat) {
  1553. Vector3.subtract(objectPosition, cameraPosition, Matrix4x4._tempVector0);
  1554. var lengthSq = Vector3.scalarLengthSquared(Matrix4x4._tempVector0);
  1555. if (MathUtils3D.isZero(lengthSq)) {
  1556. Vector3.scale(cameraForward, -1, Matrix4x4._tempVector1);
  1557. Matrix4x4._tempVector1.cloneTo(Matrix4x4._tempVector0);
  1558. }
  1559. else {
  1560. Vector3.scale(Matrix4x4._tempVector0, 1 / Math.sqrt(lengthSq), Matrix4x4._tempVector0);
  1561. }
  1562. Vector3.cross(cameraUp, Matrix4x4._tempVector0, Matrix4x4._tempVector2);
  1563. Vector3.normalize(Matrix4x4._tempVector2, Matrix4x4._tempVector2);
  1564. Vector3.cross(Matrix4x4._tempVector0, Matrix4x4._tempVector2, Matrix4x4._tempVector3);
  1565. var crosse = Matrix4x4._tempVector2;
  1566. var finale = Matrix4x4._tempVector3;
  1567. var diffee = Matrix4x4._tempVector0;
  1568. var obpose = objectPosition;
  1569. var mate = mat.elements;
  1570. mate[0] = crosse.x;
  1571. mate[1] = crosse.y;
  1572. mate[2] = crosse.z;
  1573. mate[3] = 0.0;
  1574. mate[4] = finale.x;
  1575. mate[5] = finale.y;
  1576. mate[6] = finale.z;
  1577. mate[7] = 0.0;
  1578. mate[8] = diffee.x;
  1579. mate[9] = diffee.y;
  1580. mate[10] = diffee.z;
  1581. mate[11] = 0.0;
  1582. mate[12] = obpose.x;
  1583. mate[13] = obpose.y;
  1584. mate[14] = obpose.z;
  1585. mate[15] = 1.0;
  1586. }
  1587. identity() {
  1588. var e = this.elements;
  1589. 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;
  1590. e[0] = e[5] = e[10] = e[15] = 1;
  1591. }
  1592. cloneTo(destObject) {
  1593. var i, s, d;
  1594. s = this.elements;
  1595. d = destObject.elements;
  1596. if (s === d) {
  1597. return;
  1598. }
  1599. for (i = 0; i < 16; ++i) {
  1600. d[i] = s[i];
  1601. }
  1602. }
  1603. clone() {
  1604. var dest = new Matrix4x4();
  1605. this.cloneTo(dest);
  1606. return dest;
  1607. }
  1608. static translation(v3, out) {
  1609. var oe = out.elements;
  1610. oe[0] = oe[5] = oe[10] = oe[15] = 1;
  1611. oe[12] = v3.x;
  1612. oe[13] = v3.y;
  1613. oe[14] = v3.z;
  1614. }
  1615. getTranslationVector(out) {
  1616. var me = this.elements;
  1617. out.x = me[12];
  1618. out.y = me[13];
  1619. out.z = me[14];
  1620. }
  1621. setTranslationVector(translate) {
  1622. var me = this.elements;
  1623. var ve = translate;
  1624. me[12] = ve.x;
  1625. me[13] = ve.y;
  1626. me[14] = ve.z;
  1627. }
  1628. getForward(out) {
  1629. var me = this.elements;
  1630. out.x = -me[8];
  1631. out.y = -me[9];
  1632. out.z = -me[10];
  1633. }
  1634. setForward(forward) {
  1635. var me = this.elements;
  1636. me[8] = -forward.x;
  1637. me[9] = -forward.y;
  1638. me[10] = -forward.z;
  1639. }
  1640. }
  1641. Matrix4x4._tempMatrix4x4 = new Matrix4x4();
  1642. Matrix4x4.TEMPMatrix0 = new Matrix4x4();
  1643. Matrix4x4.TEMPMatrix1 = new Matrix4x4();
  1644. Matrix4x4._tempVector0 = new Vector3();
  1645. Matrix4x4._tempVector1 = new Vector3();
  1646. Matrix4x4._tempVector2 = new Vector3();
  1647. Matrix4x4._tempVector3 = new Vector3();
  1648. Matrix4x4._tempQuaternion = new Quaternion();
  1649. Matrix4x4.DEFAULT = new Matrix4x4();
  1650. Matrix4x4.ZERO = new Matrix4x4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1651. class ColliderShape {
  1652. constructor() {
  1653. this._scale = new Vector3(1, 1, 1);
  1654. this._centerMatrix = new Matrix4x4();
  1655. this._attatched = false;
  1656. this._indexInCompound = -1;
  1657. this._compoundParent = null;
  1658. this._attatchedCollisionObject = null;
  1659. this._referenceCount = 0;
  1660. this._localOffset = new Vector3(0, 0, 0);
  1661. this._localRotation = new Quaternion(0, 0, 0, 1);
  1662. this.needsCustomCollisionCallback = false;
  1663. }
  1664. static __init__() {
  1665. var bt = ILaya3D.Physics3D._bullet;
  1666. ColliderShape._btScale = bt.btVector3_create(1, 1, 1);
  1667. ColliderShape._btVector30 = bt.btVector3_create(0, 0, 0);
  1668. ColliderShape._btQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  1669. ColliderShape._btTransform0 = bt.btTransform_create();
  1670. }
  1671. static _createAffineTransformation(trans, rot, outE) {
  1672. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  1673. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  1674. var wx = w * x2, wy = w * y2, wz = w * z2;
  1675. outE[0] = (1 - (yy + zz));
  1676. outE[1] = (xy + wz);
  1677. outE[2] = (xz - wy);
  1678. outE[3] = 0;
  1679. outE[4] = (xy - wz);
  1680. outE[5] = (1 - (xx + zz));
  1681. outE[6] = (yz + wx);
  1682. outE[7] = 0;
  1683. outE[8] = (xz + wy);
  1684. outE[9] = (yz - wx);
  1685. outE[10] = (1 - (xx + yy));
  1686. outE[11] = 0;
  1687. outE[12] = trans.x;
  1688. outE[13] = trans.y;
  1689. outE[14] = trans.z;
  1690. outE[15] = 1;
  1691. }
  1692. get type() {
  1693. return this._type;
  1694. }
  1695. get localOffset() {
  1696. return this._localOffset;
  1697. }
  1698. set localOffset(value) {
  1699. this._localOffset = value;
  1700. if (this._compoundParent)
  1701. this._compoundParent._updateChildTransform(this);
  1702. }
  1703. get localRotation() {
  1704. return this._localRotation;
  1705. }
  1706. set localRotation(value) {
  1707. this._localRotation = value;
  1708. if (this._compoundParent)
  1709. this._compoundParent._updateChildTransform(this);
  1710. }
  1711. _setScale(value) {
  1712. if (this._compoundParent) {
  1713. this.updateLocalTransformations();
  1714. }
  1715. else {
  1716. var bt = ILaya3D.Physics3D._bullet;
  1717. bt.btVector3_setValue(ColliderShape._btScale, value.x, value.y, value.z);
  1718. bt.btCollisionShape_setLocalScaling(this._btShape, ColliderShape._btScale);
  1719. }
  1720. }
  1721. _addReference() {
  1722. this._referenceCount++;
  1723. }
  1724. _removeReference() {
  1725. this._referenceCount--;
  1726. }
  1727. updateLocalTransformations() {
  1728. if (this._compoundParent) {
  1729. var offset = ColliderShape._tempVector30;
  1730. Vector3.multiply(this.localOffset, this._scale, offset);
  1731. ColliderShape._createAffineTransformation(offset, this.localRotation, this._centerMatrix.elements);
  1732. }
  1733. else {
  1734. ColliderShape._createAffineTransformation(this.localOffset, this.localRotation, this._centerMatrix.elements);
  1735. }
  1736. }
  1737. cloneTo(destObject) {
  1738. var destColliderShape = destObject;
  1739. this._localOffset.cloneTo(destColliderShape.localOffset);
  1740. this._localRotation.cloneTo(destColliderShape.localRotation);
  1741. destColliderShape.localOffset = destColliderShape.localOffset;
  1742. destColliderShape.localRotation = destColliderShape.localRotation;
  1743. }
  1744. clone() {
  1745. return null;
  1746. }
  1747. destroy() {
  1748. if (this._btShape) {
  1749. ILaya3D.Physics3D._bullet.btCollisionShape_destroy(this._btShape);
  1750. this._btShape = null;
  1751. }
  1752. }
  1753. }
  1754. ColliderShape.SHAPEORIENTATION_UPX = 0;
  1755. ColliderShape.SHAPEORIENTATION_UPY = 1;
  1756. ColliderShape.SHAPEORIENTATION_UPZ = 2;
  1757. ColliderShape.SHAPETYPES_BOX = 0;
  1758. ColliderShape.SHAPETYPES_SPHERE = 1;
  1759. ColliderShape.SHAPETYPES_CYLINDER = 2;
  1760. ColliderShape.SHAPETYPES_CAPSULE = 3;
  1761. ColliderShape.SHAPETYPES_CONVEXHULL = 4;
  1762. ColliderShape.SHAPETYPES_COMPOUND = 5;
  1763. ColliderShape.SHAPETYPES_STATICPLANE = 6;
  1764. ColliderShape.SHAPETYPES_CONE = 7;
  1765. ColliderShape._tempVector30 = new Vector3();
  1766. class StaticPlaneColliderShape extends ColliderShape {
  1767. constructor(normal, offset) {
  1768. super();
  1769. this._normal = normal;
  1770. this._offset = offset;
  1771. this._type = ColliderShape.SHAPETYPES_STATICPLANE;
  1772. var bt = ILaya3D.Physics3D._bullet;
  1773. bt.btVector3_setValue(StaticPlaneColliderShape._btNormal, -normal.x, normal.y, normal.z);
  1774. this._btShape = bt.btStaticPlaneShape_create(StaticPlaneColliderShape._btNormal, offset);
  1775. }
  1776. static __init__() {
  1777. StaticPlaneColliderShape._btNormal = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  1778. }
  1779. clone() {
  1780. var dest = new StaticPlaneColliderShape(this._normal, this._offset);
  1781. this.cloneTo(dest);
  1782. return dest;
  1783. }
  1784. }
  1785. class CompoundColliderShape extends ColliderShape {
  1786. constructor() {
  1787. super();
  1788. this._childColliderShapes = [];
  1789. this._type = ColliderShape.SHAPETYPES_COMPOUND;
  1790. this._btShape = ILaya3D.Physics3D._bullet.btCompoundShape_create();
  1791. }
  1792. static __init__() {
  1793. var bt = ILaya3D.Physics3D._bullet;
  1794. CompoundColliderShape._btVector3One = bt.btVector3_create(1, 1, 1);
  1795. CompoundColliderShape._btTransform = bt.btTransform_create();
  1796. CompoundColliderShape._btOffset = bt.btVector3_create(0, 0, 0);
  1797. CompoundColliderShape._btRotation = bt.btQuaternion_create(0, 0, 0, 1);
  1798. }
  1799. _clearChildShape(shape) {
  1800. shape._attatched = false;
  1801. shape._compoundParent = null;
  1802. shape._indexInCompound = -1;
  1803. }
  1804. _addReference() {
  1805. }
  1806. _removeReference() {
  1807. }
  1808. _updateChildTransform(shape) {
  1809. var bt = ILaya3D.Physics3D._bullet;
  1810. var offset = shape.localOffset;
  1811. var rotation = shape.localRotation;
  1812. var btOffset = ColliderShape._btVector30;
  1813. var btQuaternion = ColliderShape._btQuaternion0;
  1814. var btTransform = ColliderShape._btTransform0;
  1815. bt.btVector3_setValue(btOffset, -offset.x, offset.y, offset.z);
  1816. bt.btQuaternion_setValue(btQuaternion, -rotation.x, rotation.y, rotation.z, -rotation.w);
  1817. bt.btTransform_setOrigin(btTransform, btOffset);
  1818. bt.btTransform_setRotation(btTransform, btQuaternion);
  1819. bt.btCompoundShape_updateChildTransform(this._btShape, shape._indexInCompound, btTransform, true);
  1820. }
  1821. addChildShape(shape) {
  1822. if (shape._attatched)
  1823. throw "CompoundColliderShape: this shape has attatched to other entity.";
  1824. shape._attatched = true;
  1825. shape._compoundParent = this;
  1826. shape._indexInCompound = this._childColliderShapes.length;
  1827. this._childColliderShapes.push(shape);
  1828. var offset = shape.localOffset;
  1829. var rotation = shape.localRotation;
  1830. var bt = ILaya3D.Physics3D._bullet;
  1831. bt.btVector3_setValue(CompoundColliderShape._btOffset, -offset.x, offset.y, offset.z);
  1832. bt.btQuaternion_setValue(CompoundColliderShape._btRotation, -rotation.x, rotation.y, rotation.z, -rotation.w);
  1833. bt.btTransform_setOrigin(CompoundColliderShape._btTransform, CompoundColliderShape._btOffset);
  1834. bt.btTransform_setRotation(CompoundColliderShape._btTransform, CompoundColliderShape._btRotation);
  1835. var btScale = bt.btCollisionShape_getLocalScaling(this._btShape);
  1836. bt.btCollisionShape_setLocalScaling(this._btShape, CompoundColliderShape._btVector3One);
  1837. bt.btCompoundShape_addChildShape(this._btShape, CompoundColliderShape._btTransform, shape._btShape);
  1838. bt.btCollisionShape_setLocalScaling(this._btShape, btScale);
  1839. (this._attatchedCollisionObject) && (this._attatchedCollisionObject.colliderShape = this);
  1840. }
  1841. removeChildShape(shape) {
  1842. if (shape._compoundParent === this) {
  1843. var index = shape._indexInCompound;
  1844. this._clearChildShape(shape);
  1845. var endShape = this._childColliderShapes[this._childColliderShapes.length - 1];
  1846. endShape._indexInCompound = index;
  1847. this._childColliderShapes[index] = endShape;
  1848. this._childColliderShapes.pop();
  1849. ILaya3D.Physics3D._bullet.btCompoundShape_removeChildShapeByIndex(this._btShape, index);
  1850. }
  1851. }
  1852. clearChildShape() {
  1853. for (var i = 0, n = this._childColliderShapes.length; i < n; i++) {
  1854. this._clearChildShape(this._childColliderShapes[i]);
  1855. ILaya3D.Physics3D._bullet.btCompoundShape_removeChildShapeByIndex(this._btShape, 0);
  1856. }
  1857. this._childColliderShapes.length = 0;
  1858. }
  1859. getChildShapeCount() {
  1860. return this._childColliderShapes.length;
  1861. }
  1862. cloneTo(destObject) {
  1863. var destCompoundColliderShape = destObject;
  1864. destCompoundColliderShape.clearChildShape();
  1865. for (var i = 0, n = this._childColliderShapes.length; i < n; i++)
  1866. destCompoundColliderShape.addChildShape(this._childColliderShapes[i].clone());
  1867. }
  1868. clone() {
  1869. var dest = new CompoundColliderShape();
  1870. this.cloneTo(dest);
  1871. return dest;
  1872. }
  1873. destroy() {
  1874. super.destroy();
  1875. for (var i = 0, n = this._childColliderShapes.length; i < n; i++) {
  1876. var childShape = this._childColliderShapes[i];
  1877. if (childShape._referenceCount === 0)
  1878. childShape.destroy();
  1879. }
  1880. }
  1881. }
  1882. class Transform3D extends Laya.EventDispatcher {
  1883. constructor(owner) {
  1884. super();
  1885. this._localPosition = new Vector3(0, 0, 0);
  1886. this._localRotation = new Quaternion(0, 0, 0, 1);
  1887. this._localScale = new Vector3(1, 1, 1);
  1888. this._localRotationEuler = new Vector3(0, 0, 0);
  1889. this._localMatrix = new Matrix4x4();
  1890. this._position = new Vector3(0, 0, 0);
  1891. this._rotation = new Quaternion(0, 0, 0, 1);
  1892. this._scale = new Vector3(1, 1, 1);
  1893. this._rotationEuler = new Vector3(0, 0, 0);
  1894. this._worldMatrix = new Matrix4x4();
  1895. this._children = null;
  1896. this._parent = null;
  1897. this._dummy = null;
  1898. this._transformFlag = 0;
  1899. this._owner = owner;
  1900. this._children = [];
  1901. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION | Transform3D.TRANSFORM_LOCALEULER | Transform3D.TRANSFORM_LOCALMATRIX, false);
  1902. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER | Transform3D.TRANSFORM_WORLDSCALE | Transform3D.TRANSFORM_WORLDMATRIX, true);
  1903. }
  1904. get _isFrontFaceInvert() {
  1905. var scale = this.getWorldLossyScale();
  1906. var isInvert = scale.x < 0;
  1907. (scale.y < 0) && (isInvert = !isInvert);
  1908. (scale.z < 0) && (isInvert = !isInvert);
  1909. return isInvert;
  1910. }
  1911. get owner() {
  1912. return this._owner;
  1913. }
  1914. get worldNeedUpdate() {
  1915. return this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX);
  1916. }
  1917. get localPositionX() {
  1918. return this._localPosition.x;
  1919. }
  1920. set localPositionX(x) {
  1921. this._localPosition.x = x;
  1922. this.localPosition = this._localPosition;
  1923. }
  1924. get localPositionY() {
  1925. return this._localPosition.y;
  1926. }
  1927. set localPositionY(y) {
  1928. this._localPosition.y = y;
  1929. this.localPosition = this._localPosition;
  1930. }
  1931. get localPositionZ() {
  1932. return this._localPosition.z;
  1933. }
  1934. set localPositionZ(z) {
  1935. this._localPosition.z = z;
  1936. this.localPosition = this._localPosition;
  1937. }
  1938. get localPosition() {
  1939. return this._localPosition;
  1940. }
  1941. set localPosition(value) {
  1942. if (this._localPosition !== value)
  1943. value.cloneTo(this._localPosition);
  1944. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, true);
  1945. this._onWorldPositionTransform();
  1946. }
  1947. get localRotationX() {
  1948. return this.localRotation.x;
  1949. }
  1950. set localRotationX(x) {
  1951. this._localRotation.x = x;
  1952. this.localRotation = this._localRotation;
  1953. }
  1954. get localRotationY() {
  1955. return this.localRotation.y;
  1956. }
  1957. set localRotationY(y) {
  1958. this._localRotation.y = y;
  1959. this.localRotation = this._localRotation;
  1960. }
  1961. get localRotationZ() {
  1962. return this.localRotation.z;
  1963. }
  1964. set localRotationZ(z) {
  1965. this._localRotation.z = z;
  1966. this.localRotation = this._localRotation;
  1967. }
  1968. get localRotationW() {
  1969. return this.localRotation.w;
  1970. }
  1971. set localRotationW(w) {
  1972. this._localRotation.w = w;
  1973. this.localRotation = this._localRotation;
  1974. }
  1975. get localRotation() {
  1976. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION)) {
  1977. var eulerE = this._localRotationEuler;
  1978. Quaternion.createFromYawPitchRoll(eulerE.y / Transform3D._angleToRandin, eulerE.x / Transform3D._angleToRandin, eulerE.z / Transform3D._angleToRandin, this._localRotation);
  1979. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION, false);
  1980. }
  1981. return this._localRotation;
  1982. }
  1983. set localRotation(value) {
  1984. if (this._localRotation !== value)
  1985. value.cloneTo(this._localRotation);
  1986. this._localRotation.normalize(this._localRotation);
  1987. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER | Transform3D.TRANSFORM_LOCALMATRIX, true);
  1988. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION, false);
  1989. this._onWorldRotationTransform();
  1990. }
  1991. get localScaleX() {
  1992. return this._localScale.x;
  1993. }
  1994. set localScaleX(value) {
  1995. this._localScale.x = value;
  1996. this.localScale = this._localScale;
  1997. }
  1998. get localScaleY() {
  1999. return this._localScale.y;
  2000. }
  2001. set localScaleY(value) {
  2002. this._localScale.y = value;
  2003. this.localScale = this._localScale;
  2004. }
  2005. get localScaleZ() {
  2006. return this._localScale.z;
  2007. }
  2008. set localScaleZ(value) {
  2009. this._localScale.z = value;
  2010. this.localScale = this._localScale;
  2011. }
  2012. get localScale() {
  2013. return this._localScale;
  2014. }
  2015. set localScale(value) {
  2016. if (this._localScale !== value)
  2017. value.cloneTo(this._localScale);
  2018. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, true);
  2019. this._onWorldScaleTransform();
  2020. }
  2021. get localRotationEulerX() {
  2022. return this.localRotationEuler.x;
  2023. }
  2024. set localRotationEulerX(value) {
  2025. this._localRotationEuler.x = value;
  2026. this.localRotationEuler = this._localRotationEuler;
  2027. }
  2028. get localRotationEulerY() {
  2029. return this.localRotationEuler.y;
  2030. }
  2031. set localRotationEulerY(value) {
  2032. this._localRotationEuler.y = value;
  2033. this.localRotationEuler = this._localRotationEuler;
  2034. }
  2035. get localRotationEulerZ() {
  2036. return this.localRotationEuler.z;
  2037. }
  2038. set localRotationEulerZ(value) {
  2039. this._localRotationEuler.z = value;
  2040. this.localRotationEuler = this._localRotationEuler;
  2041. }
  2042. get localRotationEuler() {
  2043. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALEULER)) {
  2044. this._localRotation.getYawPitchRoll(Transform3D._tempVector30);
  2045. var euler = Transform3D._tempVector30;
  2046. var localRotationEuler = this._localRotationEuler;
  2047. localRotationEuler.x = euler.y * Transform3D._angleToRandin;
  2048. localRotationEuler.y = euler.x * Transform3D._angleToRandin;
  2049. localRotationEuler.z = euler.z * Transform3D._angleToRandin;
  2050. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, false);
  2051. }
  2052. return this._localRotationEuler;
  2053. }
  2054. set localRotationEuler(value) {
  2055. if (this._localRotationEuler !== value)
  2056. value.cloneTo(this._localRotationEuler);
  2057. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, false);
  2058. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION | Transform3D.TRANSFORM_LOCALMATRIX, true);
  2059. this._onWorldRotationTransform();
  2060. }
  2061. get localMatrix() {
  2062. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX)) {
  2063. Matrix4x4.createAffineTransformation(this._localPosition, this.localRotation, this._localScale, this._localMatrix);
  2064. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, false);
  2065. }
  2066. return this._localMatrix;
  2067. }
  2068. set localMatrix(value) {
  2069. if (this._localMatrix !== value)
  2070. value.cloneTo(this._localMatrix);
  2071. this._localMatrix.decomposeTransRotScale(this._localPosition, this._localRotation, this._localScale);
  2072. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, true);
  2073. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, false);
  2074. this._onWorldTransform();
  2075. }
  2076. get position() {
  2077. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  2078. if (this._parent != null) {
  2079. var worldMatE = this.worldMatrix.elements;
  2080. this._position.x = worldMatE[12];
  2081. this._position.y = worldMatE[13];
  2082. this._position.z = worldMatE[14];
  2083. }
  2084. else {
  2085. this._localPosition.cloneTo(this._position);
  2086. }
  2087. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  2088. }
  2089. return this._position;
  2090. }
  2091. set position(value) {
  2092. if (this._parent != null) {
  2093. var parentInvMat = Transform3D._tempMatrix0;
  2094. this._parent.worldMatrix.invert(parentInvMat);
  2095. Vector3.transformCoordinate(value, parentInvMat, this._localPosition);
  2096. }
  2097. else {
  2098. value.cloneTo(this._localPosition);
  2099. }
  2100. this.localPosition = this._localPosition;
  2101. if (this._position !== value)
  2102. value.cloneTo(this._position);
  2103. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  2104. }
  2105. get rotation() {
  2106. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) {
  2107. if (this._parent != null)
  2108. Quaternion.multiply(this._parent.rotation, this.localRotation, this._rotation);
  2109. else
  2110. this.localRotation.cloneTo(this._rotation);
  2111. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  2112. }
  2113. return this._rotation;
  2114. }
  2115. set rotation(value) {
  2116. if (this._parent != null) {
  2117. this._parent.rotation.invert(Transform3D._tempQuaternion0);
  2118. Quaternion.multiply(Transform3D._tempQuaternion0, value, this._localRotation);
  2119. }
  2120. else {
  2121. value.cloneTo(this._localRotation);
  2122. }
  2123. this.localRotation = this._localRotation;
  2124. if (value !== this._rotation)
  2125. value.cloneTo(this._rotation);
  2126. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  2127. }
  2128. get rotationEuler() {
  2129. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  2130. this.rotation.getYawPitchRoll(Transform3D._tempVector30);
  2131. var eulerE = Transform3D._tempVector30;
  2132. var rotationEulerE = this._rotationEuler;
  2133. rotationEulerE.x = eulerE.y * Transform3D._angleToRandin;
  2134. rotationEulerE.y = eulerE.x * Transform3D._angleToRandin;
  2135. rotationEulerE.z = eulerE.z * Transform3D._angleToRandin;
  2136. this._setTransformFlag(Transform3D.TRANSFORM_WORLDEULER, false);
  2137. }
  2138. return this._rotationEuler;
  2139. }
  2140. set rotationEuler(value) {
  2141. Quaternion.createFromYawPitchRoll(value.y / Transform3D._angleToRandin, value.x / Transform3D._angleToRandin, value.z / Transform3D._angleToRandin, this._rotation);
  2142. this.rotation = this._rotation;
  2143. if (this._rotationEuler !== value)
  2144. value.cloneTo(this._rotationEuler);
  2145. this._setTransformFlag(Transform3D.TRANSFORM_WORLDEULER, false);
  2146. }
  2147. get worldMatrix() {
  2148. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX)) {
  2149. if (this._parent != null)
  2150. Matrix4x4.multiply(this._parent.worldMatrix, this.localMatrix, this._worldMatrix);
  2151. else
  2152. this.localMatrix.cloneTo(this._worldMatrix);
  2153. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX, false);
  2154. }
  2155. return this._worldMatrix;
  2156. }
  2157. set worldMatrix(value) {
  2158. if (this._parent === null) {
  2159. value.cloneTo(this._localMatrix);
  2160. }
  2161. else {
  2162. this._parent.worldMatrix.invert(this._localMatrix);
  2163. Matrix4x4.multiply(this._localMatrix, value, this._localMatrix);
  2164. }
  2165. this.localMatrix = this._localMatrix;
  2166. if (this._worldMatrix !== value)
  2167. value.cloneTo(this._worldMatrix);
  2168. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX, false);
  2169. }
  2170. _getScaleMatrix() {
  2171. var invRotation = Transform3D._tempQuaternion0;
  2172. var invRotationMat = Transform3D._tempMatrix3x30;
  2173. var worldRotScaMat = Transform3D._tempMatrix3x31;
  2174. var scaMat = Transform3D._tempMatrix3x32;
  2175. Matrix3x3.createFromMatrix4x4(this.worldMatrix, worldRotScaMat);
  2176. this.rotation.invert(invRotation);
  2177. Matrix3x3.createRotationQuaternion(invRotation, invRotationMat);
  2178. Matrix3x3.multiply(invRotationMat, worldRotScaMat, scaMat);
  2179. return scaMat;
  2180. }
  2181. _setTransformFlag(type, value) {
  2182. if (value)
  2183. this._transformFlag |= type;
  2184. else
  2185. this._transformFlag &= ~type;
  2186. }
  2187. _getTransformFlag(type) {
  2188. return (this._transformFlag & type) != 0;
  2189. }
  2190. _setParent(value) {
  2191. if (this._parent !== value) {
  2192. if (this._parent) {
  2193. var parentChilds = this._parent._children;
  2194. var index = parentChilds.indexOf(this);
  2195. parentChilds.splice(index, 1);
  2196. }
  2197. if (value) {
  2198. value._children.push(this);
  2199. (value) && (this._onWorldTransform());
  2200. }
  2201. this._parent = value;
  2202. }
  2203. }
  2204. _onWorldPositionRotationTransform() {
  2205. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  2206. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER, true);
  2207. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2208. for (var i = 0, n = this._children.length; i < n; i++)
  2209. this._children[i]._onWorldPositionRotationTransform();
  2210. }
  2211. }
  2212. _onWorldPositionScaleTransform() {
  2213. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2214. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDSCALE, true);
  2215. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2216. for (var i = 0, n = this._children.length; i < n; i++)
  2217. this._children[i]._onWorldPositionScaleTransform();
  2218. }
  2219. }
  2220. _onWorldPositionTransform() {
  2221. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  2222. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION, true);
  2223. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2224. for (var i = 0, n = this._children.length; i < n; i++)
  2225. this._children[i]._onWorldPositionTransform();
  2226. }
  2227. }
  2228. _onWorldRotationTransform() {
  2229. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  2230. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER, true);
  2231. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2232. for (var i = 0, n = this._children.length; i < n; i++)
  2233. this._children[i]._onWorldPositionRotationTransform();
  2234. }
  2235. }
  2236. _onWorldScaleTransform() {
  2237. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2238. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDSCALE, true);
  2239. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2240. for (var i = 0, n = this._children.length; i < n; i++)
  2241. this._children[i]._onWorldPositionScaleTransform();
  2242. }
  2243. }
  2244. _onWorldTransform() {
  2245. 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)) {
  2246. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER | Transform3D.TRANSFORM_WORLDSCALE, true);
  2247. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2248. for (var i = 0, n = this._children.length; i < n; i++)
  2249. this._children[i]._onWorldTransform();
  2250. }
  2251. }
  2252. translate(translation, isLocal = true) {
  2253. if (isLocal) {
  2254. Matrix4x4.createFromQuaternion(this.localRotation, Transform3D._tempMatrix0);
  2255. Vector3.transformCoordinate(translation, Transform3D._tempMatrix0, Transform3D._tempVector30);
  2256. Vector3.add(this.localPosition, Transform3D._tempVector30, this._localPosition);
  2257. this.localPosition = this._localPosition;
  2258. }
  2259. else {
  2260. Vector3.add(this.position, translation, this._position);
  2261. this.position = this._position;
  2262. }
  2263. }
  2264. rotate(rotation, isLocal = true, isRadian = true) {
  2265. var rot;
  2266. if (isRadian) {
  2267. rot = rotation;
  2268. }
  2269. else {
  2270. Vector3.scale(rotation, Math.PI / 180.0, Transform3D._tempVector30);
  2271. rot = Transform3D._tempVector30;
  2272. }
  2273. Quaternion.createFromYawPitchRoll(rot.y, rot.x, rot.z, Transform3D._tempQuaternion0);
  2274. if (isLocal) {
  2275. Quaternion.multiply(this._localRotation, Transform3D._tempQuaternion0, this._localRotation);
  2276. this.localRotation = this._localRotation;
  2277. }
  2278. else {
  2279. Quaternion.multiply(Transform3D._tempQuaternion0, this.rotation, this._rotation);
  2280. this.rotation = this._rotation;
  2281. }
  2282. }
  2283. getForward(forward) {
  2284. var worldMatElem = this.worldMatrix.elements;
  2285. forward.x = -worldMatElem[8];
  2286. forward.y = -worldMatElem[9];
  2287. forward.z = -worldMatElem[10];
  2288. }
  2289. getUp(up) {
  2290. var worldMatElem = this.worldMatrix.elements;
  2291. up.x = worldMatElem[4];
  2292. up.y = worldMatElem[5];
  2293. up.z = worldMatElem[6];
  2294. }
  2295. getRight(right) {
  2296. var worldMatElem = this.worldMatrix.elements;
  2297. right.x = worldMatElem[0];
  2298. right.y = worldMatElem[1];
  2299. right.z = worldMatElem[2];
  2300. }
  2301. lookAt(target, up, isLocal = false) {
  2302. var eye;
  2303. if (isLocal) {
  2304. eye = this._localPosition;
  2305. 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)
  2306. return;
  2307. Quaternion.lookAt(this._localPosition, target, up, this._localRotation);
  2308. this._localRotation.invert(this._localRotation);
  2309. this.localRotation = this._localRotation;
  2310. }
  2311. else {
  2312. var worldPosition = this.position;
  2313. eye = worldPosition;
  2314. 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)
  2315. return;
  2316. Quaternion.lookAt(worldPosition, target, up, this._rotation);
  2317. this._rotation.invert(this._rotation);
  2318. this.rotation = this._rotation;
  2319. }
  2320. }
  2321. getWorldLossyScale() {
  2322. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2323. if (this._parent !== null) {
  2324. var scaMatE = this._getScaleMatrix().elements;
  2325. this._scale.x = scaMatE[0];
  2326. this._scale.y = scaMatE[4];
  2327. this._scale.z = scaMatE[8];
  2328. }
  2329. else {
  2330. this._localScale.cloneTo(this._scale);
  2331. }
  2332. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  2333. }
  2334. return this._scale;
  2335. }
  2336. setWorldLossyScale(value) {
  2337. if (this._parent !== null) {
  2338. var scaleMat = Transform3D._tempMatrix3x33;
  2339. var localScaleMat = Transform3D._tempMatrix3x33;
  2340. var localScaleMatE = localScaleMat.elements;
  2341. var parInvScaleMat = this._parent._getScaleMatrix();
  2342. parInvScaleMat.invert(parInvScaleMat);
  2343. Matrix3x3.createFromScaling(value, scaleMat);
  2344. Matrix3x3.multiply(parInvScaleMat, scaleMat, localScaleMat);
  2345. this._localScale.x = localScaleMatE[0];
  2346. this._localScale.y = localScaleMatE[4];
  2347. this._localScale.z = localScaleMatE[8];
  2348. }
  2349. else {
  2350. value.cloneTo(this._localScale);
  2351. }
  2352. this.localScale = this._localScale;
  2353. if (this._scale !== value)
  2354. value.cloneTo(this._scale);
  2355. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  2356. }
  2357. get scale() {
  2358. console.warn("Transfrm3D: discard function,please use getWorldLossyScale instead.");
  2359. return this.getWorldLossyScale();
  2360. }
  2361. set scale(value) {
  2362. console.warn("Transfrm3D: discard function,please use setWorldLossyScale instead.");
  2363. this.setWorldLossyScale(value);
  2364. }
  2365. }
  2366. Transform3D._tempVector30 = new Vector3();
  2367. Transform3D._tempQuaternion0 = new Quaternion();
  2368. Transform3D._tempMatrix0 = new Matrix4x4();
  2369. Transform3D._tempMatrix3x30 = new Matrix3x3();
  2370. Transform3D._tempMatrix3x31 = new Matrix3x3();
  2371. Transform3D._tempMatrix3x32 = new Matrix3x3();
  2372. Transform3D._tempMatrix3x33 = new Matrix3x3();
  2373. Transform3D.TRANSFORM_LOCALQUATERNION = 0x01;
  2374. Transform3D.TRANSFORM_LOCALEULER = 0x02;
  2375. Transform3D.TRANSFORM_LOCALMATRIX = 0x04;
  2376. Transform3D.TRANSFORM_WORLDPOSITION = 0x08;
  2377. Transform3D.TRANSFORM_WORLDQUATERNION = 0x10;
  2378. Transform3D.TRANSFORM_WORLDSCALE = 0x20;
  2379. Transform3D.TRANSFORM_WORLDMATRIX = 0x40;
  2380. Transform3D.TRANSFORM_WORLDEULER = 0x80;
  2381. Transform3D._angleToRandin = 180 / Math.PI;
  2382. class Physics3DUtils {
  2383. constructor() {
  2384. }
  2385. static setColliderCollision(collider1, collider2, collsion) {
  2386. }
  2387. static getIColliderCollision(collider1, collider2) {
  2388. return false;
  2389. }
  2390. }
  2391. Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER = 0x1;
  2392. Physics3DUtils.COLLISIONFILTERGROUP_STATICFILTER = 0x2;
  2393. Physics3DUtils.COLLISIONFILTERGROUP_KINEMATICFILTER = 0x4;
  2394. Physics3DUtils.COLLISIONFILTERGROUP_DEBRISFILTER = 0x8;
  2395. Physics3DUtils.COLLISIONFILTERGROUP_SENSORTRIGGER = 0x10;
  2396. Physics3DUtils.COLLISIONFILTERGROUP_CHARACTERFILTER = 0x20;
  2397. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER1 = 0x40;
  2398. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER2 = 0x80;
  2399. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER3 = 0x100;
  2400. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER4 = 0x200;
  2401. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER5 = 0x400;
  2402. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER6 = 0x800;
  2403. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER7 = 0x1000;
  2404. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER8 = 0x2000;
  2405. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER9 = 0x4000;
  2406. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER10 = 0x8000;
  2407. Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER = -1;
  2408. Physics3DUtils.gravity = new Vector3(0, -9.81, 0);
  2409. class BoxColliderShape extends ColliderShape {
  2410. constructor(sizeX = 1.0, sizeY = 1.0, sizeZ = 1.0) {
  2411. super();
  2412. this._sizeX = sizeX;
  2413. this._sizeY = sizeY;
  2414. this._sizeZ = sizeZ;
  2415. this._type = ColliderShape.SHAPETYPES_BOX;
  2416. var bt = ILaya3D.Physics3D._bullet;
  2417. bt.btVector3_setValue(BoxColliderShape._btSize, sizeX / 2, sizeY / 2, sizeZ / 2);
  2418. this._btShape = bt.btBoxShape_create(BoxColliderShape._btSize);
  2419. }
  2420. static __init__() {
  2421. BoxColliderShape._btSize = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  2422. }
  2423. get sizeX() {
  2424. return this._sizeX;
  2425. }
  2426. get sizeY() {
  2427. return this._sizeY;
  2428. }
  2429. get sizeZ() {
  2430. return this._sizeZ;
  2431. }
  2432. clone() {
  2433. var dest = new BoxColliderShape(this._sizeX, this._sizeY, this._sizeZ);
  2434. this.cloneTo(dest);
  2435. return dest;
  2436. }
  2437. }
  2438. class CapsuleColliderShape extends ColliderShape {
  2439. constructor(radius = 0.5, length = 1.25, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  2440. super();
  2441. this._radius = radius;
  2442. this._length = length;
  2443. this._orientation = orientation;
  2444. this._type = ColliderShape.SHAPETYPES_CAPSULE;
  2445. var bt = ILaya3D.Physics3D._bullet;
  2446. switch (orientation) {
  2447. case ColliderShape.SHAPEORIENTATION_UPX:
  2448. this._btShape = bt.btCapsuleShapeX_create(radius, length - radius * 2);
  2449. break;
  2450. case ColliderShape.SHAPEORIENTATION_UPY:
  2451. this._btShape = bt.btCapsuleShape_create(radius, length - radius * 2);
  2452. break;
  2453. case ColliderShape.SHAPEORIENTATION_UPZ:
  2454. this._btShape = bt.btCapsuleShapeZ_create(radius, length - radius * 2);
  2455. break;
  2456. default:
  2457. throw "CapsuleColliderShape:unknown orientation.";
  2458. }
  2459. }
  2460. get radius() {
  2461. return this._radius;
  2462. }
  2463. get length() {
  2464. return this._length;
  2465. }
  2466. get orientation() {
  2467. return this._orientation;
  2468. }
  2469. _setScale(value) {
  2470. var fixScale = CapsuleColliderShape._tempVector30;
  2471. switch (this.orientation) {
  2472. case ColliderShape.SHAPEORIENTATION_UPX:
  2473. fixScale.x = value.x;
  2474. fixScale.y = fixScale.z = Math.max(value.y, value.z);
  2475. break;
  2476. case ColliderShape.SHAPEORIENTATION_UPY:
  2477. fixScale.y = value.y;
  2478. fixScale.x = fixScale.z = Math.max(value.x, value.z);
  2479. break;
  2480. case ColliderShape.SHAPEORIENTATION_UPZ:
  2481. fixScale.z = value.z;
  2482. fixScale.x = fixScale.y = Math.max(value.x, value.y);
  2483. break;
  2484. default:
  2485. throw "CapsuleColliderShape:unknown orientation.";
  2486. }
  2487. super._setScale(fixScale);
  2488. }
  2489. clone() {
  2490. var dest = new CapsuleColliderShape(this._radius, this._length, this._orientation);
  2491. this.cloneTo(dest);
  2492. return dest;
  2493. }
  2494. }
  2495. CapsuleColliderShape._tempVector30 = new Vector3();
  2496. class ConeColliderShape extends ColliderShape {
  2497. constructor(radius = 0.5, height = 1.0, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  2498. super();
  2499. this._radius = 1;
  2500. this._height = 0.5;
  2501. this._radius = radius;
  2502. this._height = height;
  2503. this._orientation = orientation;
  2504. this._type = ColliderShape.SHAPETYPES_CYLINDER;
  2505. var bt = ILaya3D.Physics3D._bullet;
  2506. switch (orientation) {
  2507. case ColliderShape.SHAPEORIENTATION_UPX:
  2508. this._btShape = bt.btConeShapeX_create(radius, height);
  2509. break;
  2510. case ColliderShape.SHAPEORIENTATION_UPY:
  2511. this._btShape = bt.btConeShape_create(radius, height);
  2512. break;
  2513. case ColliderShape.SHAPEORIENTATION_UPZ:
  2514. this._btShape = bt.btConeShapeZ_create(radius, height);
  2515. break;
  2516. default:
  2517. throw "ConeColliderShape:unknown orientation.";
  2518. }
  2519. }
  2520. get radius() {
  2521. return this._radius;
  2522. }
  2523. get height() {
  2524. return this._height;
  2525. }
  2526. get orientation() {
  2527. return this._orientation;
  2528. }
  2529. clone() {
  2530. var dest = new ConeColliderShape(this._radius, this._height, this._orientation);
  2531. this.cloneTo(dest);
  2532. return dest;
  2533. }
  2534. }
  2535. class CylinderColliderShape extends ColliderShape {
  2536. constructor(radius = 0.5, height = 1.0, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  2537. super();
  2538. this._radius = 1;
  2539. this._height = 0.5;
  2540. this._radius = radius;
  2541. this._height = height;
  2542. this._orientation = orientation;
  2543. this._type = ColliderShape.SHAPETYPES_CYLINDER;
  2544. var bt = ILaya3D.Physics3D._bullet;
  2545. switch (orientation) {
  2546. case ColliderShape.SHAPEORIENTATION_UPX:
  2547. bt.btVector3_setValue(CylinderColliderShape._btSize, height / 2, radius, radius);
  2548. this._btShape = bt.btCylinderShapeX_create(CylinderColliderShape._btSize);
  2549. break;
  2550. case ColliderShape.SHAPEORIENTATION_UPY:
  2551. bt.btVector3_setValue(CylinderColliderShape._btSize, radius, height / 2, radius);
  2552. this._btShape = bt.btCylinderShape_create(CylinderColliderShape._btSize);
  2553. break;
  2554. case ColliderShape.SHAPEORIENTATION_UPZ:
  2555. bt.btVector3_setValue(CylinderColliderShape._btSize, radius, radius, height / 2);
  2556. this._btShape = bt.btCylinderShapeZ_create(CylinderColliderShape._btSize);
  2557. break;
  2558. default:
  2559. throw "CapsuleColliderShape:unknown orientation.";
  2560. }
  2561. }
  2562. static __init__() {
  2563. CylinderColliderShape._btSize = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  2564. }
  2565. get radius() {
  2566. return this._radius;
  2567. }
  2568. get height() {
  2569. return this._height;
  2570. }
  2571. get orientation() {
  2572. return this._orientation;
  2573. }
  2574. clone() {
  2575. var dest = new CylinderColliderShape(this._radius, this._height, this._orientation);
  2576. this.cloneTo(dest);
  2577. return dest;
  2578. }
  2579. }
  2580. class MeshColliderShape extends ColliderShape {
  2581. constructor() {
  2582. super();
  2583. this._mesh = null;
  2584. this._convex = false;
  2585. }
  2586. get mesh() {
  2587. return this._mesh;
  2588. }
  2589. set mesh(value) {
  2590. if (this._mesh !== value) {
  2591. var bt = ILaya3D.Physics3D._bullet;
  2592. if (this._mesh) {
  2593. bt.btCollisionShape_destroy(this._btShape);
  2594. }
  2595. if (value) {
  2596. this._btShape = bt.btGImpactMeshShape_create(value._getPhysicMesh());
  2597. bt.btGImpactShapeInterface_updateBound(this._btShape);
  2598. }
  2599. this._mesh = value;
  2600. }
  2601. }
  2602. get convex() {
  2603. return this._convex;
  2604. }
  2605. set convex(value) {
  2606. this._convex = value;
  2607. }
  2608. _setScale(value) {
  2609. if (this._compoundParent) {
  2610. this.updateLocalTransformations();
  2611. }
  2612. else {
  2613. var bt = ILaya3D.Physics3D._bullet;
  2614. bt.btVector3_setValue(ColliderShape._btScale, value.x, value.y, value.z);
  2615. bt.btCollisionShape_setLocalScaling(this._btShape, ColliderShape._btScale);
  2616. bt.btGImpactShapeInterface_updateBound(this._btShape);
  2617. }
  2618. }
  2619. cloneTo(destObject) {
  2620. var destMeshCollider = destObject;
  2621. destMeshCollider.convex = this._convex;
  2622. destMeshCollider.mesh = this._mesh;
  2623. super.cloneTo(destObject);
  2624. }
  2625. clone() {
  2626. var dest = new MeshColliderShape();
  2627. this.cloneTo(dest);
  2628. return dest;
  2629. }
  2630. destroy() {
  2631. if (this._btShape) {
  2632. ILaya3D.Physics3D._bullet.btCollisionShape_destroy(this._btShape);
  2633. this._btShape = null;
  2634. }
  2635. }
  2636. }
  2637. class SphereColliderShape extends ColliderShape {
  2638. constructor(radius = 0.5) {
  2639. super();
  2640. this._radius = radius;
  2641. this._type = ColliderShape.SHAPETYPES_SPHERE;
  2642. this._btShape = ILaya3D.Physics3D._bullet.btSphereShape_create(radius);
  2643. }
  2644. get radius() {
  2645. return this._radius;
  2646. }
  2647. clone() {
  2648. var dest = new SphereColliderShape(this._radius);
  2649. this.cloneTo(dest);
  2650. return dest;
  2651. }
  2652. }
  2653. class PhysicsComponent extends Laya.Component {
  2654. constructor(collisionGroup, canCollideWith) {
  2655. super();
  2656. this._restitution = 0.0;
  2657. this._friction = 0.5;
  2658. this._rollingFriction = 0.0;
  2659. this._ccdMotionThreshold = 0.0;
  2660. this._ccdSweptSphereRadius = 0.0;
  2661. this._collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER;
  2662. this._canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER;
  2663. this._colliderShape = null;
  2664. this._transformFlag = 2147483647;
  2665. this._controlBySimulation = false;
  2666. this._enableProcessCollisions = true;
  2667. this._inPhysicUpdateListIndex = -1;
  2668. this.canScaleShape = true;
  2669. this._collisionGroup = collisionGroup;
  2670. this._canCollideWith = canCollideWith;
  2671. PhysicsComponent._physicObjectsMap[this.id] = this;
  2672. }
  2673. static __init__() {
  2674. var bt = ILaya3D.Physics3D._bullet;
  2675. PhysicsComponent._btVector30 = bt.btVector3_create(0, 0, 0);
  2676. PhysicsComponent._btQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  2677. }
  2678. static _createAffineTransformationArray(tranX, tranY, tranZ, rotX, rotY, rotZ, rotW, scale, outE) {
  2679. var x2 = rotX + rotX, y2 = rotY + rotY, z2 = rotZ + rotZ;
  2680. var xx = rotX * x2, xy = rotX * y2, xz = rotX * z2, yy = rotY * y2, yz = rotY * z2, zz = rotZ * z2;
  2681. var wx = rotW * x2, wy = rotW * y2, wz = rotW * z2, sx = scale[0], sy = scale[1], sz = scale[2];
  2682. outE[0] = (1 - (yy + zz)) * sx;
  2683. outE[1] = (xy + wz) * sx;
  2684. outE[2] = (xz - wy) * sx;
  2685. outE[3] = 0;
  2686. outE[4] = (xy - wz) * sy;
  2687. outE[5] = (1 - (xx + zz)) * sy;
  2688. outE[6] = (yz + wx) * sy;
  2689. outE[7] = 0;
  2690. outE[8] = (xz + wy) * sz;
  2691. outE[9] = (yz - wx) * sz;
  2692. outE[10] = (1 - (xx + yy)) * sz;
  2693. outE[11] = 0;
  2694. outE[12] = tranX;
  2695. outE[13] = tranY;
  2696. outE[14] = tranZ;
  2697. outE[15] = 1;
  2698. }
  2699. static _creatShape(shapeData) {
  2700. var colliderShape;
  2701. switch (shapeData.type) {
  2702. case "BoxColliderShape":
  2703. var sizeData = shapeData.size;
  2704. colliderShape = sizeData ? new BoxColliderShape(sizeData[0], sizeData[1], sizeData[2]) : new BoxColliderShape();
  2705. break;
  2706. case "SphereColliderShape":
  2707. colliderShape = new SphereColliderShape(shapeData.radius);
  2708. break;
  2709. case "CapsuleColliderShape":
  2710. colliderShape = new CapsuleColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  2711. break;
  2712. case "MeshColliderShape":
  2713. var meshCollider = new MeshColliderShape();
  2714. shapeData.mesh && (meshCollider.mesh = Laya.Loader.getRes(shapeData.mesh));
  2715. colliderShape = meshCollider;
  2716. break;
  2717. case "ConeColliderShape":
  2718. colliderShape = new ConeColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  2719. break;
  2720. case "CylinderColliderShape":
  2721. colliderShape = new CylinderColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  2722. break;
  2723. default:
  2724. throw "unknown shape type.";
  2725. }
  2726. if (shapeData.center) {
  2727. var localOffset = colliderShape.localOffset;
  2728. localOffset.fromArray(shapeData.center);
  2729. colliderShape.localOffset = localOffset;
  2730. }
  2731. return colliderShape;
  2732. }
  2733. static physicVector3TransformQuat(source, qx, qy, qz, qw, out) {
  2734. 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;
  2735. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2736. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2737. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2738. }
  2739. static physicQuaternionMultiply(lx, ly, lz, lw, right, out) {
  2740. var rx = right.x;
  2741. var ry = right.y;
  2742. var rz = right.z;
  2743. var rw = right.w;
  2744. var a = (ly * rz - lz * ry);
  2745. var b = (lz * rx - lx * rz);
  2746. var c = (lx * ry - ly * rx);
  2747. var d = (lx * rx + ly * ry + lz * rz);
  2748. out.x = (lx * rw + rx * lw) + a;
  2749. out.y = (ly * rw + ry * lw) + b;
  2750. out.z = (lz * rw + rz * lw) + c;
  2751. out.w = lw * rw - d;
  2752. }
  2753. get restitution() {
  2754. return this._restitution;
  2755. }
  2756. set restitution(value) {
  2757. this._restitution = value;
  2758. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setRestitution(this._btColliderObject, value);
  2759. }
  2760. get friction() {
  2761. return this._friction;
  2762. }
  2763. set friction(value) {
  2764. this._friction = value;
  2765. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setFriction(this._btColliderObject, value);
  2766. }
  2767. get rollingFriction() {
  2768. return this._rollingFriction;
  2769. }
  2770. set rollingFriction(value) {
  2771. this._rollingFriction = value;
  2772. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setRollingFriction(this._btColliderObject, value);
  2773. }
  2774. get ccdMotionThreshold() {
  2775. return this._ccdMotionThreshold;
  2776. }
  2777. set ccdMotionThreshold(value) {
  2778. this._ccdMotionThreshold = value;
  2779. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setCcdMotionThreshold(this._btColliderObject, value);
  2780. }
  2781. get ccdSweptSphereRadius() {
  2782. return this._ccdSweptSphereRadius;
  2783. }
  2784. set ccdSweptSphereRadius(value) {
  2785. this._ccdSweptSphereRadius = value;
  2786. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setCcdSweptSphereRadius(this._btColliderObject, value);
  2787. }
  2788. get isActive() {
  2789. return this._btColliderObject ? ILaya3D.Physics3D._bullet.btCollisionObject_isActive(this._btColliderObject) : false;
  2790. }
  2791. get colliderShape() {
  2792. return this._colliderShape;
  2793. }
  2794. set colliderShape(value) {
  2795. var lastColliderShape = this._colliderShape;
  2796. if (lastColliderShape) {
  2797. lastColliderShape._attatched = false;
  2798. lastColliderShape._attatchedCollisionObject = null;
  2799. }
  2800. this._colliderShape = value;
  2801. if (value) {
  2802. if (value._attatched) {
  2803. throw "PhysicsComponent: this shape has attatched to other entity.";
  2804. }
  2805. else {
  2806. value._attatched = true;
  2807. value._attatchedCollisionObject = this;
  2808. }
  2809. if (this._btColliderObject) {
  2810. ILaya3D.Physics3D._bullet.btCollisionObject_setCollisionShape(this._btColliderObject, value._btShape);
  2811. var canInSimulation = this._simulation && this._enabled;
  2812. (canInSimulation && lastColliderShape) && (this._removeFromSimulation());
  2813. this._onShapeChange(value);
  2814. if (canInSimulation) {
  2815. this._derivePhysicsTransformation(true);
  2816. this._addToSimulation();
  2817. }
  2818. }
  2819. }
  2820. else {
  2821. if (this._simulation && this._enabled)
  2822. lastColliderShape && this._removeFromSimulation();
  2823. }
  2824. }
  2825. get simulation() {
  2826. return this._simulation;
  2827. }
  2828. get collisionGroup() {
  2829. return this._collisionGroup;
  2830. }
  2831. set collisionGroup(value) {
  2832. if (this._collisionGroup !== value) {
  2833. this._collisionGroup = value;
  2834. if (this._simulation && this._colliderShape && this._enabled) {
  2835. this._removeFromSimulation();
  2836. this._addToSimulation();
  2837. }
  2838. }
  2839. }
  2840. get canCollideWith() {
  2841. return this._canCollideWith;
  2842. }
  2843. set canCollideWith(value) {
  2844. if (this._canCollideWith !== value) {
  2845. this._canCollideWith = value;
  2846. if (this._simulation && this._colliderShape && this._enabled) {
  2847. this._removeFromSimulation();
  2848. this._addToSimulation();
  2849. }
  2850. }
  2851. }
  2852. _parseShape(shapesData) {
  2853. var shapeCount = shapesData.length;
  2854. if (shapeCount === 1) {
  2855. var shape = PhysicsComponent._creatShape(shapesData[0]);
  2856. this.colliderShape = shape;
  2857. }
  2858. else {
  2859. var compoundShape = new CompoundColliderShape();
  2860. for (var i = 0; i < shapeCount; i++) {
  2861. shape = PhysicsComponent._creatShape(shapesData[i]);
  2862. compoundShape.addChildShape(shape);
  2863. }
  2864. this.colliderShape = compoundShape;
  2865. }
  2866. }
  2867. _onScaleChange(scale) {
  2868. this._colliderShape._setScale(scale);
  2869. }
  2870. _onEnable() {
  2871. this._simulation = this.owner._scene.physicsSimulation;
  2872. ILaya3D.Physics3D._bullet.btCollisionObject_setContactProcessingThreshold(this._btColliderObject, 1e30);
  2873. if (this._colliderShape) {
  2874. this._derivePhysicsTransformation(true);
  2875. this._addToSimulation();
  2876. }
  2877. }
  2878. _onDisable() {
  2879. if (this._colliderShape) {
  2880. this._removeFromSimulation();
  2881. (this._inPhysicUpdateListIndex !== -1) && (this._simulation._physicsUpdateList.remove(this));
  2882. }
  2883. this._simulation = null;
  2884. }
  2885. _onDestroy() {
  2886. delete PhysicsComponent._physicObjectsMap[this.id];
  2887. ILaya3D.Physics3D._bullet.btCollisionObject_destroy(this._btColliderObject);
  2888. this._colliderShape.destroy();
  2889. super._onDestroy();
  2890. this._btColliderObject = null;
  2891. this._colliderShape = null;
  2892. this._simulation = null;
  2893. this.owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  2894. }
  2895. _isValid() {
  2896. return this._simulation && this._colliderShape && this._enabled;
  2897. }
  2898. _parse(data) {
  2899. (data.collisionGroup != null) && (this.collisionGroup = data.collisionGroup);
  2900. (data.canCollideWith != null) && (this.canCollideWith = data.canCollideWith);
  2901. (data.ccdMotionThreshold != null) && (this.ccdMotionThreshold = data.ccdMotionThreshold);
  2902. (data.ccdSweptSphereRadius != null) && (this.ccdSweptSphereRadius = data.ccdSweptSphereRadius);
  2903. }
  2904. _setTransformFlag(type, value) {
  2905. if (value)
  2906. this._transformFlag |= type;
  2907. else
  2908. this._transformFlag &= ~type;
  2909. }
  2910. _getTransformFlag(type) {
  2911. return (this._transformFlag & type) != 0;
  2912. }
  2913. _addToSimulation() {
  2914. }
  2915. _removeFromSimulation() {
  2916. }
  2917. _derivePhysicsTransformation(force) {
  2918. var bt = ILaya3D.Physics3D._bullet;
  2919. var btColliderObject = this._btColliderObject;
  2920. var btTransform = bt.btCollisionObject_getWorldTransform(btColliderObject);
  2921. this._innerDerivePhysicsTransformation(btTransform, force);
  2922. bt.btCollisionObject_setWorldTransform(btColliderObject, btTransform);
  2923. }
  2924. _innerDerivePhysicsTransformation(physicTransformOut, force) {
  2925. var bt = ILaya3D.Physics3D._bullet;
  2926. var transform = this.owner._transform;
  2927. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  2928. var shapeOffset = this._colliderShape.localOffset;
  2929. var position = transform.position;
  2930. var btPosition = PhysicsComponent._btVector30;
  2931. if (shapeOffset.x !== 0 || shapeOffset.y !== 0 || shapeOffset.z !== 0) {
  2932. var physicPosition = PhysicsComponent._tempVector30;
  2933. var worldMat = transform.worldMatrix;
  2934. Vector3.transformCoordinate(shapeOffset, worldMat, physicPosition);
  2935. bt.btVector3_setValue(btPosition, -physicPosition.x, physicPosition.y, physicPosition.z);
  2936. }
  2937. else {
  2938. bt.btVector3_setValue(btPosition, -position.x, position.y, position.z);
  2939. }
  2940. bt.btTransform_setOrigin(physicTransformOut, btPosition);
  2941. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  2942. }
  2943. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) {
  2944. var shapeRotation = this._colliderShape.localRotation;
  2945. var btRotation = PhysicsComponent._btQuaternion0;
  2946. var rotation = transform.rotation;
  2947. if (shapeRotation.x !== 0 || shapeRotation.y !== 0 || shapeRotation.z !== 0 || shapeRotation.w !== 1) {
  2948. var physicRotation = PhysicsComponent._tempQuaternion0;
  2949. PhysicsComponent.physicQuaternionMultiply(rotation.x, rotation.y, rotation.z, rotation.w, shapeRotation, physicRotation);
  2950. bt.btQuaternion_setValue(btRotation, -physicRotation.x, physicRotation.y, physicRotation.z, -physicRotation.w);
  2951. }
  2952. else {
  2953. bt.btQuaternion_setValue(btRotation, -rotation.x, rotation.y, rotation.z, -rotation.w);
  2954. }
  2955. bt.btTransform_setRotation(physicTransformOut, btRotation);
  2956. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  2957. }
  2958. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2959. this._onScaleChange(transform.getWorldLossyScale());
  2960. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  2961. }
  2962. }
  2963. _updateTransformComponent(physicsTransform) {
  2964. var bt = ILaya3D.Physics3D._bullet;
  2965. var colliderShape = this._colliderShape;
  2966. var localOffset = colliderShape.localOffset;
  2967. var localRotation = colliderShape.localRotation;
  2968. var transform = this.owner._transform;
  2969. var position = transform.position;
  2970. var rotation = transform.rotation;
  2971. var btPosition = bt.btTransform_getOrigin(physicsTransform);
  2972. var btRotation = bt.btTransform_getRotation(physicsTransform);
  2973. var btRotX = -bt.btQuaternion_x(btRotation);
  2974. var btRotY = bt.btQuaternion_y(btRotation);
  2975. var btRotZ = bt.btQuaternion_z(btRotation);
  2976. var btRotW = -bt.btQuaternion_w(btRotation);
  2977. if (localRotation.x !== 0 || localRotation.y !== 0 || localRotation.z !== 0 || localRotation.w !== 1) {
  2978. var invertShapeRotaion = PhysicsComponent._tempQuaternion0;
  2979. localRotation.invert(invertShapeRotaion);
  2980. PhysicsComponent.physicQuaternionMultiply(btRotX, btRotY, btRotZ, btRotW, invertShapeRotaion, rotation);
  2981. }
  2982. else {
  2983. rotation.x = btRotX;
  2984. rotation.y = btRotY;
  2985. rotation.z = btRotZ;
  2986. rotation.w = btRotW;
  2987. }
  2988. transform.rotation = rotation;
  2989. if (localOffset.x !== 0 || localOffset.y !== 0 || localOffset.z !== 0) {
  2990. var btScale = bt.btCollisionShape_getLocalScaling(colliderShape._btShape);
  2991. var rotShapePosition = PhysicsComponent._tempVector30;
  2992. rotShapePosition.x = localOffset.x * bt.btVector3_x(btScale);
  2993. rotShapePosition.y = localOffset.y * bt.btVector3_y(btScale);
  2994. rotShapePosition.z = localOffset.z * bt.btVector3_z(btScale);
  2995. Vector3.transformQuat(rotShapePosition, rotation, rotShapePosition);
  2996. position.x = -bt.btVector3_x(btPosition) - rotShapePosition.x;
  2997. position.y = bt.btVector3_y(btPosition) - rotShapePosition.y;
  2998. position.z = bt.btVector3_z(btPosition) - rotShapePosition.z;
  2999. }
  3000. else {
  3001. position.x = -bt.btVector3_x(btPosition);
  3002. position.y = bt.btVector3_y(btPosition);
  3003. position.z = bt.btVector3_z(btPosition);
  3004. }
  3005. transform.position = position;
  3006. }
  3007. _onShapeChange(colShape) {
  3008. var btColObj = this._btColliderObject;
  3009. var bt = ILaya3D.Physics3D._bullet;
  3010. var flags = bt.btCollisionObject_getCollisionFlags(btColObj);
  3011. if (colShape.needsCustomCollisionCallback) {
  3012. if ((flags & PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK) === 0)
  3013. bt.btCollisionObject_setCollisionFlags(btColObj, flags | PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK);
  3014. }
  3015. else {
  3016. if ((flags & PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK) > 0)
  3017. bt.btCollisionObject_setCollisionFlags(btColObj, flags ^ PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK);
  3018. }
  3019. }
  3020. _onAdded() {
  3021. this.enabled = this._enabled;
  3022. this.restitution = this._restitution;
  3023. this.friction = this._friction;
  3024. this.rollingFriction = this._rollingFriction;
  3025. this.ccdMotionThreshold = this._ccdMotionThreshold;
  3026. this.ccdSweptSphereRadius = this._ccdSweptSphereRadius;
  3027. this.owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  3028. }
  3029. _onTransformChanged(flag) {
  3030. if (PhysicsComponent._addUpdateList || !this._controlBySimulation) {
  3031. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  3032. if (flag) {
  3033. this._transformFlag |= flag;
  3034. if (this._isValid() && this._inPhysicUpdateListIndex === -1)
  3035. this._simulation._physicsUpdateList.add(this);
  3036. }
  3037. }
  3038. }
  3039. _cloneTo(dest) {
  3040. var destPhysicsComponent = dest;
  3041. destPhysicsComponent.restitution = this._restitution;
  3042. destPhysicsComponent.friction = this._friction;
  3043. destPhysicsComponent.rollingFriction = this._rollingFriction;
  3044. destPhysicsComponent.ccdMotionThreshold = this._ccdMotionThreshold;
  3045. destPhysicsComponent.ccdSweptSphereRadius = this._ccdSweptSphereRadius;
  3046. destPhysicsComponent.collisionGroup = this._collisionGroup;
  3047. destPhysicsComponent.canCollideWith = this._canCollideWith;
  3048. destPhysicsComponent.canScaleShape = this.canScaleShape;
  3049. (this._colliderShape) && (destPhysicsComponent.colliderShape = this._colliderShape.clone());
  3050. }
  3051. }
  3052. PhysicsComponent.ACTIVATIONSTATE_ACTIVE_TAG = 1;
  3053. PhysicsComponent.ACTIVATIONSTATE_ISLAND_SLEEPING = 2;
  3054. PhysicsComponent.ACTIVATIONSTATE_WANTS_DEACTIVATION = 3;
  3055. PhysicsComponent.ACTIVATIONSTATE_DISABLE_DEACTIVATION = 4;
  3056. PhysicsComponent.ACTIVATIONSTATE_DISABLE_SIMULATION = 5;
  3057. PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT = 1;
  3058. PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT = 2;
  3059. PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE = 4;
  3060. PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK = 8;
  3061. PhysicsComponent.COLLISIONFLAGS_CHARACTER_OBJECT = 16;
  3062. PhysicsComponent.COLLISIONFLAGS_DISABLE_VISUALIZE_OBJECT = 32;
  3063. PhysicsComponent.COLLISIONFLAGS_DISABLE_SPU_COLLISION_PROCESSING = 64;
  3064. PhysicsComponent._tempVector30 = new Vector3();
  3065. PhysicsComponent._tempQuaternion0 = new Quaternion();
  3066. PhysicsComponent._tempQuaternion1 = new Quaternion();
  3067. PhysicsComponent._tempMatrix4x40 = new Matrix4x4();
  3068. PhysicsComponent._physicObjectsMap = {};
  3069. PhysicsComponent._addUpdateList = true;
  3070. class SingletonList {
  3071. constructor() {
  3072. this.elements = [];
  3073. this.length = 0;
  3074. }
  3075. _add(element) {
  3076. if (this.length === this.elements.length)
  3077. this.elements.push(element);
  3078. else
  3079. this.elements[this.length] = element;
  3080. }
  3081. add(element) {
  3082. if (this.length === this.elements.length)
  3083. this.elements.push(element);
  3084. else
  3085. this.elements[this.length] = element;
  3086. this.length++;
  3087. }
  3088. }
  3089. class PhysicsUpdateList extends SingletonList {
  3090. constructor() {
  3091. super();
  3092. }
  3093. add(element) {
  3094. var index = element._inPhysicUpdateListIndex;
  3095. if (index !== -1)
  3096. throw "PhysicsUpdateList:element has in PhysicsUpdateList.";
  3097. this._add(element);
  3098. element._inPhysicUpdateListIndex = this.length++;
  3099. }
  3100. remove(element) {
  3101. var index = element._inPhysicUpdateListIndex;
  3102. this.length--;
  3103. if (index !== this.length) {
  3104. var end = this.elements[this.length];
  3105. this.elements[index] = end;
  3106. end._inPhysicUpdateListIndex = index;
  3107. }
  3108. element._inPhysicUpdateListIndex = -1;
  3109. }
  3110. }
  3111. class ContactPoint {
  3112. constructor() {
  3113. this._idCounter = 0;
  3114. this.colliderA = null;
  3115. this.colliderB = null;
  3116. this.distance = 0;
  3117. this.normal = new Vector3();
  3118. this.positionOnA = new Vector3();
  3119. this.positionOnB = new Vector3();
  3120. this._id = ++this._idCounter;
  3121. }
  3122. }
  3123. class HitResult {
  3124. constructor() {
  3125. this.succeeded = false;
  3126. this.collider = null;
  3127. this.point = new Vector3();
  3128. this.normal = new Vector3();
  3129. this.hitFraction = 0;
  3130. }
  3131. }
  3132. class Collision {
  3133. constructor() {
  3134. this._lastUpdateFrame = -2147483648;
  3135. this._updateFrame = -2147483648;
  3136. this._isTrigger = false;
  3137. this.contacts = [];
  3138. }
  3139. _setUpdateFrame(farme) {
  3140. this._lastUpdateFrame = this._updateFrame;
  3141. this._updateFrame = farme;
  3142. }
  3143. }
  3144. class CollisionTool {
  3145. constructor() {
  3146. this._hitResultsPoolIndex = 0;
  3147. this._hitResultsPool = [];
  3148. this._contactPonintsPoolIndex = 0;
  3149. this._contactPointsPool = [];
  3150. this._collisionsPool = [];
  3151. this._collisions = {};
  3152. }
  3153. getHitResult() {
  3154. var hitResult = this._hitResultsPool[this._hitResultsPoolIndex++];
  3155. if (!hitResult) {
  3156. hitResult = new HitResult();
  3157. this._hitResultsPool.push(hitResult);
  3158. }
  3159. return hitResult;
  3160. }
  3161. recoverAllHitResultsPool() {
  3162. this._hitResultsPoolIndex = 0;
  3163. }
  3164. getContactPoints() {
  3165. var contactPoint = this._contactPointsPool[this._contactPonintsPoolIndex++];
  3166. if (!contactPoint) {
  3167. contactPoint = new ContactPoint();
  3168. this._contactPointsPool.push(contactPoint);
  3169. }
  3170. return contactPoint;
  3171. }
  3172. recoverAllContactPointsPool() {
  3173. this._contactPonintsPoolIndex = 0;
  3174. }
  3175. getCollision(physicComponentA, physicComponentB) {
  3176. var collision;
  3177. var idA = physicComponentA.id;
  3178. var idB = physicComponentB.id;
  3179. var subCollisionFirst = this._collisions[idA];
  3180. if (subCollisionFirst)
  3181. collision = subCollisionFirst[idB];
  3182. if (!collision) {
  3183. if (!subCollisionFirst) {
  3184. subCollisionFirst = {};
  3185. this._collisions[idA] = subCollisionFirst;
  3186. }
  3187. collision = this._collisionsPool.length === 0 ? new Collision() : this._collisionsPool.pop();
  3188. collision._colliderA = physicComponentA;
  3189. collision._colliderB = physicComponentB;
  3190. subCollisionFirst[idB] = collision;
  3191. }
  3192. return collision;
  3193. }
  3194. recoverCollision(collision) {
  3195. var idA = collision._colliderA.id;
  3196. var idB = collision._colliderB.id;
  3197. this._collisions[idA][idB] = null;
  3198. this._collisionsPool.push(collision);
  3199. }
  3200. garbageCollection() {
  3201. this._hitResultsPoolIndex = 0;
  3202. this._hitResultsPool.length = 0;
  3203. this._contactPonintsPoolIndex = 0;
  3204. this._contactPointsPool.length = 0;
  3205. this._collisionsPool.length = 0;
  3206. for (var subCollisionsKey in this._collisionsPool) {
  3207. var subCollisions = this._collisionsPool[subCollisionsKey];
  3208. var wholeDelete = true;
  3209. for (var collisionKey in subCollisions) {
  3210. if (subCollisions[collisionKey])
  3211. wholeDelete = false;
  3212. else
  3213. delete subCollisions[collisionKey];
  3214. }
  3215. if (wholeDelete)
  3216. delete this._collisionsPool[subCollisionsKey];
  3217. }
  3218. }
  3219. }
  3220. class PhysicsSimulation {
  3221. constructor(configuration, flags = 0) {
  3222. this._gravity = new Vector3(0, -10, 0);
  3223. this._btVector3Zero = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  3224. this._btDefaultQuaternion = ILaya3D.Physics3D._bullet.btQuaternion_create(0, 0, 0, -1);
  3225. this._collisionsUtils = new CollisionTool();
  3226. this._previousFrameCollisions = [];
  3227. this._currentFrameCollisions = [];
  3228. this._currentConstraint = {};
  3229. this._physicsUpdateList = new PhysicsUpdateList();
  3230. this._characters = [];
  3231. this._updatedRigidbodies = 0;
  3232. this.maxSubSteps = 1;
  3233. this.fixedTimeStep = 1.0 / 60.0;
  3234. this.maxSubSteps = configuration.maxSubSteps;
  3235. this.fixedTimeStep = configuration.fixedTimeStep;
  3236. var bt = ILaya3D.Physics3D._bullet;
  3237. this._btCollisionConfiguration = bt.btDefaultCollisionConfiguration_create();
  3238. this._btDispatcher = bt.btCollisionDispatcher_create(this._btCollisionConfiguration);
  3239. this._btBroadphase = bt.btDbvtBroadphase_create();
  3240. bt.btOverlappingPairCache_setInternalGhostPairCallback(bt.btDbvtBroadphase_getOverlappingPairCache(this._btBroadphase), bt.btGhostPairCallback_create());
  3241. var conFlags = configuration.flags;
  3242. if (conFlags & PhysicsSimulation.PHYSICSENGINEFLAGS_COLLISIONSONLY) {
  3243. this._btCollisionWorld = new bt.btCollisionWorld(this._btDispatcher, this._btBroadphase, this._btCollisionConfiguration);
  3244. }
  3245. else if (conFlags & PhysicsSimulation.PHYSICSENGINEFLAGS_SOFTBODYSUPPORT) {
  3246. throw "PhysicsSimulation:SoftBody processing is not yet available";
  3247. }
  3248. else {
  3249. var solver = bt.btSequentialImpulseConstraintSolver_create();
  3250. this._btDiscreteDynamicsWorld = bt.btDiscreteDynamicsWorld_create(this._btDispatcher, this._btBroadphase, solver, this._btCollisionConfiguration);
  3251. this._btCollisionWorld = this._btDiscreteDynamicsWorld;
  3252. }
  3253. if (this._btDiscreteDynamicsWorld) {
  3254. this._btSolverInfo = bt.btDynamicsWorld_getSolverInfo(this._btDiscreteDynamicsWorld);
  3255. this._btDispatchInfo = bt.btCollisionWorld_getDispatchInfo(this._btDiscreteDynamicsWorld);
  3256. }
  3257. this._btClosestRayResultCallback = bt.ClosestRayResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  3258. this._btAllHitsRayResultCallback = bt.AllHitsRayResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  3259. this._btClosestConvexResultCallback = bt.ClosestConvexResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  3260. this._btAllConvexResultCallback = bt.AllConvexResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  3261. bt.btGImpactCollisionAlgorithm_RegisterAlgorithm(this._btDispatcher);
  3262. }
  3263. static __init__() {
  3264. var bt = ILaya3D.Physics3D._bullet;
  3265. PhysicsSimulation._btTempVector30 = bt.btVector3_create(0, 0, 0);
  3266. PhysicsSimulation._btTempVector31 = bt.btVector3_create(0, 0, 0);
  3267. PhysicsSimulation._btTempQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  3268. PhysicsSimulation._btTempQuaternion1 = bt.btQuaternion_create(0, 0, 0, 1);
  3269. PhysicsSimulation._btTempTransform0 = bt.btTransform_create();
  3270. PhysicsSimulation._btTempTransform1 = bt.btTransform_create();
  3271. }
  3272. static createConstraint() {
  3273. }
  3274. get continuousCollisionDetection() {
  3275. return ILaya3D.Physics3D._bullet.btCollisionWorld_get_m_useContinuous(this._btDispatchInfo);
  3276. }
  3277. set continuousCollisionDetection(value) {
  3278. ILaya3D.Physics3D._bullet.btCollisionWorld_set_m_useContinuous(this._btDispatchInfo, value);
  3279. }
  3280. get gravity() {
  3281. if (!this._btDiscreteDynamicsWorld)
  3282. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3283. return this._gravity;
  3284. }
  3285. set gravity(value) {
  3286. if (!this._btDiscreteDynamicsWorld)
  3287. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3288. this._gravity = value;
  3289. var bt = ILaya3D.Physics3D._bullet;
  3290. var btGravity = PhysicsSimulation._btTempVector30;
  3291. bt.btVector3_setValue(btGravity, -value.x, value.y, value.z);
  3292. bt.btDiscreteDynamicsWorld_setGravity(this._btDiscreteDynamicsWorld, btGravity);
  3293. }
  3294. get speculativeContactRestitution() {
  3295. if (!this._btDiscreteDynamicsWorld)
  3296. throw "Simulation:Cannot Cannot perform this action when the physics engine is set to CollisionsOnly";
  3297. return ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_getApplySpeculativeContactRestitution(this._btDiscreteDynamicsWorld);
  3298. }
  3299. set speculativeContactRestitution(value) {
  3300. if (!this._btDiscreteDynamicsWorld)
  3301. throw "Simulation:Cannot Cannot perform this action when the physics engine is set to CollisionsOnly";
  3302. ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_setApplySpeculativeContactRestitution(this._btDiscreteDynamicsWorld, value);
  3303. }
  3304. _simulate(deltaTime) {
  3305. this._updatedRigidbodies = 0;
  3306. var bt = ILaya3D.Physics3D._bullet;
  3307. if (this._btDiscreteDynamicsWorld)
  3308. bt.btDiscreteDynamicsWorld_stepSimulation(this._btDiscreteDynamicsWorld, deltaTime, this.maxSubSteps, this.fixedTimeStep);
  3309. else
  3310. bt.PerformDiscreteCollisionDetection(this._btCollisionWorld);
  3311. }
  3312. _destroy() {
  3313. var bt = ILaya3D.Physics3D._bullet;
  3314. if (this._btDiscreteDynamicsWorld) {
  3315. bt.btCollisionWorld_destroy(this._btDiscreteDynamicsWorld);
  3316. this._btDiscreteDynamicsWorld = null;
  3317. }
  3318. else {
  3319. bt.btCollisionWorld_destroy(this._btCollisionWorld);
  3320. this._btCollisionWorld = null;
  3321. }
  3322. bt.btDbvtBroadphase_destroy(this._btBroadphase);
  3323. this._btBroadphase = null;
  3324. bt.btCollisionDispatcher_destroy(this._btDispatcher);
  3325. this._btDispatcher = null;
  3326. bt.btDefaultCollisionConfiguration_destroy(this._btCollisionConfiguration);
  3327. this._btCollisionConfiguration = null;
  3328. }
  3329. _addPhysicsCollider(component, group, mask) {
  3330. ILaya3D.Physics3D._bullet.btCollisionWorld_addCollisionObject(this._btCollisionWorld, component._btColliderObject, group, mask);
  3331. }
  3332. _removePhysicsCollider(component) {
  3333. ILaya3D.Physics3D._bullet.btCollisionWorld_removeCollisionObject(this._btCollisionWorld, component._btColliderObject);
  3334. }
  3335. _addRigidBody(rigidBody, group, mask) {
  3336. if (!this._btDiscreteDynamicsWorld)
  3337. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3338. ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_addRigidBody(this._btCollisionWorld, rigidBody._btColliderObject, group, mask);
  3339. }
  3340. _removeRigidBody(rigidBody) {
  3341. if (!this._btDiscreteDynamicsWorld)
  3342. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3343. ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_removeRigidBody(this._btCollisionWorld, rigidBody._btColliderObject);
  3344. }
  3345. _addCharacter(character, group, mask) {
  3346. if (!this._btDiscreteDynamicsWorld)
  3347. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3348. var bt = ILaya3D.Physics3D._bullet;
  3349. bt.btCollisionWorld_addCollisionObject(this._btCollisionWorld, character._btColliderObject, group, mask);
  3350. bt.btDynamicsWorld_addAction(this._btCollisionWorld, character._btKinematicCharacter);
  3351. }
  3352. _removeCharacter(character) {
  3353. if (!this._btDiscreteDynamicsWorld)
  3354. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3355. var bt = ILaya3D.Physics3D._bullet;
  3356. bt.btCollisionWorld_removeCollisionObject(this._btCollisionWorld, character._btColliderObject);
  3357. bt.btDynamicsWorld_removeAction(this._btCollisionWorld, character._btKinematicCharacter);
  3358. }
  3359. raycastFromTo(from, to, out = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  3360. var bt = ILaya3D.Physics3D._bullet;
  3361. var rayResultCall = this._btClosestRayResultCallback;
  3362. var rayFrom = PhysicsSimulation._btTempVector30;
  3363. var rayTo = PhysicsSimulation._btTempVector31;
  3364. bt.btVector3_setValue(rayFrom, -from.x, from.y, from.z);
  3365. bt.btVector3_setValue(rayTo, -to.x, to.y, to.z);
  3366. bt.ClosestRayResultCallback_set_m_rayFromWorld(rayResultCall, rayFrom);
  3367. bt.ClosestRayResultCallback_set_m_rayToWorld(rayResultCall, rayTo);
  3368. bt.RayResultCallback_set_m_collisionFilterGroup(rayResultCall, collisonGroup);
  3369. bt.RayResultCallback_set_m_collisionFilterMask(rayResultCall, collisionMask);
  3370. bt.RayResultCallback_set_m_collisionObject(rayResultCall, null);
  3371. bt.RayResultCallback_set_m_closestHitFraction(rayResultCall, 1);
  3372. bt.btCollisionWorld_rayTest(this._btCollisionWorld, rayFrom, rayTo, rayResultCall);
  3373. if (bt.RayResultCallback_hasHit(rayResultCall)) {
  3374. if (out) {
  3375. out.succeeded = true;
  3376. out.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.RayResultCallback_get_m_collisionObject(rayResultCall))];
  3377. out.hitFraction = bt.RayResultCallback_get_m_closestHitFraction(rayResultCall);
  3378. var btPoint = bt.ClosestRayResultCallback_get_m_hitPointWorld(rayResultCall);
  3379. var point = out.point;
  3380. point.x = -bt.btVector3_x(btPoint);
  3381. point.y = bt.btVector3_y(btPoint);
  3382. point.z = bt.btVector3_z(btPoint);
  3383. var btNormal = bt.ClosestRayResultCallback_get_m_hitNormalWorld(rayResultCall);
  3384. var normal = out.normal;
  3385. normal.x = -bt.btVector3_x(btNormal);
  3386. normal.y = bt.btVector3_y(btNormal);
  3387. normal.z = bt.btVector3_z(btNormal);
  3388. }
  3389. return true;
  3390. }
  3391. else {
  3392. if (out)
  3393. out.succeeded = false;
  3394. return false;
  3395. }
  3396. }
  3397. raycastAllFromTo(from, to, out, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  3398. var bt = ILaya3D.Physics3D._bullet;
  3399. var rayResultCall = this._btAllHitsRayResultCallback;
  3400. var rayFrom = PhysicsSimulation._btTempVector30;
  3401. var rayTo = PhysicsSimulation._btTempVector31;
  3402. out.length = 0;
  3403. bt.btVector3_setValue(rayFrom, -from.x, from.y, from.z);
  3404. bt.btVector3_setValue(rayTo, -to.x, to.y, to.z);
  3405. bt.AllHitsRayResultCallback_set_m_rayFromWorld(rayResultCall, rayFrom);
  3406. bt.AllHitsRayResultCallback_set_m_rayToWorld(rayResultCall, rayTo);
  3407. bt.RayResultCallback_set_m_collisionFilterGroup(rayResultCall, collisonGroup);
  3408. bt.RayResultCallback_set_m_collisionFilterMask(rayResultCall, collisionMask);
  3409. var collisionObjects = bt.AllHitsRayResultCallback_get_m_collisionObjects(rayResultCall);
  3410. var btPoints = bt.AllHitsRayResultCallback_get_m_hitPointWorld(rayResultCall);
  3411. var btNormals = bt.AllHitsRayResultCallback_get_m_hitNormalWorld(rayResultCall);
  3412. var btFractions = bt.AllHitsRayResultCallback_get_m_hitFractions(rayResultCall);
  3413. bt.tBtCollisionObjectArray_clear(collisionObjects);
  3414. bt.tVector3Array_clear(btPoints);
  3415. bt.tVector3Array_clear(btNormals);
  3416. bt.tScalarArray_clear(btFractions);
  3417. bt.btCollisionWorld_rayTest(this._btCollisionWorld, rayFrom, rayTo, rayResultCall);
  3418. var count = bt.tBtCollisionObjectArray_size(collisionObjects);
  3419. if (count > 0) {
  3420. this._collisionsUtils.recoverAllHitResultsPool();
  3421. for (var i = 0; i < count; i++) {
  3422. var hitResult = this._collisionsUtils.getHitResult();
  3423. out.push(hitResult);
  3424. hitResult.succeeded = true;
  3425. hitResult.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.tBtCollisionObjectArray_at(collisionObjects, i))];
  3426. hitResult.hitFraction = bt.tScalarArray_at(btFractions, i);
  3427. var btPoint = bt.tVector3Array_at(btPoints, i);
  3428. var pointE = hitResult.point;
  3429. pointE.x = -bt.btVector3_x(btPoint);
  3430. pointE.y = bt.btVector3_y(btPoint);
  3431. pointE.z = bt.btVector3_z(btPoint);
  3432. var btNormal = bt.tVector3Array_at(btNormals, i);
  3433. var normal = hitResult.normal;
  3434. normal.x = -bt.btVector3_x(btNormal);
  3435. normal.y = bt.btVector3_y(btNormal);
  3436. normal.z = bt.btVector3_z(btNormal);
  3437. }
  3438. return true;
  3439. }
  3440. else {
  3441. return false;
  3442. }
  3443. }
  3444. rayCast(ray, outHitResult = null, distance = 2147483647, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  3445. var from = ray.origin;
  3446. var to = PhysicsSimulation._tempVector30;
  3447. Vector3.normalize(ray.direction, to);
  3448. Vector3.scale(to, distance, to);
  3449. Vector3.add(from, to, to);
  3450. return this.raycastFromTo(from, to, outHitResult, collisonGroup, collisionMask);
  3451. }
  3452. rayCastAll(ray, out, distance = 2147483647, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  3453. var from = ray.origin;
  3454. var to = PhysicsSimulation._tempVector30;
  3455. Vector3.normalize(ray.direction, to);
  3456. Vector3.scale(to, distance, to);
  3457. Vector3.add(from, to, to);
  3458. return this.raycastAllFromTo(from, to, out, collisonGroup, collisionMask);
  3459. }
  3460. shapeCast(shape, fromPosition, toPosition, out = null, fromRotation = null, toRotation = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, allowedCcdPenetration = 0.0) {
  3461. var bt = ILaya3D.Physics3D._bullet;
  3462. var convexResultCall = this._btClosestConvexResultCallback;
  3463. var convexPosFrom = PhysicsSimulation._btTempVector30;
  3464. var convexPosTo = PhysicsSimulation._btTempVector31;
  3465. var convexRotFrom = PhysicsSimulation._btTempQuaternion0;
  3466. var convexRotTo = PhysicsSimulation._btTempQuaternion1;
  3467. var convexTransform = PhysicsSimulation._btTempTransform0;
  3468. var convexTransTo = PhysicsSimulation._btTempTransform1;
  3469. var sweepShape = shape._btShape;
  3470. bt.btVector3_setValue(convexPosFrom, -fromPosition.x, fromPosition.y, fromPosition.z);
  3471. bt.btVector3_setValue(convexPosTo, -toPosition.x, toPosition.y, toPosition.z);
  3472. bt.ConvexResultCallback_set_m_collisionFilterGroup(convexResultCall, collisonGroup);
  3473. bt.ConvexResultCallback_set_m_collisionFilterMask(convexResultCall, collisionMask);
  3474. bt.btTransform_setOrigin(convexTransform, convexPosFrom);
  3475. bt.btTransform_setOrigin(convexTransTo, convexPosTo);
  3476. if (fromRotation) {
  3477. bt.btQuaternion_setValue(convexRotFrom, -fromRotation.x, fromRotation.y, fromRotation.z, -fromRotation.w);
  3478. bt.btTransform_setRotation(convexTransform, convexRotFrom);
  3479. }
  3480. else {
  3481. bt.btTransform_setRotation(convexTransform, this._btDefaultQuaternion);
  3482. }
  3483. if (toRotation) {
  3484. bt.btQuaternion_setValue(convexRotTo, -toRotation.x, toRotation.y, toRotation.z, -toRotation.w);
  3485. bt.btTransform_setRotation(convexTransTo, convexRotTo);
  3486. }
  3487. else {
  3488. bt.btTransform_setRotation(convexTransTo, this._btDefaultQuaternion);
  3489. }
  3490. bt.ClosestConvexResultCallback_set_m_hitCollisionObject(convexResultCall, null);
  3491. bt.ConvexResultCallback_set_m_closestHitFraction(convexResultCall, 1);
  3492. bt.btCollisionWorld_convexSweepTest(this._btCollisionWorld, sweepShape, convexTransform, convexTransTo, convexResultCall, allowedCcdPenetration);
  3493. if (bt.ConvexResultCallback_hasHit(convexResultCall)) {
  3494. if (out) {
  3495. out.succeeded = true;
  3496. out.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.ClosestConvexResultCallback_get_m_hitCollisionObject(convexResultCall))];
  3497. out.hitFraction = bt.ConvexResultCallback_get_m_closestHitFraction(convexResultCall);
  3498. var btPoint = bt.ClosestConvexResultCallback_get_m_hitPointWorld(convexResultCall);
  3499. var btNormal = bt.ClosestConvexResultCallback_get_m_hitNormalWorld(convexResultCall);
  3500. var point = out.point;
  3501. var normal = out.normal;
  3502. point.x = -bt.btVector3_x(btPoint);
  3503. point.y = bt.btVector3_y(btPoint);
  3504. point.z = bt.btVector3_z(btPoint);
  3505. normal.x = -bt.btVector3_x(btNormal);
  3506. normal.y = bt.btVector3_y(btNormal);
  3507. normal.z = bt.btVector3_z(btNormal);
  3508. }
  3509. return true;
  3510. }
  3511. else {
  3512. if (out)
  3513. out.succeeded = false;
  3514. return false;
  3515. }
  3516. }
  3517. shapeCastAll(shape, fromPosition, toPosition, out, fromRotation = null, toRotation = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, allowedCcdPenetration = 0.0) {
  3518. var bt = ILaya3D.Physics3D._bullet;
  3519. var convexResultCall = this._btAllConvexResultCallback;
  3520. var convexPosFrom = PhysicsSimulation._btTempVector30;
  3521. var convexPosTo = PhysicsSimulation._btTempVector31;
  3522. var convexRotFrom = PhysicsSimulation._btTempQuaternion0;
  3523. var convexRotTo = PhysicsSimulation._btTempQuaternion1;
  3524. var convexTransform = PhysicsSimulation._btTempTransform0;
  3525. var convexTransTo = PhysicsSimulation._btTempTransform1;
  3526. var sweepShape = shape._btShape;
  3527. out.length = 0;
  3528. bt.btVector3_setValue(convexPosFrom, -fromPosition.x, fromPosition.y, fromPosition.z);
  3529. bt.btVector3_setValue(convexPosTo, -toPosition.x, toPosition.y, toPosition.z);
  3530. bt.ConvexResultCallback_set_m_collisionFilterGroup(convexResultCall, collisonGroup);
  3531. bt.ConvexResultCallback_set_m_collisionFilterMask(convexResultCall, collisionMask);
  3532. bt.btTransform_setOrigin(convexTransform, convexPosFrom);
  3533. bt.btTransform_setOrigin(convexTransTo, convexPosTo);
  3534. if (fromRotation) {
  3535. bt.btQuaternion_setValue(convexRotFrom, -fromRotation.x, fromRotation.y, fromRotation.z, -fromRotation.w);
  3536. bt.btTransform_setRotation(convexTransform, convexRotFrom);
  3537. }
  3538. else {
  3539. bt.btTransform_setRotation(convexTransform, this._btDefaultQuaternion);
  3540. }
  3541. if (toRotation) {
  3542. bt.btQuaternion_setValue(convexRotTo, -toRotation.x, toRotation.y, toRotation.z, -toRotation.w);
  3543. bt.btTransform_setRotation(convexTransTo, convexRotTo);
  3544. }
  3545. else {
  3546. bt.btTransform_setRotation(convexTransTo, this._btDefaultQuaternion);
  3547. }
  3548. var collisionObjects = bt.AllConvexResultCallback_get_m_collisionObjects(convexResultCall);
  3549. bt.tBtCollisionObjectArray_clear(collisionObjects);
  3550. bt.btCollisionWorld_convexSweepTest(this._btCollisionWorld, sweepShape, convexTransform, convexTransTo, convexResultCall, allowedCcdPenetration);
  3551. var count = bt.tBtCollisionObjectArray_size(collisionObjects);
  3552. if (count > 0) {
  3553. this._collisionsUtils.recoverAllHitResultsPool();
  3554. var btPoints = bt.AllConvexResultCallback_get_m_hitPointWorld(convexResultCall);
  3555. var btNormals = bt.AllConvexResultCallback_get_m_hitNormalWorld(convexResultCall);
  3556. var btFractions = bt.AllConvexResultCallback_get_m_hitFractions(convexResultCall);
  3557. for (var i = 0; i < count; i++) {
  3558. var hitResult = this._collisionsUtils.getHitResult();
  3559. out.push(hitResult);
  3560. hitResult.succeeded = true;
  3561. hitResult.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.tBtCollisionObjectArray_at(collisionObjects, i))];
  3562. hitResult.hitFraction = bt.tScalarArray_at(btFractions, i);
  3563. var btPoint = bt.tVector3Array_at(btPoints, i);
  3564. var point = hitResult.point;
  3565. point.x = -bt.btVector3_x(btPoint);
  3566. point.y = bt.btVector3_y(btPoint);
  3567. point.z = bt.btVector3_z(btPoint);
  3568. var btNormal = bt.tVector3Array_at(btNormals, i);
  3569. var normal = hitResult.normal;
  3570. normal.x = -bt.btVector3_x(btNormal);
  3571. normal.y = bt.btVector3_y(btNormal);
  3572. normal.z = bt.btVector3_z(btNormal);
  3573. }
  3574. return true;
  3575. }
  3576. else {
  3577. return false;
  3578. }
  3579. }
  3580. addConstraint(constraint, disableCollisionsBetweenLinkedBodies = false) {
  3581. if (!this._btDiscreteDynamicsWorld)
  3582. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  3583. ILaya3D.Physics3D._bullet.btCollisionWorld_addConstraint(this._btDiscreteDynamicsWorld, constraint._btConstraint, disableCollisionsBetweenLinkedBodies);
  3584. this._currentConstraint[constraint.id] = constraint;
  3585. }
  3586. removeConstraint(constraint) {
  3587. if (!this._btDiscreteDynamicsWorld)
  3588. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  3589. ILaya3D.Physics3D._bullet.btCollisionWorld_removeConstraint(this._btDiscreteDynamicsWorld, constraint._btConstraint);
  3590. delete this._currentConstraint[constraint.id];
  3591. }
  3592. _updatePhysicsTransformFromRender() {
  3593. var elements = this._physicsUpdateList.elements;
  3594. for (var i = 0, n = this._physicsUpdateList.length; i < n; i++) {
  3595. var physicCollider = elements[i];
  3596. physicCollider._derivePhysicsTransformation(false);
  3597. physicCollider._inPhysicUpdateListIndex = -1;
  3598. }
  3599. this._physicsUpdateList.length = 0;
  3600. }
  3601. _updateCharacters() {
  3602. for (var i = 0, n = this._characters.length; i < n; i++) {
  3603. var character = this._characters[i];
  3604. character._updateTransformComponent(ILaya3D.Physics3D._bullet.btCollisionObject_getWorldTransform(character._btColliderObject));
  3605. }
  3606. }
  3607. _updateCollisions() {
  3608. this._collisionsUtils.recoverAllContactPointsPool();
  3609. var previous = this._currentFrameCollisions;
  3610. this._currentFrameCollisions = this._previousFrameCollisions;
  3611. this._currentFrameCollisions.length = 0;
  3612. this._previousFrameCollisions = previous;
  3613. var loopCount = Laya.Stat.loopCount;
  3614. var bt = ILaya3D.Physics3D._bullet;
  3615. var numManifolds = bt.btDispatcher_getNumManifolds(this._btDispatcher);
  3616. for (var i = 0; i < numManifolds; i++) {
  3617. var contactManifold = bt.btDispatcher_getManifoldByIndexInternal(this._btDispatcher, i);
  3618. var componentA = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.btPersistentManifold_getBody0(contactManifold))];
  3619. var componentB = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.btPersistentManifold_getBody1(contactManifold))];
  3620. var collision = null;
  3621. var isFirstCollision;
  3622. var contacts = null;
  3623. var isTrigger = componentA.isTrigger || componentB.isTrigger;
  3624. if (isTrigger && (componentA.owner._needProcessTriggers || componentB.owner._needProcessTriggers)) {
  3625. var numContacts = bt.btPersistentManifold_getNumContacts(contactManifold);
  3626. for (var j = 0; j < numContacts; j++) {
  3627. var pt = bt.btPersistentManifold_getContactPoint(contactManifold, j);
  3628. var distance = bt.btManifoldPoint_getDistance(pt);
  3629. if (distance <= 0) {
  3630. collision = this._collisionsUtils.getCollision(componentA, componentB);
  3631. contacts = collision.contacts;
  3632. isFirstCollision = collision._updateFrame !== loopCount;
  3633. if (isFirstCollision) {
  3634. collision._isTrigger = true;
  3635. contacts.length = 0;
  3636. }
  3637. break;
  3638. }
  3639. }
  3640. }
  3641. else if (componentA.owner._needProcessCollisions || componentB.owner._needProcessCollisions) {
  3642. if (componentA._enableProcessCollisions || componentB._enableProcessCollisions) {
  3643. numContacts = bt.btPersistentManifold_getNumContacts(contactManifold);
  3644. for (j = 0; j < numContacts; j++) {
  3645. pt = bt.btPersistentManifold_getContactPoint(contactManifold, j);
  3646. distance = bt.btManifoldPoint_getDistance(pt);
  3647. if (distance <= 0) {
  3648. var contactPoint = this._collisionsUtils.getContactPoints();
  3649. contactPoint.colliderA = componentA;
  3650. contactPoint.colliderB = componentB;
  3651. contactPoint.distance = distance;
  3652. var btNormal = bt.btManifoldPoint_get_m_normalWorldOnB(pt);
  3653. var normal = contactPoint.normal;
  3654. normal.x = -bt.btVector3_x(btNormal);
  3655. normal.y = bt.btVector3_y(btNormal);
  3656. normal.z = bt.btVector3_z(btNormal);
  3657. var btPostionA = bt.btManifoldPoint_get_m_positionWorldOnA(pt);
  3658. var positionOnA = contactPoint.positionOnA;
  3659. positionOnA.x = -bt.btVector3_x(btPostionA);
  3660. positionOnA.y = bt.btVector3_y(btPostionA);
  3661. positionOnA.z = bt.btVector3_z(btPostionA);
  3662. var btPostionB = bt.btManifoldPoint_get_m_positionWorldOnB(pt);
  3663. var positionOnB = contactPoint.positionOnB;
  3664. positionOnB.x = -bt.btVector3_x(btPostionB);
  3665. positionOnB.y = bt.btVector3_y(btPostionB);
  3666. positionOnB.z = bt.btVector3_z(btPostionB);
  3667. if (!collision) {
  3668. collision = this._collisionsUtils.getCollision(componentA, componentB);
  3669. contacts = collision.contacts;
  3670. isFirstCollision = collision._updateFrame !== loopCount;
  3671. if (isFirstCollision) {
  3672. collision._isTrigger = false;
  3673. contacts.length = 0;
  3674. }
  3675. }
  3676. contacts.push(contactPoint);
  3677. }
  3678. }
  3679. }
  3680. }
  3681. if (collision && isFirstCollision) {
  3682. this._currentFrameCollisions.push(collision);
  3683. collision._setUpdateFrame(loopCount);
  3684. }
  3685. }
  3686. }
  3687. _eventScripts() {
  3688. var loopCount = Laya.Stat.loopCount;
  3689. for (var i = 0, n = this._currentFrameCollisions.length; i < n; i++) {
  3690. var curFrameCol = this._currentFrameCollisions[i];
  3691. var colliderA = curFrameCol._colliderA;
  3692. var colliderB = curFrameCol._colliderB;
  3693. if (colliderA.destroyed || colliderB.destroyed)
  3694. continue;
  3695. if (loopCount - curFrameCol._lastUpdateFrame === 1) {
  3696. var ownerA = colliderA.owner;
  3697. var scriptsA = ownerA._scripts;
  3698. if (scriptsA) {
  3699. if (curFrameCol._isTrigger) {
  3700. if (ownerA._needProcessTriggers) {
  3701. for (var j = 0, m = scriptsA.length; j < m; j++)
  3702. scriptsA[j].onTriggerStay(colliderB);
  3703. }
  3704. }
  3705. else {
  3706. if (ownerA._needProcessCollisions) {
  3707. for (j = 0, m = scriptsA.length; j < m; j++) {
  3708. curFrameCol.other = colliderB;
  3709. scriptsA[j].onCollisionStay(curFrameCol);
  3710. }
  3711. }
  3712. }
  3713. }
  3714. var ownerB = colliderB.owner;
  3715. var scriptsB = ownerB._scripts;
  3716. if (scriptsB) {
  3717. if (curFrameCol._isTrigger) {
  3718. if (ownerB._needProcessTriggers) {
  3719. for (j = 0, m = scriptsB.length; j < m; j++)
  3720. scriptsB[j].onTriggerStay(colliderA);
  3721. }
  3722. }
  3723. else {
  3724. if (ownerB._needProcessCollisions) {
  3725. for (j = 0, m = scriptsB.length; j < m; j++) {
  3726. curFrameCol.other = colliderA;
  3727. scriptsB[j].onCollisionStay(curFrameCol);
  3728. }
  3729. }
  3730. }
  3731. }
  3732. }
  3733. else {
  3734. ownerA = colliderA.owner;
  3735. scriptsA = ownerA._scripts;
  3736. if (scriptsA) {
  3737. if (curFrameCol._isTrigger) {
  3738. if (ownerA._needProcessTriggers) {
  3739. for (j = 0, m = scriptsA.length; j < m; j++)
  3740. scriptsA[j].onTriggerEnter(colliderB);
  3741. }
  3742. }
  3743. else {
  3744. if (ownerA._needProcessCollisions) {
  3745. for (j = 0, m = scriptsA.length; j < m; j++) {
  3746. curFrameCol.other = colliderB;
  3747. scriptsA[j].onCollisionEnter(curFrameCol);
  3748. }
  3749. }
  3750. }
  3751. }
  3752. ownerB = colliderB.owner;
  3753. scriptsB = ownerB._scripts;
  3754. if (scriptsB) {
  3755. if (curFrameCol._isTrigger) {
  3756. if (ownerB._needProcessTriggers) {
  3757. for (j = 0, m = scriptsB.length; j < m; j++)
  3758. scriptsB[j].onTriggerEnter(colliderA);
  3759. }
  3760. }
  3761. else {
  3762. if (ownerB._needProcessCollisions) {
  3763. for (j = 0, m = scriptsB.length; j < m; j++) {
  3764. curFrameCol.other = colliderA;
  3765. scriptsB[j].onCollisionEnter(curFrameCol);
  3766. }
  3767. }
  3768. }
  3769. }
  3770. }
  3771. }
  3772. for (i = 0, n = this._previousFrameCollisions.length; i < n; i++) {
  3773. var preFrameCol = this._previousFrameCollisions[i];
  3774. var preColliderA = preFrameCol._colliderA;
  3775. var preColliderB = preFrameCol._colliderB;
  3776. if (preColliderA.destroyed || preColliderB.destroyed)
  3777. continue;
  3778. if (loopCount - preFrameCol._updateFrame === 1) {
  3779. this._collisionsUtils.recoverCollision(preFrameCol);
  3780. ownerA = preColliderA.owner;
  3781. scriptsA = ownerA._scripts;
  3782. if (scriptsA) {
  3783. if (preFrameCol._isTrigger) {
  3784. if (ownerA._needProcessTriggers) {
  3785. for (j = 0, m = scriptsA.length; j < m; j++)
  3786. scriptsA[j].onTriggerExit(preColliderB);
  3787. }
  3788. }
  3789. else {
  3790. if (ownerA._needProcessCollisions) {
  3791. for (j = 0, m = scriptsA.length; j < m; j++) {
  3792. preFrameCol.other = preColliderB;
  3793. scriptsA[j].onCollisionExit(preFrameCol);
  3794. }
  3795. }
  3796. }
  3797. }
  3798. ownerB = preColliderB.owner;
  3799. scriptsB = ownerB._scripts;
  3800. if (scriptsB) {
  3801. if (preFrameCol._isTrigger) {
  3802. if (ownerB._needProcessTriggers) {
  3803. for (j = 0, m = scriptsB.length; j < m; j++)
  3804. scriptsB[j].onTriggerExit(preColliderA);
  3805. }
  3806. }
  3807. else {
  3808. if (ownerB._needProcessCollisions) {
  3809. for (j = 0, m = scriptsB.length; j < m; j++) {
  3810. preFrameCol.other = preColliderA;
  3811. scriptsB[j].onCollisionExit(preFrameCol);
  3812. }
  3813. }
  3814. }
  3815. }
  3816. }
  3817. }
  3818. for (var id in this._currentConstraint) {
  3819. var constraintObj = this._currentConstraint[id];
  3820. var scripts = constraintObj.owner._scripts;
  3821. if (constraintObj.enabled && constraintObj._isBreakConstrained() && (!!scripts)) {
  3822. if (scripts.length != 0) {
  3823. for (i = 0, n = scripts.length; i < n; i++) {
  3824. scripts[i].onJointBreak();
  3825. }
  3826. }
  3827. }
  3828. }
  3829. }
  3830. clearForces() {
  3831. if (!this._btDiscreteDynamicsWorld)
  3832. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  3833. ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_clearForces(this._btDiscreteDynamicsWorld);
  3834. }
  3835. }
  3836. PhysicsSimulation.PHYSICSENGINEFLAGS_NONE = 0x0;
  3837. PhysicsSimulation.PHYSICSENGINEFLAGS_COLLISIONSONLY = 0x1;
  3838. PhysicsSimulation.PHYSICSENGINEFLAGS_SOFTBODYSUPPORT = 0x2;
  3839. PhysicsSimulation.PHYSICSENGINEFLAGS_MULTITHREADED = 0x4;
  3840. PhysicsSimulation.PHYSICSENGINEFLAGS_USEHARDWAREWHENPOSSIBLE = 0x8;
  3841. PhysicsSimulation.SOLVERMODE_RANDMIZE_ORDER = 1;
  3842. PhysicsSimulation.SOLVERMODE_FRICTION_SEPARATE = 2;
  3843. PhysicsSimulation.SOLVERMODE_USE_WARMSTARTING = 4;
  3844. PhysicsSimulation.SOLVERMODE_USE_2_FRICTION_DIRECTIONS = 16;
  3845. PhysicsSimulation.SOLVERMODE_ENABLE_FRICTION_DIRECTION_CACHING = 32;
  3846. PhysicsSimulation.SOLVERMODE_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION = 64;
  3847. PhysicsSimulation.SOLVERMODE_CACHE_FRIENDLY = 128;
  3848. PhysicsSimulation.SOLVERMODE_SIMD = 256;
  3849. PhysicsSimulation.SOLVERMODE_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS = 512;
  3850. PhysicsSimulation.SOLVERMODE_ALLOW_ZERO_LENGTH_FRICTION_DIRECTIONS = 1024;
  3851. PhysicsSimulation._tempVector30 = new Vector3();
  3852. PhysicsSimulation.disableSimulation = false;
  3853. class TextureGenerator {
  3854. constructor() {
  3855. }
  3856. static lightAttenTexture(x, y, maxX, maxY, index, data) {
  3857. var sqrRange = x / maxX;
  3858. var atten = 1.0 / (1.0 + 25.0 * sqrRange);
  3859. if (sqrRange >= 0.64) {
  3860. if (sqrRange > 1.0) {
  3861. atten = 0;
  3862. }
  3863. else {
  3864. atten *= 1 - (sqrRange - 0.64) / (1 - 0.64);
  3865. }
  3866. }
  3867. data[index] = Math.floor(atten * 255.0 + 0.5);
  3868. }
  3869. static haloTexture(x, y, maxX, maxY, index, data) {
  3870. maxX >>= 1;
  3871. maxY >>= 1;
  3872. var xFac = (x - maxX) / maxX;
  3873. var yFac = (y - maxY) / maxY;
  3874. var sqrRange = xFac * xFac + yFac * yFac;
  3875. if (sqrRange > 1.0) {
  3876. sqrRange = 1.0;
  3877. }
  3878. data[index] = Math.floor((1.0 - sqrRange) * 255.0 + 0.5);
  3879. }
  3880. static _generateTexture2D(texture, textureWidth, textureHeight, func) {
  3881. var index = 0;
  3882. var size = 0;
  3883. switch (texture.format) {
  3884. case Laya.TextureFormat.R8G8B8:
  3885. size = 3;
  3886. break;
  3887. case Laya.TextureFormat.R8G8B8A8:
  3888. size = 4;
  3889. break;
  3890. case Laya.TextureFormat.Alpha8:
  3891. size = 1;
  3892. break;
  3893. default:
  3894. throw "GeneratedTexture._generateTexture: unkonw texture format.";
  3895. }
  3896. var data = new Uint8Array(textureWidth * textureHeight * size);
  3897. for (var y = 0; y < textureHeight; y++) {
  3898. for (var x = 0; x < textureWidth; x++) {
  3899. func(x, y, textureWidth, textureHeight, index, data);
  3900. index += size;
  3901. }
  3902. }
  3903. texture.setPixels(data);
  3904. }
  3905. }
  3906. class Utils3D {
  3907. static _createFloatTextureBuffer(width, height) {
  3908. var floatTex = new Laya.Texture2D(width, height, Laya.TextureFormat.R32G32B32A32, false, false);
  3909. floatTex.filterMode = Laya.FilterMode.Point;
  3910. floatTex.wrapModeU = Laya.WarpMode.Clamp;
  3911. floatTex.wrapModeV = Laya.WarpMode.Clamp;
  3912. floatTex.anisoLevel = 0;
  3913. return floatTex;
  3914. }
  3915. static _convertToLayaVec3(bVector, out, inverseX) {
  3916. var bullet = ILaya3D.Physics3D._bullet;
  3917. out.x = inverseX ? -bullet.btVector3_x(bVector) : bullet.btVector3_x(bVector);
  3918. out.y = bullet.btVector3_y(bVector);
  3919. out.z = bullet.btVector3_z(bVector);
  3920. }
  3921. static _convertToBulletVec3(lVector, out, inverseX) {
  3922. ILaya3D.Physics3D._bullet.btVector3_setValue(out, inverseX ? -lVector.x : lVector.x, lVector.y, lVector.z);
  3923. }
  3924. static _rotationTransformScaleSkinAnimation(tx, ty, tz, qx, qy, qz, qw, sx, sy, sz, outArray, outOffset) {
  3925. var re = Utils3D._tempArray16_0;
  3926. var se = Utils3D._tempArray16_1;
  3927. var tse = Utils3D._tempArray16_2;
  3928. var x2 = qx + qx;
  3929. var y2 = qy + qy;
  3930. var z2 = qz + qz;
  3931. var xx = qx * x2;
  3932. var yx = qy * x2;
  3933. var yy = qy * y2;
  3934. var zx = qz * x2;
  3935. var zy = qz * y2;
  3936. var zz = qz * z2;
  3937. var wx = qw * x2;
  3938. var wy = qw * y2;
  3939. var wz = qw * z2;
  3940. re[15] = 1;
  3941. re[0] = 1 - yy - zz;
  3942. re[1] = yx + wz;
  3943. re[2] = zx - wy;
  3944. re[4] = yx - wz;
  3945. re[5] = 1 - xx - zz;
  3946. re[6] = zy + wx;
  3947. re[8] = zx + wy;
  3948. re[9] = zy - wx;
  3949. re[10] = 1 - xx - yy;
  3950. se[15] = 1;
  3951. se[0] = sx;
  3952. se[5] = sy;
  3953. se[10] = sz;
  3954. var i, ai0, ai1, ai2, ai3;
  3955. for (i = 0; i < 4; i++) {
  3956. ai0 = re[i];
  3957. ai1 = re[i + 4];
  3958. ai2 = re[i + 8];
  3959. ai3 = re[i + 12];
  3960. tse[i] = ai0;
  3961. tse[i + 4] = ai1;
  3962. tse[i + 8] = ai2;
  3963. tse[i + 12] = ai0 * tx + ai1 * ty + ai2 * tz + ai3;
  3964. }
  3965. for (i = 0; i < 4; i++) {
  3966. ai0 = tse[i];
  3967. ai1 = tse[i + 4];
  3968. ai2 = tse[i + 8];
  3969. ai3 = tse[i + 12];
  3970. outArray[i + outOffset] = ai0 * se[0] + ai1 * se[1] + ai2 * se[2] + ai3 * se[3];
  3971. outArray[i + outOffset + 4] = ai0 * se[4] + ai1 * se[5] + ai2 * se[6] + ai3 * se[7];
  3972. outArray[i + outOffset + 8] = ai0 * se[8] + ai1 * se[9] + ai2 * se[10] + ai3 * se[11];
  3973. outArray[i + outOffset + 12] = ai0 * se[12] + ai1 * se[13] + ai2 * se[14] + ai3 * se[15];
  3974. }
  3975. }
  3976. static _computeBoneAndAnimationDatasByBindPoseMatrxix(bones, curData, inverGlobalBindPose, outBonesDatas, outAnimationDatas, boneIndexToMesh) {
  3977. var offset = 0;
  3978. var matOffset = 0;
  3979. var i;
  3980. var parentOffset;
  3981. var boneLength = bones.length;
  3982. for (i = 0; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++) {
  3983. 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);
  3984. if (i != 0) {
  3985. parentOffset = bones[i].parentIndex * 16;
  3986. Utils3D.mulMatrixByArray(outBonesDatas, parentOffset, outBonesDatas, matOffset, outBonesDatas, matOffset);
  3987. }
  3988. }
  3989. var n = inverGlobalBindPose.length;
  3990. for (i = 0; i < n; i++) {
  3991. Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas, boneIndexToMesh[i] * 16, inverGlobalBindPose[i], outAnimationDatas, i * 16);
  3992. }
  3993. }
  3994. static _computeAnimationDatasByArrayAndMatrixFast(inverGlobalBindPose, bonesDatas, outAnimationDatas, boneIndexToMesh) {
  3995. for (var i = 0, n = inverGlobalBindPose.length; i < n; i++)
  3996. Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas, boneIndexToMesh[i] * 16, inverGlobalBindPose[i], outAnimationDatas, i * 16);
  3997. }
  3998. static _computeBoneAndAnimationDatasByBindPoseMatrxixOld(bones, curData, inverGlobalBindPose, outBonesDatas, outAnimationDatas) {
  3999. var offset = 0;
  4000. var matOffset = 0;
  4001. var i;
  4002. var parentOffset;
  4003. var boneLength = bones.length;
  4004. for (i = 0; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++) {
  4005. 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);
  4006. if (i != 0) {
  4007. parentOffset = bones[i].parentIndex * 16;
  4008. Utils3D.mulMatrixByArray(outBonesDatas, parentOffset, outBonesDatas, matOffset, outBonesDatas, matOffset);
  4009. }
  4010. }
  4011. var n = inverGlobalBindPose.length;
  4012. for (i = 0; i < n; i++) {
  4013. var arrayOffset = i * 16;
  4014. Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas, arrayOffset, inverGlobalBindPose[i], outAnimationDatas, arrayOffset);
  4015. }
  4016. }
  4017. static _computeAnimationDatasByArrayAndMatrixFastOld(inverGlobalBindPose, bonesDatas, outAnimationDatas) {
  4018. var n = inverGlobalBindPose.length;
  4019. for (var i = 0; i < n; i++) {
  4020. var arrayOffset = i * 16;
  4021. Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas, arrayOffset, inverGlobalBindPose[i], outAnimationDatas, arrayOffset);
  4022. }
  4023. }
  4024. static _computeRootAnimationData(bones, curData, animationDatas) {
  4025. for (var i = 0, offset = 0, matOffset = 0, boneLength = bones.length; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++)
  4026. 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);
  4027. }
  4028. static transformVector3ArrayByQuat(sourceArray, sourceOffset, rotation, outArray, outOffset) {
  4029. 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;
  4030. outArray[outOffset] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4031. outArray[outOffset + 1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4032. outArray[outOffset + 2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4033. }
  4034. static mulMatrixByArray(leftArray, leftOffset, rightArray, rightOffset, outArray, outOffset) {
  4035. var i, ai0, ai1, ai2, ai3;
  4036. if (outArray === rightArray) {
  4037. rightArray = Utils3D._tempArray16_3;
  4038. for (i = 0; i < 16; ++i) {
  4039. rightArray[i] = outArray[outOffset + i];
  4040. }
  4041. rightOffset = 0;
  4042. }
  4043. for (i = 0; i < 4; i++) {
  4044. ai0 = leftArray[leftOffset + i];
  4045. ai1 = leftArray[leftOffset + i + 4];
  4046. ai2 = leftArray[leftOffset + i + 8];
  4047. ai3 = leftArray[leftOffset + i + 12];
  4048. outArray[outOffset + i] = ai0 * rightArray[rightOffset + 0] + ai1 * rightArray[rightOffset + 1] + ai2 * rightArray[rightOffset + 2] + ai3 * rightArray[rightOffset + 3];
  4049. outArray[outOffset + i + 4] = ai0 * rightArray[rightOffset + 4] + ai1 * rightArray[rightOffset + 5] + ai2 * rightArray[rightOffset + 6] + ai3 * rightArray[rightOffset + 7];
  4050. outArray[outOffset + i + 8] = ai0 * rightArray[rightOffset + 8] + ai1 * rightArray[rightOffset + 9] + ai2 * rightArray[rightOffset + 10] + ai3 * rightArray[rightOffset + 11];
  4051. outArray[outOffset + i + 12] = ai0 * rightArray[rightOffset + 12] + ai1 * rightArray[rightOffset + 13] + ai2 * rightArray[rightOffset + 14] + ai3 * rightArray[rightOffset + 15];
  4052. }
  4053. }
  4054. static mulMatrixByArrayFast(leftArray, leftOffset, rightArray, rightOffset, outArray, outOffset) {
  4055. var i, ai0, ai1, ai2, ai3;
  4056. for (i = 0; i < 4; i++) {
  4057. ai0 = leftArray[leftOffset + i];
  4058. ai1 = leftArray[leftOffset + i + 4];
  4059. ai2 = leftArray[leftOffset + i + 8];
  4060. ai3 = leftArray[leftOffset + i + 12];
  4061. outArray[outOffset + i] = ai0 * rightArray[rightOffset + 0] + ai1 * rightArray[rightOffset + 1] + ai2 * rightArray[rightOffset + 2] + ai3 * rightArray[rightOffset + 3];
  4062. outArray[outOffset + i + 4] = ai0 * rightArray[rightOffset + 4] + ai1 * rightArray[rightOffset + 5] + ai2 * rightArray[rightOffset + 6] + ai3 * rightArray[rightOffset + 7];
  4063. outArray[outOffset + i + 8] = ai0 * rightArray[rightOffset + 8] + ai1 * rightArray[rightOffset + 9] + ai2 * rightArray[rightOffset + 10] + ai3 * rightArray[rightOffset + 11];
  4064. outArray[outOffset + i + 12] = ai0 * rightArray[rightOffset + 12] + ai1 * rightArray[rightOffset + 13] + ai2 * rightArray[rightOffset + 14] + ai3 * rightArray[rightOffset + 15];
  4065. }
  4066. }
  4067. static mulMatrixByArrayAndMatrixFast(leftArray, leftOffset, rightMatrix, outArray, outOffset) {
  4068. var i, ai0, ai1, ai2, ai3;
  4069. var rightMatrixE = rightMatrix.elements;
  4070. var m11 = rightMatrixE[0], m12 = rightMatrixE[1], m13 = rightMatrixE[2], m14 = rightMatrixE[3];
  4071. var m21 = rightMatrixE[4], m22 = rightMatrixE[5], m23 = rightMatrixE[6], m24 = rightMatrixE[7];
  4072. var m31 = rightMatrixE[8], m32 = rightMatrixE[9], m33 = rightMatrixE[10], m34 = rightMatrixE[11];
  4073. var m41 = rightMatrixE[12], m42 = rightMatrixE[13], m43 = rightMatrixE[14], m44 = rightMatrixE[15];
  4074. var ai0LeftOffset = leftOffset;
  4075. var ai1LeftOffset = leftOffset + 4;
  4076. var ai2LeftOffset = leftOffset + 8;
  4077. var ai3LeftOffset = leftOffset + 12;
  4078. var ai0OutOffset = outOffset;
  4079. var ai1OutOffset = outOffset + 4;
  4080. var ai2OutOffset = outOffset + 8;
  4081. var ai3OutOffset = outOffset + 12;
  4082. for (i = 0; i < 4; i++) {
  4083. ai0 = leftArray[ai0LeftOffset + i];
  4084. ai1 = leftArray[ai1LeftOffset + i];
  4085. ai2 = leftArray[ai2LeftOffset + i];
  4086. ai3 = leftArray[ai3LeftOffset + i];
  4087. outArray[ai0OutOffset + i] = ai0 * m11 + ai1 * m12 + ai2 * m13 + ai3 * m14;
  4088. outArray[ai1OutOffset + i] = ai0 * m21 + ai1 * m22 + ai2 * m23 + ai3 * m24;
  4089. outArray[ai2OutOffset + i] = ai0 * m31 + ai1 * m32 + ai2 * m33 + ai3 * m34;
  4090. outArray[ai3OutOffset + i] = ai0 * m41 + ai1 * m42 + ai2 * m43 + ai3 * m44;
  4091. }
  4092. }
  4093. static createAffineTransformationArray(tX, tY, tZ, rX, rY, rZ, rW, sX, sY, sZ, outArray, outOffset) {
  4094. var x2 = rX + rX, y2 = rY + rY, z2 = rZ + rZ;
  4095. var xx = rX * x2, xy = rX * y2, xz = rX * z2, yy = rY * y2, yz = rY * z2, zz = rZ * z2;
  4096. var wx = rW * x2, wy = rW * y2, wz = rW * z2;
  4097. outArray[outOffset + 0] = (1 - (yy + zz)) * sX;
  4098. outArray[outOffset + 1] = (xy + wz) * sX;
  4099. outArray[outOffset + 2] = (xz - wy) * sX;
  4100. outArray[outOffset + 3] = 0;
  4101. outArray[outOffset + 4] = (xy - wz) * sY;
  4102. outArray[outOffset + 5] = (1 - (xx + zz)) * sY;
  4103. outArray[outOffset + 6] = (yz + wx) * sY;
  4104. outArray[outOffset + 7] = 0;
  4105. outArray[outOffset + 8] = (xz + wy) * sZ;
  4106. outArray[outOffset + 9] = (yz - wx) * sZ;
  4107. outArray[outOffset + 10] = (1 - (xx + yy)) * sZ;
  4108. outArray[outOffset + 11] = 0;
  4109. outArray[outOffset + 12] = tX;
  4110. outArray[outOffset + 13] = tY;
  4111. outArray[outOffset + 14] = tZ;
  4112. outArray[outOffset + 15] = 1;
  4113. }
  4114. static transformVector3ArrayToVector3ArrayCoordinate(source, sourceOffset, transform, result, resultOffset) {
  4115. var coordinateX = source[sourceOffset + 0];
  4116. var coordinateY = source[sourceOffset + 1];
  4117. var coordinateZ = source[sourceOffset + 2];
  4118. var transformElem = transform.elements;
  4119. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  4120. result[resultOffset] = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  4121. result[resultOffset + 1] = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  4122. result[resultOffset + 2] = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  4123. }
  4124. static transformVector3ArrayToVector3ArrayNormal(source, sourceOffset, transform, result, resultOffset) {
  4125. var coordinateX = source[sourceOffset + 0];
  4126. var coordinateY = source[sourceOffset + 1];
  4127. var coordinateZ = source[sourceOffset + 2];
  4128. var transformElem = transform.elements;
  4129. result[resultOffset] = coordinateX * transformElem[0] + coordinateY * transformElem[4] + coordinateZ * transformElem[8];
  4130. result[resultOffset + 1] = coordinateX * transformElem[1] + coordinateY * transformElem[5] + coordinateZ * transformElem[9];
  4131. result[resultOffset + 2] = coordinateX * transformElem[2] + coordinateY * transformElem[6] + coordinateZ * transformElem[10];
  4132. }
  4133. static transformLightingMapTexcoordArray(source, sourceOffset, lightingMapScaleOffset, result, resultOffset) {
  4134. result[resultOffset + 0] = source[sourceOffset + 0] * lightingMapScaleOffset.x + lightingMapScaleOffset.z;
  4135. result[resultOffset + 1] = 1.0 - ((1.0 - source[sourceOffset + 1]) * lightingMapScaleOffset.y + lightingMapScaleOffset.w);
  4136. }
  4137. static getURLVerion(url) {
  4138. var index = url.indexOf("?");
  4139. return index >= 0 ? url.substr(index) : null;
  4140. }
  4141. static _createAffineTransformationArray(trans, rot, scale, outE) {
  4142. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  4143. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  4144. var wx = w * x2, wy = w * y2, wz = w * z2, sx = scale.x, sy = scale.y, sz = scale.z;
  4145. outE[0] = (1 - (yy + zz)) * sx;
  4146. outE[1] = (xy + wz) * sx;
  4147. outE[2] = (xz - wy) * sx;
  4148. outE[3] = 0;
  4149. outE[4] = (xy - wz) * sy;
  4150. outE[5] = (1 - (xx + zz)) * sy;
  4151. outE[6] = (yz + wx) * sy;
  4152. outE[7] = 0;
  4153. outE[8] = (xz + wy) * sz;
  4154. outE[9] = (yz - wx) * sz;
  4155. outE[10] = (1 - (xx + yy)) * sz;
  4156. outE[11] = 0;
  4157. outE[12] = trans.x;
  4158. outE[13] = trans.y;
  4159. outE[14] = trans.z;
  4160. outE[15] = 1;
  4161. }
  4162. static _mulMatrixArray(left, right, rightOffset, outArray, outOffset) {
  4163. var l = right;
  4164. var r = left;
  4165. var e = outArray;
  4166. var l11 = l[rightOffset], l12 = l[rightOffset + 1], l13 = l[rightOffset + 2], l14 = l[rightOffset + 3];
  4167. var l21 = l[rightOffset + 4], l22 = l[rightOffset + 5], l23 = l[rightOffset + 6], l24 = l[rightOffset + 7];
  4168. var l31 = l[rightOffset + 8], l32 = l[rightOffset + 9], l33 = l[rightOffset + 10], l34 = l[rightOffset + 11];
  4169. var l41 = l[rightOffset + 12], l42 = l[rightOffset + 13], l43 = l[rightOffset + 14], l44 = l[rightOffset + 15];
  4170. var r11 = r[0], r12 = r[1], r13 = r[2], r14 = r[3];
  4171. var r21 = r[4], r22 = r[5], r23 = r[6], r24 = r[7];
  4172. var r31 = r[8], r32 = r[9], r33 = r[10], r34 = r[11];
  4173. var r41 = r[12], r42 = r[13], r43 = r[14], r44 = r[15];
  4174. e[outOffset] = (l11 * r11) + (l12 * r21) + (l13 * r31) + (l14 * r41);
  4175. e[outOffset + 1] = (l11 * r12) + (l12 * r22) + (l13 * r32) + (l14 * r42);
  4176. e[outOffset + 2] = (l11 * r13) + (l12 * r23) + (l13 * r33) + (l14 * r43);
  4177. e[outOffset + 3] = (l11 * r14) + (l12 * r24) + (l13 * r34) + (l14 * r44);
  4178. e[outOffset + 4] = (l21 * r11) + (l22 * r21) + (l23 * r31) + (l24 * r41);
  4179. e[outOffset + 5] = (l21 * r12) + (l22 * r22) + (l23 * r32) + (l24 * r42);
  4180. e[outOffset + 6] = (l21 * r13) + (l22 * r23) + (l23 * r33) + (l24 * r43);
  4181. e[outOffset + 7] = (l21 * r14) + (l22 * r24) + (l23 * r34) + (l24 * r44);
  4182. e[outOffset + 8] = (l31 * r11) + (l32 * r21) + (l33 * r31) + (l34 * r41);
  4183. e[outOffset + 9] = (l31 * r12) + (l32 * r22) + (l33 * r32) + (l34 * r42);
  4184. e[outOffset + 10] = (l31 * r13) + (l32 * r23) + (l33 * r33) + (l34 * r43);
  4185. e[outOffset + 11] = (l31 * r14) + (l32 * r24) + (l33 * r34) + (l34 * r44);
  4186. e[outOffset + 12] = (l41 * r11) + (l42 * r21) + (l43 * r31) + (l44 * r41);
  4187. e[outOffset + 13] = (l41 * r12) + (l42 * r22) + (l43 * r32) + (l44 * r42);
  4188. e[outOffset + 14] = (l41 * r13) + (l42 * r23) + (l43 * r33) + (l44 * r43);
  4189. e[outOffset + 15] = (l41 * r14) + (l42 * r24) + (l43 * r34) + (l44 * r44);
  4190. }
  4191. static arcTanAngle(x, y) {
  4192. if (x == 0) {
  4193. if (y == 1)
  4194. return Math.PI / 2;
  4195. return -Math.PI / 2;
  4196. }
  4197. if (x > 0)
  4198. return Math.atan(y / x);
  4199. if (x < 0) {
  4200. if (y > 0)
  4201. return Math.atan(y / x) + Math.PI;
  4202. return Math.atan(y / x) - Math.PI;
  4203. }
  4204. return 0;
  4205. }
  4206. static angleTo(from, location, angle) {
  4207. Vector3.subtract(location, from, Quaternion.TEMPVector30);
  4208. Vector3.normalize(Quaternion.TEMPVector30, Quaternion.TEMPVector30);
  4209. angle.x = Math.asin(Quaternion.TEMPVector30.y);
  4210. angle.y = Utils3D.arcTanAngle(-Quaternion.TEMPVector30.z, -Quaternion.TEMPVector30.x);
  4211. }
  4212. static transformQuat(source, rotation, out) {
  4213. var re = rotation;
  4214. 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;
  4215. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4216. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4217. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4218. }
  4219. static quaternionWeight(f, weight, e) {
  4220. e.x = f.x * weight;
  4221. e.y = f.y * weight;
  4222. e.z = f.z * weight;
  4223. e.w = f.w;
  4224. }
  4225. static quaternionConjugate(value, result) {
  4226. result.x = -value.x;
  4227. result.y = -value.y;
  4228. result.z = -value.z;
  4229. result.w = value.w;
  4230. }
  4231. static scaleWeight(s, w, out) {
  4232. var sX = s.x, sY = s.y, sZ = s.z;
  4233. out.x = sX > 0 ? Math.pow(Math.abs(sX), w) : -Math.pow(Math.abs(sX), w);
  4234. out.y = sY > 0 ? Math.pow(Math.abs(sY), w) : -Math.pow(Math.abs(sY), w);
  4235. out.z = sZ > 0 ? Math.pow(Math.abs(sZ), w) : -Math.pow(Math.abs(sZ), w);
  4236. }
  4237. static scaleBlend(sa, sb, w, out) {
  4238. var saw = Utils3D._tempVector3_0;
  4239. var sbw = Utils3D._tempVector3_1;
  4240. Utils3D.scaleWeight(sa, 1.0 - w, saw);
  4241. Utils3D.scaleWeight(sb, w, sbw);
  4242. var sng = w > 0.5 ? sb : sa;
  4243. out.x = sng.x > 0 ? Math.abs(saw.x * sbw.x) : -Math.abs(saw.x * sbw.x);
  4244. out.y = sng.y > 0 ? Math.abs(saw.y * sbw.y) : -Math.abs(saw.y * sbw.y);
  4245. out.z = sng.z > 0 ? Math.abs(saw.z * sbw.z) : -Math.abs(saw.z * sbw.z);
  4246. }
  4247. static matrix4x4MultiplyFFF(a, b, e) {
  4248. var i, ai0, ai1, ai2, ai3;
  4249. if (e === b) {
  4250. b = new Float32Array(16);
  4251. for (i = 0; i < 16; ++i) {
  4252. b[i] = e[i];
  4253. }
  4254. }
  4255. var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
  4256. var b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7];
  4257. var b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11];
  4258. var b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
  4259. for (i = 0; i < 4; i++) {
  4260. ai0 = a[i];
  4261. ai1 = a[i + 4];
  4262. ai2 = a[i + 8];
  4263. ai3 = a[i + 12];
  4264. e[i] = ai0 * b0 + ai1 * b1 + ai2 * b2 + ai3 * b3;
  4265. e[i + 4] = ai0 * b4 + ai1 * b5 + ai2 * b6 + ai3 * b7;
  4266. e[i + 8] = ai0 * b8 + ai1 * b9 + ai2 * b10 + ai3 * b11;
  4267. e[i + 12] = ai0 * b12 + ai1 * b13 + ai2 * b14 + ai3 * b15;
  4268. }
  4269. }
  4270. static matrix4x4MultiplyFFFForNative(a, b, e) {
  4271. Laya.LayaGL.instance.matrix4x4Multiply(a, b, e);
  4272. }
  4273. static matrix4x4MultiplyMFM(left, right, out) {
  4274. Utils3D.matrix4x4MultiplyFFF(left.elements, right, out.elements);
  4275. }
  4276. static _buildTexture2D(width, height, format, colorFunc, mipmaps = false) {
  4277. var texture = new Laya.Texture2D(width, height, format, mipmaps, true);
  4278. texture.anisoLevel = 1;
  4279. texture.filterMode = Laya.FilterMode.Point;
  4280. TextureGenerator._generateTexture2D(texture, width, height, colorFunc);
  4281. return texture;
  4282. }
  4283. static _drawBound(debugLine, boundBox, color) {
  4284. if (debugLine.lineCount + 12 > debugLine.maxLineCount)
  4285. debugLine.maxLineCount += 12;
  4286. var start = Utils3D._tempVector3_0;
  4287. var end = Utils3D._tempVector3_1;
  4288. var min = boundBox.min;
  4289. var max = boundBox.max;
  4290. start.setValue(min.x, min.y, min.z);
  4291. end.setValue(max.x, min.y, min.z);
  4292. debugLine.addLine(start, end, color, color);
  4293. start.setValue(min.x, min.y, min.z);
  4294. end.setValue(min.x, min.y, max.z);
  4295. debugLine.addLine(start, end, color, color);
  4296. start.setValue(max.x, min.y, min.z);
  4297. end.setValue(max.x, min.y, max.z);
  4298. debugLine.addLine(start, end, color, color);
  4299. start.setValue(min.x, min.y, max.z);
  4300. end.setValue(max.x, min.y, max.z);
  4301. debugLine.addLine(start, end, color, color);
  4302. start.setValue(min.x, min.y, min.z);
  4303. end.setValue(min.x, max.y, min.z);
  4304. debugLine.addLine(start, end, color, color);
  4305. start.setValue(min.x, min.y, max.z);
  4306. end.setValue(min.x, max.y, max.z);
  4307. debugLine.addLine(start, end, color, color);
  4308. start.setValue(max.x, min.y, min.z);
  4309. end.setValue(max.x, max.y, min.z);
  4310. debugLine.addLine(start, end, color, color);
  4311. start.setValue(max.x, min.y, max.z);
  4312. end.setValue(max.x, max.y, max.z);
  4313. debugLine.addLine(start, end, color, color);
  4314. start.setValue(min.x, max.y, min.z);
  4315. end.setValue(max.x, max.y, min.z);
  4316. debugLine.addLine(start, end, color, color);
  4317. start.setValue(min.x, max.y, min.z);
  4318. end.setValue(min.x, max.y, max.z);
  4319. debugLine.addLine(start, end, color, color);
  4320. start.setValue(max.x, max.y, min.z);
  4321. end.setValue(max.x, max.y, max.z);
  4322. debugLine.addLine(start, end, color, color);
  4323. start.setValue(min.x, max.y, max.z);
  4324. end.setValue(max.x, max.y, max.z);
  4325. debugLine.addLine(start, end, color, color);
  4326. }
  4327. static _getHierarchyPath(rootSprite, checkSprite, path) {
  4328. path.length = 0;
  4329. var sprite = checkSprite;
  4330. while (sprite !== rootSprite) {
  4331. var parent = sprite._parent;
  4332. if (parent)
  4333. path.push(parent.getChildIndex(sprite));
  4334. else
  4335. return null;
  4336. sprite = parent;
  4337. }
  4338. return path;
  4339. }
  4340. static _getNodeByHierarchyPath(rootSprite, invPath) {
  4341. var sprite = rootSprite;
  4342. for (var i = invPath.length - 1; i >= 0; i--) {
  4343. sprite = sprite.getChildAt(invPath[i]);
  4344. }
  4345. return sprite;
  4346. }
  4347. }
  4348. Utils3D._tempVector3_0 = new Vector3();
  4349. Utils3D._tempVector3_1 = new Vector3();
  4350. Utils3D._tempArray16_0 = new Float32Array(16);
  4351. Utils3D._tempArray16_1 = new Float32Array(16);
  4352. Utils3D._tempArray16_2 = new Float32Array(16);
  4353. Utils3D._tempArray16_3 = new Float32Array(16);
  4354. Utils3D._compIdToNode = new Object();
  4355. class CharacterController extends PhysicsComponent {
  4356. constructor(stepheight = 0.1, upAxis = null, collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  4357. super(collisionGroup, canCollideWith);
  4358. this._upAxis = new Vector3(0, 1, 0);
  4359. this._maxSlope = 45.0;
  4360. this._jumpSpeed = 10.0;
  4361. this._fallSpeed = 55.0;
  4362. this._gravity = new Vector3(0, -9.8 * 3, 0);
  4363. this._btKinematicCharacter = null;
  4364. this._stepHeight = stepheight;
  4365. (upAxis) && (this._upAxis = upAxis);
  4366. this._controlBySimulation = true;
  4367. }
  4368. static __init__() {
  4369. CharacterController._btTempVector30 = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  4370. }
  4371. get fallSpeed() {
  4372. return this._fallSpeed;
  4373. }
  4374. set fallSpeed(value) {
  4375. this._fallSpeed = value;
  4376. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setFallSpeed(this._btKinematicCharacter, value);
  4377. }
  4378. get jumpSpeed() {
  4379. return this._jumpSpeed;
  4380. }
  4381. set jumpSpeed(value) {
  4382. this._jumpSpeed = value;
  4383. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setJumpSpeed(this._btKinematicCharacter, value);
  4384. }
  4385. get gravity() {
  4386. return this._gravity;
  4387. }
  4388. set gravity(value) {
  4389. this._gravity = value;
  4390. var bt = ILaya3D.Physics3D._bullet;
  4391. var btGravity = CharacterController._btTempVector30;
  4392. bt.btVector3_setValue(btGravity, -value.x, value.y, value.z);
  4393. bt.btKinematicCharacterController_setGravity(this._btKinematicCharacter, btGravity);
  4394. }
  4395. get maxSlope() {
  4396. return this._maxSlope;
  4397. }
  4398. set maxSlope(value) {
  4399. this._maxSlope = value;
  4400. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setMaxSlope(this._btKinematicCharacter, (value / 180) * Math.PI);
  4401. }
  4402. get isGrounded() {
  4403. return ILaya3D.Physics3D._bullet.btKinematicCharacterController_onGround(this._btKinematicCharacter);
  4404. }
  4405. get stepHeight() {
  4406. return this._stepHeight;
  4407. }
  4408. set stepHeight(value) {
  4409. this._stepHeight = value;
  4410. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setStepHeight(this._btKinematicCharacter, value);
  4411. }
  4412. get upAxis() {
  4413. return this._upAxis;
  4414. }
  4415. set upAxis(value) {
  4416. this._upAxis = value;
  4417. var btUpAxis = CharacterController._btTempVector30;
  4418. Utils3D._convertToBulletVec3(value, btUpAxis, false);
  4419. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setUp(this._btKinematicCharacter, btUpAxis);
  4420. }
  4421. _constructCharacter() {
  4422. var bt = ILaya3D.Physics3D._bullet;
  4423. if (this._btKinematicCharacter)
  4424. bt.btKinematicCharacterController_destroy(this._btKinematicCharacter);
  4425. var btUpAxis = CharacterController._btTempVector30;
  4426. bt.btVector3_setValue(btUpAxis, this._upAxis.x, this._upAxis.y, this._upAxis.z);
  4427. this._btKinematicCharacter = bt.btKinematicCharacterController_create(this._btColliderObject, this._colliderShape._btShape, this._stepHeight, btUpAxis);
  4428. this.fallSpeed = this._fallSpeed;
  4429. this.maxSlope = this._maxSlope;
  4430. this.jumpSpeed = this._jumpSpeed;
  4431. this.gravity = this._gravity;
  4432. }
  4433. _onShapeChange(colShape) {
  4434. super._onShapeChange(colShape);
  4435. this._constructCharacter();
  4436. }
  4437. _onAdded() {
  4438. var bt = ILaya3D.Physics3D._bullet;
  4439. var ghostObject = bt.btPairCachingGhostObject_create();
  4440. bt.btCollisionObject_setUserIndex(ghostObject, this.id);
  4441. bt.btCollisionObject_setCollisionFlags(ghostObject, PhysicsComponent.COLLISIONFLAGS_CHARACTER_OBJECT);
  4442. this._btColliderObject = ghostObject;
  4443. (this._colliderShape) && (this._constructCharacter());
  4444. super._onAdded();
  4445. }
  4446. _addToSimulation() {
  4447. this._simulation._characters.push(this);
  4448. this._simulation._addCharacter(this, this._collisionGroup, this._canCollideWith);
  4449. }
  4450. _removeFromSimulation() {
  4451. this._simulation._removeCharacter(this);
  4452. var characters = this._simulation._characters;
  4453. characters.splice(characters.indexOf(this), 1);
  4454. }
  4455. _cloneTo(dest) {
  4456. super._cloneTo(dest);
  4457. var destCharacterController = dest;
  4458. destCharacterController.stepHeight = this._stepHeight;
  4459. destCharacterController.upAxis = this._upAxis;
  4460. destCharacterController.maxSlope = this._maxSlope;
  4461. destCharacterController.jumpSpeed = this._jumpSpeed;
  4462. destCharacterController.fallSpeed = this._fallSpeed;
  4463. destCharacterController.gravity = this._gravity;
  4464. }
  4465. _onDestroy() {
  4466. ILaya3D.Physics3D._bullet.btKinematicCharacterController_destroy(this._btKinematicCharacter);
  4467. super._onDestroy();
  4468. this._btKinematicCharacter = null;
  4469. }
  4470. move(movement) {
  4471. var btMovement = CharacterController._btVector30;
  4472. var bt = ILaya3D.Physics3D._bullet;
  4473. bt.btVector3_setValue(btMovement, -movement.x, movement.y, movement.z);
  4474. bt.btKinematicCharacterController_setWalkDirection(this._btKinematicCharacter, btMovement);
  4475. }
  4476. jump(velocity = null) {
  4477. var bt = ILaya3D.Physics3D._bullet;
  4478. var btVelocity = CharacterController._btVector30;
  4479. if (velocity) {
  4480. Utils3D._convertToBulletVec3(velocity, btVelocity, true);
  4481. bt.btKinematicCharacterController_jump(this._btKinematicCharacter, btVelocity);
  4482. }
  4483. else {
  4484. bt.btVector3_setValue(btVelocity, 0, 0, 0);
  4485. bt.btKinematicCharacterController_jump(this._btKinematicCharacter, btVelocity);
  4486. }
  4487. }
  4488. }
  4489. CharacterController.UPAXIS_X = 0;
  4490. CharacterController.UPAXIS_Y = 1;
  4491. CharacterController.UPAXIS_Z = 2;
  4492. class PhysicsTriggerComponent extends PhysicsComponent {
  4493. constructor(collisionGroup, canCollideWith) {
  4494. super(collisionGroup, canCollideWith);
  4495. this._isTrigger = false;
  4496. }
  4497. get isTrigger() {
  4498. return this._isTrigger;
  4499. }
  4500. set isTrigger(value) {
  4501. this._isTrigger = value;
  4502. var bt = ILaya3D.Physics3D._bullet;
  4503. if (this._btColliderObject) {
  4504. var flags = bt.btCollisionObject_getCollisionFlags(this._btColliderObject);
  4505. if (value) {
  4506. if ((flags & PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE) === 0)
  4507. bt.btCollisionObject_setCollisionFlags(this._btColliderObject, flags | PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE);
  4508. }
  4509. else {
  4510. if ((flags & PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE) !== 0)
  4511. bt.btCollisionObject_setCollisionFlags(this._btColliderObject, flags ^ PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE);
  4512. }
  4513. }
  4514. }
  4515. _onAdded() {
  4516. super._onAdded();
  4517. this.isTrigger = this._isTrigger;
  4518. }
  4519. _cloneTo(dest) {
  4520. super._cloneTo(dest);
  4521. dest.isTrigger = this._isTrigger;
  4522. }
  4523. }
  4524. class Rigidbody3D extends PhysicsTriggerComponent {
  4525. constructor(collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  4526. super(collisionGroup, canCollideWith);
  4527. this._isKinematic = false;
  4528. this._mass = 1.0;
  4529. this._gravity = new Vector3(0, -10, 0);
  4530. this._angularDamping = 0.0;
  4531. this._linearDamping = 0.0;
  4532. this._overrideGravity = false;
  4533. this._totalTorque = new Vector3(0, 0, 0);
  4534. this._totalForce = new Vector3(0, 0, 0);
  4535. this._linearVelocity = new Vector3();
  4536. this._angularVelocity = new Vector3();
  4537. this._linearFactor = new Vector3(1, 1, 1);
  4538. this._angularFactor = new Vector3(1, 1, 1);
  4539. this._detectCollisions = true;
  4540. this._controlBySimulation = true;
  4541. }
  4542. static __init__() {
  4543. var bt = ILaya3D.Physics3D._bullet;
  4544. Rigidbody3D._btTempVector30 = bt.btVector3_create(0, 0, 0);
  4545. Rigidbody3D._btTempVector31 = bt.btVector3_create(0, 0, 0);
  4546. Rigidbody3D._btVector3Zero = bt.btVector3_create(0, 0, 0);
  4547. Rigidbody3D._btInertia = bt.btVector3_create(0, 0, 0);
  4548. Rigidbody3D._btImpulse = bt.btVector3_create(0, 0, 0);
  4549. Rigidbody3D._btImpulseOffset = bt.btVector3_create(0, 0, 0);
  4550. Rigidbody3D._btGravity = bt.btVector3_create(0, 0, 0);
  4551. Rigidbody3D._btTransform0 = bt.btTransform_create();
  4552. }
  4553. get mass() {
  4554. return this._mass;
  4555. }
  4556. set mass(value) {
  4557. value = Math.max(value, 1e-07);
  4558. this._mass = value;
  4559. (this._isKinematic) || (this._updateMass(value));
  4560. }
  4561. get isKinematic() {
  4562. return this._isKinematic;
  4563. }
  4564. set isKinematic(value) {
  4565. this._isKinematic = value;
  4566. this._controlBySimulation = !value;
  4567. var bt = ILaya3D.Physics3D._bullet;
  4568. var canInSimulation = !!(this._simulation && this._enabled && this._colliderShape);
  4569. canInSimulation && this._removeFromSimulation();
  4570. var natColObj = this._btColliderObject;
  4571. var flags = bt.btCollisionObject_getCollisionFlags(natColObj);
  4572. if (value) {
  4573. flags = flags | PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  4574. bt.btCollisionObject_setCollisionFlags(natColObj, flags);
  4575. bt.btCollisionObject_forceActivationState(this._btColliderObject, PhysicsComponent.ACTIVATIONSTATE_DISABLE_DEACTIVATION);
  4576. this._enableProcessCollisions = false;
  4577. this._updateMass(0);
  4578. }
  4579. else {
  4580. if ((flags & PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT) > 0)
  4581. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  4582. bt.btCollisionObject_setCollisionFlags(natColObj, flags);
  4583. bt.btCollisionObject_setActivationState(this._btColliderObject, PhysicsComponent.ACTIVATIONSTATE_ACTIVE_TAG);
  4584. this._enableProcessCollisions = true;
  4585. this._updateMass(this._mass);
  4586. }
  4587. var btZero = Rigidbody3D._btVector3Zero;
  4588. bt.btCollisionObject_setInterpolationLinearVelocity(natColObj, btZero);
  4589. bt.btRigidBody_setLinearVelocity(natColObj, btZero);
  4590. bt.btCollisionObject_setInterpolationAngularVelocity(natColObj, btZero);
  4591. bt.btRigidBody_setAngularVelocity(natColObj, btZero);
  4592. canInSimulation && this._addToSimulation();
  4593. }
  4594. get linearDamping() {
  4595. return this._linearDamping;
  4596. }
  4597. set linearDamping(value) {
  4598. this._linearDamping = value;
  4599. if (this._btColliderObject)
  4600. ILaya3D.Physics3D._bullet.btRigidBody_setDamping(this._btColliderObject, value, this._angularDamping);
  4601. }
  4602. get angularDamping() {
  4603. return this._angularDamping;
  4604. }
  4605. set angularDamping(value) {
  4606. this._angularDamping = value;
  4607. if (this._btColliderObject)
  4608. ILaya3D.Physics3D._bullet.btRigidBody_setDamping(this._btColliderObject, this._linearDamping, value);
  4609. }
  4610. get overrideGravity() {
  4611. return this._overrideGravity;
  4612. }
  4613. set overrideGravity(value) {
  4614. this._overrideGravity = value;
  4615. var bt = ILaya3D.Physics3D._bullet;
  4616. if (this._btColliderObject) {
  4617. var flag = bt.btRigidBody_getFlags(this._btColliderObject);
  4618. if (value) {
  4619. if ((flag & Rigidbody3D._BT_DISABLE_WORLD_GRAVITY) === 0)
  4620. bt.btRigidBody_setFlags(this._btColliderObject, flag | Rigidbody3D._BT_DISABLE_WORLD_GRAVITY);
  4621. }
  4622. else {
  4623. if ((flag & Rigidbody3D._BT_DISABLE_WORLD_GRAVITY) > 0)
  4624. bt.btRigidBody_setFlags(this._btColliderObject, flag ^ Rigidbody3D._BT_DISABLE_WORLD_GRAVITY);
  4625. }
  4626. }
  4627. }
  4628. get gravity() {
  4629. return this._gravity;
  4630. }
  4631. set gravity(value) {
  4632. this._gravity = value;
  4633. var bt = ILaya3D.Physics3D._bullet;
  4634. bt.btVector3_setValue(Rigidbody3D._btGravity, -value.x, value.y, value.z);
  4635. bt.btRigidBody_setGravity(this._btColliderObject, Rigidbody3D._btGravity);
  4636. }
  4637. get totalForce() {
  4638. if (this._btColliderObject) {
  4639. var btTotalForce = ILaya3D.Physics3D._bullet.btRigidBody_getTotalForce(this._btColliderObject);
  4640. Utils3D._convertToLayaVec3(btTotalForce, this._totalForce, true);
  4641. return this._totalForce;
  4642. }
  4643. return null;
  4644. }
  4645. get linearFactor() {
  4646. return this._linearFactor;
  4647. }
  4648. set linearFactor(value) {
  4649. this._linearFactor = value;
  4650. var btValue = Rigidbody3D._btTempVector30;
  4651. Utils3D._convertToBulletVec3(value, btValue, false);
  4652. ILaya3D.Physics3D._bullet.btRigidBody_setLinearFactor(this._btColliderObject, btValue);
  4653. }
  4654. get linearVelocity() {
  4655. if (this._btColliderObject)
  4656. Utils3D._convertToLayaVec3(ILaya3D.Physics3D._bullet.btRigidBody_getLinearVelocity(this._btColliderObject), this._linearVelocity, true);
  4657. return this._linearVelocity;
  4658. }
  4659. set linearVelocity(value) {
  4660. this._linearVelocity = value;
  4661. if (this._btColliderObject) {
  4662. var btValue = Rigidbody3D._btTempVector30;
  4663. Utils3D._convertToBulletVec3(value, btValue, true);
  4664. (this.isSleeping) && (this.wakeUp());
  4665. ILaya3D.Physics3D._bullet.btRigidBody_setLinearVelocity(this._btColliderObject, btValue);
  4666. }
  4667. }
  4668. get angularFactor() {
  4669. return this._angularFactor;
  4670. }
  4671. set angularFactor(value) {
  4672. this._angularFactor = value;
  4673. var btValue = Rigidbody3D._btTempVector30;
  4674. Utils3D._convertToBulletVec3(value, btValue, false);
  4675. ILaya3D.Physics3D._bullet.btRigidBody_setAngularFactor(this._btColliderObject, btValue);
  4676. }
  4677. get angularVelocity() {
  4678. if (this._btColliderObject)
  4679. Utils3D._convertToLayaVec3(ILaya3D.Physics3D._bullet.btRigidBody_getAngularVelocity(this._btColliderObject), this._angularVelocity, true);
  4680. return this._angularVelocity;
  4681. }
  4682. set angularVelocity(value) {
  4683. this._angularVelocity = value;
  4684. if (this._btColliderObject) {
  4685. var btValue = Rigidbody3D._btTempVector30;
  4686. Utils3D._convertToBulletVec3(value, btValue, true);
  4687. (this.isSleeping) && (this.wakeUp());
  4688. ILaya3D.Physics3D._bullet.btRigidBody_setAngularVelocity(this._btColliderObject, btValue);
  4689. }
  4690. }
  4691. get totalTorque() {
  4692. if (this._btColliderObject) {
  4693. var btTotalTorque = ILaya3D.Physics3D._bullet.btRigidBody_getTotalTorque(this._btColliderObject);
  4694. Utils3D._convertToLayaVec3(btTotalTorque, this._totalTorque, true);
  4695. return this._totalTorque;
  4696. }
  4697. return null;
  4698. }
  4699. get detectCollisions() {
  4700. return this._detectCollisions;
  4701. }
  4702. set detectCollisions(value) {
  4703. if (this._detectCollisions !== value) {
  4704. this._detectCollisions = value;
  4705. if (this._colliderShape && this._enabled && this._simulation) {
  4706. this._simulation._removeRigidBody(this);
  4707. this._simulation._addRigidBody(this, this._collisionGroup, value ? this._canCollideWith : 0);
  4708. }
  4709. }
  4710. }
  4711. get isSleeping() {
  4712. if (this._btColliderObject)
  4713. return ILaya3D.Physics3D._bullet.btCollisionObject_getActivationState(this._btColliderObject) === PhysicsComponent.ACTIVATIONSTATE_ISLAND_SLEEPING;
  4714. return false;
  4715. }
  4716. get sleepLinearVelocity() {
  4717. return ILaya3D.Physics3D._bullet.btRigidBody_getLinearSleepingThreshold(this._btColliderObject);
  4718. }
  4719. set sleepLinearVelocity(value) {
  4720. var bt = ILaya3D.Physics3D._bullet;
  4721. bt.btRigidBody_setSleepingThresholds(this._btColliderObject, value, bt.btRigidBody_getAngularSleepingThreshold(this._btColliderObject));
  4722. }
  4723. get sleepAngularVelocity() {
  4724. return ILaya3D.Physics3D._bullet.btRigidBody_getAngularSleepingThreshold(this._btColliderObject);
  4725. }
  4726. set sleepAngularVelocity(value) {
  4727. var bt = ILaya3D.Physics3D._bullet;
  4728. bt.btRigidBody_setSleepingThresholds(this._btColliderObject, bt.btRigidBody_getLinearSleepingThreshold(this._btColliderObject), value);
  4729. }
  4730. get btColliderObject() {
  4731. return this._btColliderObject;
  4732. }
  4733. set constaintRigidbodyA(value) {
  4734. this._constaintRigidbodyA = value;
  4735. }
  4736. get constaintRigidbodyA() {
  4737. return this._constaintRigidbodyA;
  4738. }
  4739. set constaintRigidbodyB(value) {
  4740. this._constaintRigidbodyB = value;
  4741. }
  4742. get constaintRigidbodyB() {
  4743. return this._constaintRigidbodyB;
  4744. }
  4745. _updateMass(mass) {
  4746. if (this._btColliderObject && this._colliderShape) {
  4747. var bt = ILaya3D.Physics3D._bullet;
  4748. bt.btCollisionShape_calculateLocalInertia(this._colliderShape._btShape, mass, Rigidbody3D._btInertia);
  4749. bt.btRigidBody_setMassProps(this._btColliderObject, mass, Rigidbody3D._btInertia);
  4750. bt.btRigidBody_updateInertiaTensor(this._btColliderObject);
  4751. }
  4752. }
  4753. _onScaleChange(scale) {
  4754. super._onScaleChange(scale);
  4755. this._updateMass(this._isKinematic ? 0 : this._mass);
  4756. }
  4757. _derivePhysicsTransformation(force) {
  4758. var bt = ILaya3D.Physics3D._bullet;
  4759. var btColliderObject = this._btColliderObject;
  4760. var oriTransform = bt.btCollisionObject_getWorldTransform(btColliderObject);
  4761. var transform = Rigidbody3D._btTransform0;
  4762. bt.btTransform_equal(transform, oriTransform);
  4763. this._innerDerivePhysicsTransformation(transform, force);
  4764. bt.btRigidBody_setCenterOfMassTransform(btColliderObject, transform);
  4765. }
  4766. _onAdded() {
  4767. var bt = ILaya3D.Physics3D._bullet;
  4768. var motionState = bt.layaMotionState_create();
  4769. bt.layaMotionState_set_rigidBodyID(motionState, this._id);
  4770. this._btLayaMotionState = motionState;
  4771. var constructInfo = bt.btRigidBodyConstructionInfo_create(0.0, motionState, null, Rigidbody3D._btVector3Zero);
  4772. var btRigid = bt.btRigidBody_create(constructInfo);
  4773. bt.btCollisionObject_setUserIndex(btRigid, this.id);
  4774. this._btColliderObject = btRigid;
  4775. super._onAdded();
  4776. this.mass = this._mass;
  4777. this.linearFactor = this._linearFactor;
  4778. this.angularFactor = this._angularFactor;
  4779. this.linearDamping = this._linearDamping;
  4780. this.angularDamping = this._angularDamping;
  4781. this.overrideGravity = this._overrideGravity;
  4782. this.gravity = this._gravity;
  4783. this.isKinematic = this._isKinematic;
  4784. bt.btRigidBodyConstructionInfo_destroy(constructInfo);
  4785. }
  4786. _onEnable() {
  4787. super._onEnable();
  4788. if (this._constaintRigidbodyA) {
  4789. if (this._constaintRigidbodyA.connectedBody._simulation) {
  4790. this._constaintRigidbodyA._createConstraint();
  4791. this._constaintRigidbodyA._onEnable();
  4792. }
  4793. }
  4794. if (this._constaintRigidbodyB) {
  4795. if (this._constaintRigidbodyB.ownBody._simulation) {
  4796. this._constaintRigidbodyB._createConstraint();
  4797. this._constaintRigidbodyB._onEnable();
  4798. }
  4799. }
  4800. }
  4801. _onShapeChange(colShape) {
  4802. super._onShapeChange(colShape);
  4803. if (this._isKinematic) {
  4804. this._updateMass(0);
  4805. }
  4806. else {
  4807. var bt = ILaya3D.Physics3D._bullet;
  4808. bt.btRigidBody_setCenterOfMassTransform(this._btColliderObject, bt.btCollisionObject_getWorldTransform(this._btColliderObject));
  4809. this._updateMass(this._mass);
  4810. }
  4811. }
  4812. _parse(data) {
  4813. (data.friction != null) && (this.friction = data.friction);
  4814. (data.rollingFriction != null) && (this.rollingFriction = data.rollingFriction);
  4815. (data.restitution != null) && (this.restitution = data.restitution);
  4816. (data.isTrigger != null) && (this.isTrigger = data.isTrigger);
  4817. (data.mass != null) && (this.mass = data.mass);
  4818. (data.linearDamping != null) && (this.linearDamping = data.linearDamping);
  4819. (data.angularDamping != null) && (this.angularDamping = data.angularDamping);
  4820. (data.overrideGravity != null) && (this.overrideGravity = data.overrideGravity);
  4821. if (data.linearFactor != null) {
  4822. var linFac = this.linearFactor;
  4823. linFac.fromArray(data.linearFactor);
  4824. this.linearFactor = linFac;
  4825. }
  4826. if (data.angularFactor != null) {
  4827. var angFac = this.angularFactor;
  4828. angFac.fromArray(data.angularFactor);
  4829. this.angularFactor = angFac;
  4830. }
  4831. if (data.gravity) {
  4832. this.gravity.fromArray(data.gravity);
  4833. this.gravity = this.gravity;
  4834. }
  4835. super._parse(data);
  4836. this._parseShape(data.shapes);
  4837. (data.isKinematic != null) && (this._isKinematic = data.isKinematic);
  4838. }
  4839. _onDestroy() {
  4840. ILaya3D.Physics3D._bullet.btMotionState_destroy(this._btLayaMotionState);
  4841. super._onDestroy();
  4842. this._btLayaMotionState = null;
  4843. this._gravity = null;
  4844. this._totalTorque = null;
  4845. this._linearVelocity = null;
  4846. this._angularVelocity = null;
  4847. this._linearFactor = null;
  4848. this._angularFactor = null;
  4849. if (this.constaintRigidbodyA)
  4850. this.constaintRigidbodyA._breakConstrained();
  4851. if (this.constaintRigidbodyB) {
  4852. this.constaintRigidbodyB.connectedBody = null;
  4853. this.constaintRigidbodyB._onDisable();
  4854. }
  4855. }
  4856. _addToSimulation() {
  4857. this._simulation._addRigidBody(this, this._collisionGroup, this._detectCollisions ? this._canCollideWith : 0);
  4858. }
  4859. _removeFromSimulation() {
  4860. this._simulation._removeRigidBody(this);
  4861. }
  4862. _cloneTo(dest) {
  4863. super._cloneTo(dest);
  4864. var destRigidbody3D = dest;
  4865. destRigidbody3D.isKinematic = this._isKinematic;
  4866. destRigidbody3D.mass = this._mass;
  4867. destRigidbody3D.gravity = this._gravity;
  4868. destRigidbody3D.angularDamping = this._angularDamping;
  4869. destRigidbody3D.linearDamping = this._linearDamping;
  4870. destRigidbody3D.overrideGravity = this._overrideGravity;
  4871. destRigidbody3D.linearVelocity = this._linearVelocity;
  4872. destRigidbody3D.angularVelocity = this._angularVelocity;
  4873. destRigidbody3D.linearFactor = this._linearFactor;
  4874. destRigidbody3D.angularFactor = this._angularFactor;
  4875. destRigidbody3D.detectCollisions = this._detectCollisions;
  4876. }
  4877. applyForce(force, localOffset = null) {
  4878. if (this._btColliderObject == null)
  4879. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4880. var bt = ILaya3D.Physics3D._bullet;
  4881. var btForce = Rigidbody3D._btTempVector30;
  4882. bt.btVector3_setValue(btForce, -force.x, force.y, force.z);
  4883. if (localOffset) {
  4884. var btOffset = Rigidbody3D._btTempVector31;
  4885. bt.btVector3_setValue(btOffset, -localOffset.x, localOffset.y, localOffset.z);
  4886. bt.btRigidBody_applyForce(this._btColliderObject, btForce, btOffset);
  4887. }
  4888. else {
  4889. bt.btRigidBody_applyCentralForce(this._btColliderObject, btForce);
  4890. }
  4891. }
  4892. applyTorque(torque) {
  4893. if (this._btColliderObject == null)
  4894. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4895. var bullet = ILaya3D.Physics3D._bullet;
  4896. var btTorque = Rigidbody3D._btTempVector30;
  4897. bullet.btVector3_setValue(btTorque, -torque.x, torque.y, torque.z);
  4898. bullet.btRigidBody_applyTorque(this._btColliderObject, btTorque);
  4899. }
  4900. applyImpulse(impulse, localOffset = null) {
  4901. if (this._btColliderObject == null)
  4902. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4903. var bt = ILaya3D.Physics3D._bullet;
  4904. bt.btVector3_setValue(Rigidbody3D._btImpulse, -impulse.x, impulse.y, impulse.z);
  4905. if (localOffset) {
  4906. bt.btVector3_setValue(Rigidbody3D._btImpulseOffset, -localOffset.x, localOffset.y, localOffset.z);
  4907. bt.btRigidBody_applyImpulse(this._btColliderObject, Rigidbody3D._btImpulse, Rigidbody3D._btImpulseOffset);
  4908. }
  4909. else {
  4910. bt.btRigidBody_applyCentralImpulse(this._btColliderObject, Rigidbody3D._btImpulse);
  4911. }
  4912. }
  4913. applyTorqueImpulse(torqueImpulse) {
  4914. if (this._btColliderObject == null)
  4915. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4916. var bt = ILaya3D.Physics3D._bullet;
  4917. var btTorqueImpulse = Rigidbody3D._btTempVector30;
  4918. bt.btVector3_setValue(btTorqueImpulse, -torqueImpulse.x, torqueImpulse.y, torqueImpulse.z);
  4919. bt.btRigidBody_applyTorqueImpulse(this._btColliderObject, btTorqueImpulse);
  4920. }
  4921. wakeUp() {
  4922. this._btColliderObject && (ILaya3D.Physics3D._bullet.btCollisionObject_activate(this._btColliderObject, false));
  4923. }
  4924. clearForces() {
  4925. var rigidBody = this._btColliderObject;
  4926. if (rigidBody == null)
  4927. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4928. var bt = ILaya3D.Physics3D._bullet;
  4929. bt.btRigidBody_clearForces(rigidBody);
  4930. var btZero = Rigidbody3D._btVector3Zero;
  4931. bt.btCollisionObject_setInterpolationLinearVelocity(rigidBody, btZero);
  4932. bt.btRigidBody_setLinearVelocity(rigidBody, btZero);
  4933. bt.btCollisionObject_setInterpolationAngularVelocity(rigidBody, btZero);
  4934. bt.btRigidBody_setAngularVelocity(rigidBody, btZero);
  4935. }
  4936. }
  4937. Rigidbody3D.TYPE_STATIC = 0;
  4938. Rigidbody3D.TYPE_DYNAMIC = 1;
  4939. Rigidbody3D.TYPE_KINEMATIC = 2;
  4940. Rigidbody3D._BT_DISABLE_WORLD_GRAVITY = 1;
  4941. Rigidbody3D._BT_ENABLE_GYROPSCOPIC_FORCE = 2;
  4942. class Physics3D {
  4943. static __bulletinit__() {
  4944. this._bullet = window.Physics3D;
  4945. if (this._bullet) {
  4946. StaticPlaneColliderShape.__init__();
  4947. ColliderShape.__init__();
  4948. CompoundColliderShape.__init__();
  4949. PhysicsComponent.__init__();
  4950. PhysicsSimulation.__init__();
  4951. BoxColliderShape.__init__();
  4952. CylinderColliderShape.__init__();
  4953. CharacterController.__init__();
  4954. Rigidbody3D.__init__();
  4955. }
  4956. }
  4957. static __cannoninit__() {
  4958. this._cannon = window.CANNON;
  4959. if (!this._cannon)
  4960. return;
  4961. Laya.CannonColliderShape.__init__();
  4962. Laya.CannonPhysicsComponent.__init__();
  4963. Laya.CannonPhysicsSimulation.__init__();
  4964. Laya.CannonBoxColliderShape.__init__();
  4965. Laya.CannonRigidbody3D.__init__();
  4966. }
  4967. }
  4968. Physics3D._bullet = null;
  4969. Physics3D._cannon = null;
  4970. Physics3D._enablePhysics = false;
  4971. class Config3D {
  4972. constructor() {
  4973. this._defaultPhysicsMemory = 16;
  4974. this._maxLightCount = 32;
  4975. this._lightClusterCount = new Vector3(12, 12, 12);
  4976. this._editerEnvironment = false;
  4977. this.isAntialias = true;
  4978. this.isAlpha = false;
  4979. this.premultipliedAlpha = true;
  4980. this.isStencil = true;
  4981. this.enableMultiLight = true;
  4982. this.octreeCulling = false;
  4983. this.octreeInitialSize = 64.0;
  4984. this.octreeInitialCenter = new Vector3(0, 0, 0);
  4985. this.octreeMinNodeSize = 2.0;
  4986. this.octreeLooseness = 1.25;
  4987. this.debugFrustumCulling = false;
  4988. this.pbrRenderQuality = exports.PBRRenderQuality.High;
  4989. this.isUseCannonPhysicsEngine = false;
  4990. this._maxAreaLightCountPerClusterAverage = Math.min(Math.floor(2048 / this._lightClusterCount.z - 1) * 4, this._maxLightCount);
  4991. }
  4992. static get useCannonPhysics() {
  4993. return Config3D._config.isUseCannonPhysicsEngine;
  4994. }
  4995. static set useCannonPhysics(value) {
  4996. Config3D._config.isUseCannonPhysicsEngine = value;
  4997. if (value) {
  4998. Physics3D.__cannoninit__();
  4999. if (!ILaya3D.Scene3D.cannonPhysicsSettings)
  5000. ILaya3D.Scene3D.cannonPhysicsSettings = new Laya.CannonPhysicsSettings();
  5001. }
  5002. }
  5003. get defaultPhysicsMemory() {
  5004. return this._defaultPhysicsMemory;
  5005. }
  5006. set defaultPhysicsMemory(value) {
  5007. if (value < 16)
  5008. throw "defaultPhysicsMemory must large than 16M";
  5009. this._defaultPhysicsMemory = value;
  5010. }
  5011. get maxLightCount() {
  5012. return this._maxLightCount;
  5013. }
  5014. set maxLightCount(value) {
  5015. if (value > 2048) {
  5016. this._maxLightCount = 2048;
  5017. console.warn("Config3D: maxLightCount must less equal 2048.");
  5018. }
  5019. else {
  5020. this._maxLightCount = value;
  5021. }
  5022. }
  5023. get lightClusterCount() {
  5024. return this._lightClusterCount;
  5025. }
  5026. set lightClusterCount(value) {
  5027. if (value.x > 128 || value.y > 128 || value.z > 128) {
  5028. this._lightClusterCount.setValue(Math.min(value.x, 128), Math.min(value.y, 128), Math.min(value.z, 128));
  5029. console.warn("Config3D: lightClusterCount X and Y、Z must less equal 128.");
  5030. }
  5031. else {
  5032. value.cloneTo(this._lightClusterCount);
  5033. }
  5034. var maxAreaLightCountWithZ = Math.floor(2048 / this._lightClusterCount.z - 1) * 4;
  5035. if (maxAreaLightCountWithZ < this._maxLightCount)
  5036. console.warn("Config3D: if the area light(PointLight、SpotLight) count is large than " + maxAreaLightCountWithZ + ",maybe the far away culster will ingonre some light.");
  5037. this._maxAreaLightCountPerClusterAverage = Math.min(maxAreaLightCountWithZ, this._maxLightCount);
  5038. }
  5039. cloneTo(dest) {
  5040. var destConfig3D = dest;
  5041. destConfig3D._defaultPhysicsMemory = this._defaultPhysicsMemory;
  5042. destConfig3D._editerEnvironment = this._editerEnvironment;
  5043. destConfig3D.isAntialias = this.isAntialias;
  5044. destConfig3D.isAlpha = this.isAlpha;
  5045. destConfig3D.premultipliedAlpha = this.premultipliedAlpha;
  5046. destConfig3D.isStencil = this.isStencil;
  5047. destConfig3D.octreeCulling = this.octreeCulling;
  5048. this.octreeInitialCenter.cloneTo(destConfig3D.octreeInitialCenter);
  5049. destConfig3D.octreeInitialSize = this.octreeInitialSize;
  5050. destConfig3D.octreeMinNodeSize = this.octreeMinNodeSize;
  5051. destConfig3D.octreeLooseness = this.octreeLooseness;
  5052. destConfig3D.debugFrustumCulling = this.debugFrustumCulling;
  5053. destConfig3D.maxLightCount = this.maxLightCount;
  5054. destConfig3D.enableMultiLight = this.enableMultiLight;
  5055. var lightClusterCount = destConfig3D.lightClusterCount;
  5056. this.lightClusterCount.cloneTo(lightClusterCount);
  5057. destConfig3D.lightClusterCount = lightClusterCount;
  5058. destConfig3D.pbrRenderQuality = this.pbrRenderQuality;
  5059. }
  5060. clone() {
  5061. var dest = new Config3D();
  5062. this.cloneTo(dest);
  5063. return dest;
  5064. }
  5065. }
  5066. Config3D._config = new Config3D();
  5067. window.Config3D = Config3D;
  5068. class KeyframeNode {
  5069. constructor() {
  5070. this._ownerPath = [];
  5071. this._propertys = [];
  5072. this._keyFrames = [];
  5073. }
  5074. get ownerPathCount() {
  5075. return this._ownerPath.length;
  5076. }
  5077. get propertyCount() {
  5078. return this._propertys.length;
  5079. }
  5080. get keyFramesCount() {
  5081. return this._keyFrames.length;
  5082. }
  5083. _setOwnerPathCount(value) {
  5084. this._ownerPath.length = value;
  5085. }
  5086. _setOwnerPathByIndex(index, value) {
  5087. this._ownerPath[index] = value;
  5088. }
  5089. _joinOwnerPath(sep) {
  5090. return this._ownerPath.join(sep);
  5091. }
  5092. _setPropertyCount(value) {
  5093. this._propertys.length = value;
  5094. }
  5095. _setPropertyByIndex(index, value) {
  5096. this._propertys[index] = value;
  5097. }
  5098. _joinProperty(sep) {
  5099. return this._propertys.join(sep);
  5100. }
  5101. _setKeyframeCount(value) {
  5102. this._keyFrames.length = value;
  5103. }
  5104. _setKeyframeByIndex(index, value) {
  5105. this._keyFrames[index] = value;
  5106. }
  5107. getOwnerPathByIndex(index) {
  5108. return this._ownerPath[index];
  5109. }
  5110. getPropertyByIndex(index) {
  5111. return this._propertys[index];
  5112. }
  5113. getKeyframeByIndex(index) {
  5114. return this._keyFrames[index];
  5115. }
  5116. }
  5117. class AnimationEvent {
  5118. constructor() {
  5119. }
  5120. }
  5121. class Keyframe {
  5122. constructor() {
  5123. }
  5124. cloneTo(destObject) {
  5125. var destKeyFrame = destObject;
  5126. destKeyFrame.time = this.time;
  5127. }
  5128. clone() {
  5129. var dest = new Keyframe();
  5130. this.cloneTo(dest);
  5131. return dest;
  5132. }
  5133. }
  5134. class FloatKeyframe extends Keyframe {
  5135. constructor() {
  5136. super();
  5137. }
  5138. cloneTo(destObject) {
  5139. super.cloneTo(destObject);
  5140. var destKeyFrame = destObject;
  5141. destKeyFrame.inTangent = this.inTangent;
  5142. destKeyFrame.outTangent = this.outTangent;
  5143. destKeyFrame.value = this.value;
  5144. }
  5145. }
  5146. class QuaternionKeyframe extends Keyframe {
  5147. constructor() {
  5148. super();
  5149. this.inTangent = new Vector4();
  5150. this.outTangent = new Vector4();
  5151. this.value = new Quaternion();
  5152. }
  5153. cloneTo(dest) {
  5154. super.cloneTo(dest);
  5155. var destKeyFarme = dest;
  5156. this.inTangent.cloneTo(destKeyFarme.inTangent);
  5157. this.outTangent.cloneTo(destKeyFarme.outTangent);
  5158. this.value.cloneTo(destKeyFarme.value);
  5159. }
  5160. }
  5161. class Vector3Keyframe extends Keyframe {
  5162. constructor() {
  5163. super();
  5164. this.inTangent = new Vector3();
  5165. this.outTangent = new Vector3();
  5166. this.value = new Vector3();
  5167. }
  5168. cloneTo(dest) {
  5169. super.cloneTo(dest);
  5170. var destKeyFarme = dest;
  5171. this.inTangent.cloneTo(destKeyFarme.inTangent);
  5172. this.outTangent.cloneTo(destKeyFarme.outTangent);
  5173. this.value.cloneTo(destKeyFarme.value);
  5174. }
  5175. }
  5176. class AnimationClipParser03 {
  5177. static READ_DATA() {
  5178. AnimationClipParser03._DATA.offset = AnimationClipParser03._reader.getUint32();
  5179. AnimationClipParser03._DATA.size = AnimationClipParser03._reader.getUint32();
  5180. }
  5181. static READ_BLOCK() {
  5182. var count = AnimationClipParser03._BLOCK.count = AnimationClipParser03._reader.getUint16();
  5183. var blockStarts = AnimationClipParser03._BLOCK.blockStarts = [];
  5184. var blockLengths = AnimationClipParser03._BLOCK.blockLengths = [];
  5185. for (var i = 0; i < count; i++) {
  5186. blockStarts.push(AnimationClipParser03._reader.getUint32());
  5187. blockLengths.push(AnimationClipParser03._reader.getUint32());
  5188. }
  5189. }
  5190. static READ_STRINGS() {
  5191. var offset = AnimationClipParser03._reader.getUint32();
  5192. var count = AnimationClipParser03._reader.getUint16();
  5193. var prePos = AnimationClipParser03._reader.pos;
  5194. AnimationClipParser03._reader.pos = offset + AnimationClipParser03._DATA.offset;
  5195. for (var i = 0; i < count; i++)
  5196. AnimationClipParser03._strings[i] = AnimationClipParser03._reader.readUTFString();
  5197. AnimationClipParser03._reader.pos = prePos;
  5198. }
  5199. static parse(clip, reader) {
  5200. AnimationClipParser03._animationClip = clip;
  5201. AnimationClipParser03._reader = reader;
  5202. var arrayBuffer = reader.__getBuffer();
  5203. AnimationClipParser03.READ_DATA();
  5204. AnimationClipParser03.READ_BLOCK();
  5205. AnimationClipParser03.READ_STRINGS();
  5206. for (var i = 0, n = AnimationClipParser03._BLOCK.count; i < n; i++) {
  5207. var index = reader.getUint16();
  5208. var blockName = AnimationClipParser03._strings[index];
  5209. var fn = AnimationClipParser03["READ_" + blockName];
  5210. if (fn == null)
  5211. throw new Error("model file err,no this function:" + index + " " + blockName);
  5212. else
  5213. fn.call(null);
  5214. }
  5215. }
  5216. static READ_ANIMATIONS() {
  5217. var i, j;
  5218. var node;
  5219. var reader = AnimationClipParser03._reader;
  5220. var buffer = reader.__getBuffer();
  5221. var startTimeTypes = [];
  5222. var startTimeTypeCount = reader.getUint16();
  5223. startTimeTypes.length = startTimeTypeCount;
  5224. for (i = 0; i < startTimeTypeCount; i++)
  5225. startTimeTypes[i] = reader.getFloat32();
  5226. var clip = AnimationClipParser03._animationClip;
  5227. clip.name = AnimationClipParser03._strings[reader.getUint16()];
  5228. var clipDur = clip._duration = reader.getFloat32();
  5229. clip.islooping = !!reader.getByte();
  5230. clip._frameRate = reader.getInt16();
  5231. var nodeCount = reader.getInt16();
  5232. var nodes = clip._nodes;
  5233. nodes.count = nodeCount;
  5234. var nodesMap = clip._nodesMap = {};
  5235. var nodesDic = clip._nodesDic = {};
  5236. for (i = 0; i < nodeCount; i++) {
  5237. node = new KeyframeNode();
  5238. nodes.setNodeByIndex(i, node);
  5239. node._indexInList = i;
  5240. var type = node.type = reader.getUint8();
  5241. var pathLength = reader.getUint16();
  5242. node._setOwnerPathCount(pathLength);
  5243. for (j = 0; j < pathLength; j++)
  5244. node._setOwnerPathByIndex(j, AnimationClipParser03._strings[reader.getUint16()]);
  5245. var nodePath = node._joinOwnerPath("/");
  5246. var mapArray = nodesMap[nodePath];
  5247. (mapArray) || (nodesMap[nodePath] = mapArray = []);
  5248. mapArray.push(node);
  5249. node.propertyOwner = AnimationClipParser03._strings[reader.getUint16()];
  5250. var propertyLength = reader.getUint16();
  5251. node._setPropertyCount(propertyLength);
  5252. for (j = 0; j < propertyLength; j++)
  5253. node._setPropertyByIndex(j, AnimationClipParser03._strings[reader.getUint16()]);
  5254. var fullPath = nodePath + "." + node.propertyOwner + "." + node._joinProperty(".");
  5255. nodesDic[fullPath] = node;
  5256. node.fullPath = fullPath;
  5257. var keyframeCount = reader.getUint16();
  5258. node._setKeyframeCount(keyframeCount);
  5259. var startTime;
  5260. for (j = 0; j < keyframeCount; j++) {
  5261. switch (type) {
  5262. case 0:
  5263. var floatKeyframe = new FloatKeyframe();
  5264. node._setKeyframeByIndex(j, floatKeyframe);
  5265. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  5266. floatKeyframe.inTangent = reader.getFloat32();
  5267. floatKeyframe.outTangent = reader.getFloat32();
  5268. floatKeyframe.value = reader.getFloat32();
  5269. break;
  5270. case 1:
  5271. case 3:
  5272. case 4:
  5273. var floatArrayKeyframe = new Vector3Keyframe();
  5274. node._setKeyframeByIndex(j, floatArrayKeyframe);
  5275. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  5276. if (Laya.Render.supportWebGLPlusAnimation) {
  5277. var data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  5278. for (var k = 0; k < 3; k++)
  5279. data[k] = reader.getFloat32();
  5280. for (k = 0; k < 3; k++)
  5281. data[3 + k] = reader.getFloat32();
  5282. for (k = 0; k < 3; k++)
  5283. data[6 + k] = reader.getFloat32();
  5284. }
  5285. else {
  5286. var inTangent = floatArrayKeyframe.inTangent;
  5287. var outTangent = floatArrayKeyframe.outTangent;
  5288. var value = floatArrayKeyframe.value;
  5289. inTangent.x = reader.getFloat32();
  5290. inTangent.y = reader.getFloat32();
  5291. inTangent.z = reader.getFloat32();
  5292. outTangent.x = reader.getFloat32();
  5293. outTangent.y = reader.getFloat32();
  5294. outTangent.z = reader.getFloat32();
  5295. value.x = reader.getFloat32();
  5296. value.y = reader.getFloat32();
  5297. value.z = reader.getFloat32();
  5298. }
  5299. break;
  5300. case 2:
  5301. var quaArrayKeyframe = new QuaternionKeyframe();
  5302. node._setKeyframeByIndex(j, quaArrayKeyframe);
  5303. startTime = quaArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  5304. if (Laya.Render.supportWebGLPlusAnimation) {
  5305. data = quaArrayKeyframe.data = new Float32Array(3 * 4);
  5306. for (k = 0; k < 4; k++)
  5307. data[k] = reader.getFloat32();
  5308. for (k = 0; k < 4; k++)
  5309. data[4 + k] = reader.getFloat32();
  5310. for (k = 0; k < 4; k++)
  5311. data[8 + k] = reader.getFloat32();
  5312. }
  5313. else {
  5314. var inTangentQua = quaArrayKeyframe.inTangent;
  5315. var outTangentQua = quaArrayKeyframe.outTangent;
  5316. var valueQua = quaArrayKeyframe.value;
  5317. inTangentQua.x = reader.getFloat32();
  5318. inTangentQua.y = reader.getFloat32();
  5319. inTangentQua.z = reader.getFloat32();
  5320. inTangentQua.w = reader.getFloat32();
  5321. outTangentQua.x = reader.getFloat32();
  5322. outTangentQua.y = reader.getFloat32();
  5323. outTangentQua.z = reader.getFloat32();
  5324. outTangentQua.w = reader.getFloat32();
  5325. valueQua.x = reader.getFloat32();
  5326. valueQua.y = reader.getFloat32();
  5327. valueQua.z = reader.getFloat32();
  5328. valueQua.w = reader.getFloat32();
  5329. }
  5330. break;
  5331. default:
  5332. throw "AnimationClipParser03:unknown type.";
  5333. }
  5334. }
  5335. }
  5336. var eventCount = reader.getUint16();
  5337. for (i = 0; i < eventCount; i++) {
  5338. var event = new AnimationEvent();
  5339. event.time = Math.min(clipDur, reader.getFloat32());
  5340. event.eventName = AnimationClipParser03._strings[reader.getUint16()];
  5341. var params;
  5342. var paramCount = reader.getUint16();
  5343. (paramCount > 0) && (event.params = params = []);
  5344. for (j = 0; j < paramCount; j++) {
  5345. var eventType = reader.getByte();
  5346. switch (eventType) {
  5347. case 0:
  5348. params.push(!!reader.getByte());
  5349. break;
  5350. case 1:
  5351. params.push(reader.getInt32());
  5352. break;
  5353. case 2:
  5354. params.push(reader.getFloat32());
  5355. break;
  5356. case 3:
  5357. params.push(AnimationClipParser03._strings[reader.getUint16()]);
  5358. break;
  5359. default:
  5360. throw new Error("unknown type.");
  5361. }
  5362. }
  5363. clip.addEvent(event);
  5364. }
  5365. }
  5366. }
  5367. AnimationClipParser03._strings = [];
  5368. AnimationClipParser03._BLOCK = { count: 0 };
  5369. AnimationClipParser03._DATA = { offset: 0, size: 0 };
  5370. class HalfFloatUtils {
  5371. static __init__() {
  5372. for (var i = 0; i < 256; ++i) {
  5373. var e = i - 127;
  5374. if (e < -27) {
  5375. HalfFloatUtils._baseTable[i | 0x000] = 0x0000;
  5376. HalfFloatUtils._baseTable[i | 0x100] = 0x8000;
  5377. HalfFloatUtils._shiftTable[i | 0x000] = 24;
  5378. HalfFloatUtils._shiftTable[i | 0x100] = 24;
  5379. }
  5380. else if (e < -14) {
  5381. HalfFloatUtils._baseTable[i | 0x000] = 0x0400 >> (-e - 14);
  5382. HalfFloatUtils._baseTable[i | 0x100] = (0x0400 >> (-e - 14)) | 0x8000;
  5383. HalfFloatUtils._shiftTable[i | 0x000] = -e - 1;
  5384. HalfFloatUtils._shiftTable[i | 0x100] = -e - 1;
  5385. }
  5386. else if (e <= 15) {
  5387. HalfFloatUtils._baseTable[i | 0x000] = (e + 15) << 10;
  5388. HalfFloatUtils._baseTable[i | 0x100] = ((e + 15) << 10) | 0x8000;
  5389. HalfFloatUtils._shiftTable[i | 0x000] = 13;
  5390. HalfFloatUtils._shiftTable[i | 0x100] = 13;
  5391. }
  5392. else if (e < 128) {
  5393. HalfFloatUtils._baseTable[i | 0x000] = 0x7c00;
  5394. HalfFloatUtils._baseTable[i | 0x100] = 0xfc00;
  5395. HalfFloatUtils._shiftTable[i | 0x000] = 24;
  5396. HalfFloatUtils._shiftTable[i | 0x100] = 24;
  5397. }
  5398. else {
  5399. HalfFloatUtils._baseTable[i | 0x000] = 0x7c00;
  5400. HalfFloatUtils._baseTable[i | 0x100] = 0xfc00;
  5401. HalfFloatUtils._shiftTable[i | 0x000] = 13;
  5402. HalfFloatUtils._shiftTable[i | 0x100] = 13;
  5403. }
  5404. }
  5405. HalfFloatUtils._mantissaTable[0] = 0;
  5406. for (i = 1; i < 1024; ++i) {
  5407. var m = i << 13;
  5408. e = 0;
  5409. while ((m & 0x00800000) === 0) {
  5410. e -= 0x00800000;
  5411. m <<= 1;
  5412. }
  5413. m &= ~0x00800000;
  5414. e += 0x38800000;
  5415. HalfFloatUtils._mantissaTable[i] = m | e;
  5416. }
  5417. for (i = 1024; i < 2048; ++i) {
  5418. HalfFloatUtils._mantissaTable[i] = 0x38000000 + ((i - 1024) << 13);
  5419. }
  5420. HalfFloatUtils._exponentTable[0] = 0;
  5421. for (i = 1; i < 31; ++i) {
  5422. HalfFloatUtils._exponentTable[i] = i << 23;
  5423. }
  5424. HalfFloatUtils._exponentTable[31] = 0x47800000;
  5425. HalfFloatUtils._exponentTable[32] = 0x80000000;
  5426. for (i = 33; i < 63; ++i) {
  5427. HalfFloatUtils._exponentTable[i] = 0x80000000 + ((i - 32) << 23);
  5428. }
  5429. HalfFloatUtils._exponentTable[63] = 0xc7800000;
  5430. HalfFloatUtils._offsetTable[0] = 0;
  5431. for (i = 1; i < 64; ++i) {
  5432. if (i === 32) {
  5433. HalfFloatUtils._offsetTable[i] = 0;
  5434. }
  5435. else {
  5436. HalfFloatUtils._offsetTable[i] = 1024;
  5437. }
  5438. }
  5439. }
  5440. static roundToFloat16Bits(num) {
  5441. HalfFloatUtils._floatView[0] = num;
  5442. var f = HalfFloatUtils._uint32View[0];
  5443. var e = (f >> 23) & 0x1ff;
  5444. return HalfFloatUtils._baseTable[e] + ((f & 0x007fffff) >> HalfFloatUtils._shiftTable[e]);
  5445. }
  5446. static convertToNumber(float16bits) {
  5447. var m = float16bits >> 10;
  5448. HalfFloatUtils._uint32View[0] = HalfFloatUtils._mantissaTable[HalfFloatUtils._offsetTable[m] + (float16bits & 0x3ff)] + HalfFloatUtils._exponentTable[m];
  5449. return HalfFloatUtils._floatView[0];
  5450. }
  5451. }
  5452. HalfFloatUtils._buffer = new ArrayBuffer(4);
  5453. HalfFloatUtils._floatView = new Float32Array(HalfFloatUtils._buffer);
  5454. HalfFloatUtils._uint32View = new Uint32Array(HalfFloatUtils._buffer);
  5455. HalfFloatUtils._baseTable = new Uint32Array(512);
  5456. HalfFloatUtils._shiftTable = new Uint32Array(512);
  5457. HalfFloatUtils._mantissaTable = new Uint32Array(2048);
  5458. HalfFloatUtils._exponentTable = new Uint32Array(64);
  5459. HalfFloatUtils._offsetTable = new Uint32Array(64);
  5460. class AnimationClipParser04 {
  5461. static READ_DATA() {
  5462. AnimationClipParser04._DATA.offset = AnimationClipParser04._reader.getUint32();
  5463. AnimationClipParser04._DATA.size = AnimationClipParser04._reader.getUint32();
  5464. }
  5465. static READ_BLOCK() {
  5466. var count = AnimationClipParser04._BLOCK.count = AnimationClipParser04._reader.getUint16();
  5467. var blockStarts = AnimationClipParser04._BLOCK.blockStarts = [];
  5468. var blockLengths = AnimationClipParser04._BLOCK.blockLengths = [];
  5469. for (var i = 0; i < count; i++) {
  5470. blockStarts.push(AnimationClipParser04._reader.getUint32());
  5471. blockLengths.push(AnimationClipParser04._reader.getUint32());
  5472. }
  5473. }
  5474. static READ_STRINGS() {
  5475. var offset = AnimationClipParser04._reader.getUint32();
  5476. var count = AnimationClipParser04._reader.getUint16();
  5477. var prePos = AnimationClipParser04._reader.pos;
  5478. AnimationClipParser04._reader.pos = offset + AnimationClipParser04._DATA.offset;
  5479. for (var i = 0; i < count; i++)
  5480. AnimationClipParser04._strings[i] = AnimationClipParser04._reader.readUTFString();
  5481. AnimationClipParser04._reader.pos = prePos;
  5482. }
  5483. static parse(clip, reader, version) {
  5484. AnimationClipParser04._animationClip = clip;
  5485. AnimationClipParser04._reader = reader;
  5486. AnimationClipParser04._version = version;
  5487. AnimationClipParser04.READ_DATA();
  5488. AnimationClipParser04.READ_BLOCK();
  5489. AnimationClipParser04.READ_STRINGS();
  5490. for (var i = 0, n = AnimationClipParser04._BLOCK.count; i < n; i++) {
  5491. var index = reader.getUint16();
  5492. var blockName = AnimationClipParser04._strings[index];
  5493. var fn = AnimationClipParser04["READ_" + blockName];
  5494. if (fn == null)
  5495. throw new Error("model file err,no this function:" + index + " " + blockName);
  5496. else
  5497. fn.call(null);
  5498. }
  5499. AnimationClipParser04._version = null;
  5500. AnimationClipParser04._reader = null;
  5501. AnimationClipParser04._animationClip = null;
  5502. }
  5503. static READ_ANIMATIONS() {
  5504. var i, j;
  5505. var node;
  5506. var reader = AnimationClipParser04._reader;
  5507. var buffer = reader.__getBuffer();
  5508. var startTimeTypes = [];
  5509. var startTimeTypeCount = reader.getUint16();
  5510. startTimeTypes.length = startTimeTypeCount;
  5511. for (i = 0; i < startTimeTypeCount; i++)
  5512. startTimeTypes[i] = reader.getFloat32();
  5513. var clip = AnimationClipParser04._animationClip;
  5514. clip.name = AnimationClipParser04._strings[reader.getUint16()];
  5515. var clipDur = clip._duration = reader.getFloat32();
  5516. clip.islooping = !!reader.getByte();
  5517. clip._frameRate = reader.getInt16();
  5518. var nodeCount = reader.getInt16();
  5519. var nodes = clip._nodes;
  5520. nodes.count = nodeCount;
  5521. var nodesMap = clip._nodesMap = {};
  5522. var nodesDic = clip._nodesDic = {};
  5523. for (i = 0; i < nodeCount; i++) {
  5524. node = new KeyframeNode();
  5525. nodes.setNodeByIndex(i, node);
  5526. node._indexInList = i;
  5527. var type = node.type = reader.getUint8();
  5528. var pathLength = reader.getUint16();
  5529. node._setOwnerPathCount(pathLength);
  5530. for (j = 0; j < pathLength; j++)
  5531. node._setOwnerPathByIndex(j, AnimationClipParser04._strings[reader.getUint16()]);
  5532. var nodePath = node._joinOwnerPath("/");
  5533. var mapArray = nodesMap[nodePath];
  5534. (mapArray) || (nodesMap[nodePath] = mapArray = []);
  5535. mapArray.push(node);
  5536. node.propertyOwner = AnimationClipParser04._strings[reader.getUint16()];
  5537. var propertyLength = reader.getUint16();
  5538. node._setPropertyCount(propertyLength);
  5539. for (j = 0; j < propertyLength; j++)
  5540. node._setPropertyByIndex(j, AnimationClipParser04._strings[reader.getUint16()]);
  5541. var fullPath = nodePath + "." + node.propertyOwner + "." + node._joinProperty(".");
  5542. nodesDic[fullPath] = node;
  5543. node.fullPath = fullPath;
  5544. var keyframeCount = reader.getUint16();
  5545. node._setKeyframeCount(keyframeCount);
  5546. var startTime;
  5547. switch (AnimationClipParser04._version) {
  5548. case "LAYAANIMATION:04":
  5549. for (j = 0; j < keyframeCount; j++) {
  5550. switch (type) {
  5551. case 0:
  5552. var floatKeyframe = new FloatKeyframe();
  5553. node._setKeyframeByIndex(j, floatKeyframe);
  5554. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  5555. floatKeyframe.inTangent = reader.getFloat32();
  5556. floatKeyframe.outTangent = reader.getFloat32();
  5557. floatKeyframe.value = reader.getFloat32();
  5558. break;
  5559. case 1:
  5560. case 3:
  5561. case 4:
  5562. var floatArrayKeyframe = new Vector3Keyframe();
  5563. node._setKeyframeByIndex(j, floatArrayKeyframe);
  5564. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  5565. if (Laya.Render.supportWebGLPlusAnimation) {
  5566. var data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  5567. for (var k = 0; k < 3; k++)
  5568. data[k] = reader.getFloat32();
  5569. for (k = 0; k < 3; k++)
  5570. data[3 + k] = reader.getFloat32();
  5571. for (k = 0; k < 3; k++)
  5572. data[6 + k] = reader.getFloat32();
  5573. }
  5574. else {
  5575. var inTangent = floatArrayKeyframe.inTangent;
  5576. var outTangent = floatArrayKeyframe.outTangent;
  5577. var value = floatArrayKeyframe.value;
  5578. inTangent.x = reader.getFloat32();
  5579. inTangent.y = reader.getFloat32();
  5580. inTangent.z = reader.getFloat32();
  5581. outTangent.x = reader.getFloat32();
  5582. outTangent.y = reader.getFloat32();
  5583. outTangent.z = reader.getFloat32();
  5584. value.x = reader.getFloat32();
  5585. value.y = reader.getFloat32();
  5586. value.z = reader.getFloat32();
  5587. }
  5588. break;
  5589. case 2:
  5590. var quaternionKeyframe = new QuaternionKeyframe();
  5591. node._setKeyframeByIndex(j, quaternionKeyframe);
  5592. startTime = quaternionKeyframe.time = startTimeTypes[reader.getUint16()];
  5593. if (Laya.Render.supportWebGLPlusAnimation) {
  5594. data = quaternionKeyframe.data = new Float32Array(3 * 4);
  5595. for (k = 0; k < 4; k++)
  5596. data[k] = reader.getFloat32();
  5597. for (k = 0; k < 4; k++)
  5598. data[4 + k] = reader.getFloat32();
  5599. for (k = 0; k < 4; k++)
  5600. data[8 + k] = reader.getFloat32();
  5601. }
  5602. else {
  5603. var inTangentQua = quaternionKeyframe.inTangent;
  5604. var outTangentQua = quaternionKeyframe.outTangent;
  5605. var valueQua = quaternionKeyframe.value;
  5606. inTangentQua.x = reader.getFloat32();
  5607. inTangentQua.y = reader.getFloat32();
  5608. inTangentQua.z = reader.getFloat32();
  5609. inTangentQua.w = reader.getFloat32();
  5610. outTangentQua.x = reader.getFloat32();
  5611. outTangentQua.y = reader.getFloat32();
  5612. outTangentQua.z = reader.getFloat32();
  5613. outTangentQua.w = reader.getFloat32();
  5614. valueQua.x = reader.getFloat32();
  5615. valueQua.y = reader.getFloat32();
  5616. valueQua.z = reader.getFloat32();
  5617. valueQua.w = reader.getFloat32();
  5618. }
  5619. break;
  5620. default:
  5621. throw "AnimationClipParser04:unknown type.";
  5622. }
  5623. }
  5624. break;
  5625. case "LAYAANIMATION:COMPRESSION_04":
  5626. for (j = 0; j < keyframeCount; j++) {
  5627. switch (type) {
  5628. case 0:
  5629. floatKeyframe = new FloatKeyframe();
  5630. node._setKeyframeByIndex(j, floatKeyframe);
  5631. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  5632. floatKeyframe.inTangent = HalfFloatUtils.convertToNumber(reader.getUint16());
  5633. floatKeyframe.outTangent = HalfFloatUtils.convertToNumber(reader.getUint16());
  5634. floatKeyframe.value = HalfFloatUtils.convertToNumber(reader.getUint16());
  5635. break;
  5636. case 1:
  5637. case 3:
  5638. case 4:
  5639. floatArrayKeyframe = new Vector3Keyframe();
  5640. node._setKeyframeByIndex(j, floatArrayKeyframe);
  5641. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  5642. if (Laya.Render.supportWebGLPlusAnimation) {
  5643. data = floatArrayKeyframe.data = new Float32Array(3 * 3);
  5644. for (k = 0; k < 3; k++)
  5645. data[k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  5646. for (k = 0; k < 3; k++)
  5647. data[3 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  5648. for (k = 0; k < 3; k++)
  5649. data[6 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  5650. }
  5651. else {
  5652. inTangent = floatArrayKeyframe.inTangent;
  5653. outTangent = floatArrayKeyframe.outTangent;
  5654. value = floatArrayKeyframe.value;
  5655. inTangent.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  5656. inTangent.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  5657. inTangent.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  5658. outTangent.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  5659. outTangent.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  5660. outTangent.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  5661. value.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  5662. value.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  5663. value.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  5664. }
  5665. break;
  5666. case 2:
  5667. quaternionKeyframe = new QuaternionKeyframe();
  5668. node._setKeyframeByIndex(j, quaternionKeyframe);
  5669. startTime = quaternionKeyframe.time = startTimeTypes[reader.getUint16()];
  5670. if (Laya.Render.supportWebGLPlusAnimation) {
  5671. data = quaternionKeyframe.data = new Float32Array(3 * 4);
  5672. for (k = 0; k < 4; k++)
  5673. data[k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  5674. for (k = 0; k < 4; k++)
  5675. data[4 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  5676. for (k = 0; k < 4; k++)
  5677. data[8 + k] = HalfFloatUtils.convertToNumber(reader.getUint16());
  5678. }
  5679. else {
  5680. inTangentQua = quaternionKeyframe.inTangent;
  5681. outTangentQua = quaternionKeyframe.outTangent;
  5682. valueQua = quaternionKeyframe.value;
  5683. inTangentQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  5684. inTangentQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  5685. inTangentQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  5686. inTangentQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  5687. outTangentQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  5688. outTangentQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  5689. outTangentQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  5690. outTangentQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  5691. valueQua.x = HalfFloatUtils.convertToNumber(reader.getUint16());
  5692. valueQua.y = HalfFloatUtils.convertToNumber(reader.getUint16());
  5693. valueQua.z = HalfFloatUtils.convertToNumber(reader.getUint16());
  5694. valueQua.w = HalfFloatUtils.convertToNumber(reader.getUint16());
  5695. }
  5696. break;
  5697. default:
  5698. throw "AnimationClipParser04:unknown type.";
  5699. }
  5700. }
  5701. break;
  5702. }
  5703. }
  5704. var eventCount = reader.getUint16();
  5705. for (i = 0; i < eventCount; i++) {
  5706. var event = new AnimationEvent();
  5707. event.time = Math.min(clipDur, reader.getFloat32());
  5708. event.eventName = AnimationClipParser04._strings[reader.getUint16()];
  5709. var params;
  5710. var paramCount = reader.getUint16();
  5711. (paramCount > 0) && (event.params = params = []);
  5712. for (j = 0; j < paramCount; j++) {
  5713. var eventType = reader.getByte();
  5714. switch (eventType) {
  5715. case 0:
  5716. params.push(!!reader.getByte());
  5717. break;
  5718. case 1:
  5719. params.push(reader.getInt32());
  5720. break;
  5721. case 2:
  5722. params.push(reader.getFloat32());
  5723. break;
  5724. case 3:
  5725. params.push(AnimationClipParser04._strings[reader.getUint16()]);
  5726. break;
  5727. default:
  5728. throw new Error("unknown type.");
  5729. }
  5730. }
  5731. clip.addEvent(event);
  5732. }
  5733. }
  5734. }
  5735. AnimationClipParser04._strings = [];
  5736. AnimationClipParser04._BLOCK = { count: 0 };
  5737. AnimationClipParser04._DATA = { offset: 0, size: 0 };
  5738. class KeyframeNodeList {
  5739. constructor() {
  5740. this._nodes = [];
  5741. }
  5742. get count() {
  5743. return this._nodes.length;
  5744. }
  5745. set count(value) {
  5746. this._nodes.length = value;
  5747. }
  5748. getNodeByIndex(index) {
  5749. return this._nodes[index];
  5750. }
  5751. setNodeByIndex(index, node) {
  5752. this._nodes[index] = node;
  5753. }
  5754. }
  5755. class AnimationClip extends Laya.Resource {
  5756. constructor() {
  5757. super();
  5758. this._nodes = new KeyframeNodeList();
  5759. this._animationEvents = [];
  5760. }
  5761. static _parse(data, propertyParams = null, constructParams = null) {
  5762. var clip = new AnimationClip();
  5763. var reader = new Laya.Byte(data);
  5764. var version = reader.readUTFString();
  5765. switch (version) {
  5766. case "LAYAANIMATION:03":
  5767. AnimationClipParser03.parse(clip, reader);
  5768. break;
  5769. case "LAYAANIMATION:04":
  5770. case "LAYAANIMATION:COMPRESSION_04":
  5771. AnimationClipParser04.parse(clip, reader, version);
  5772. break;
  5773. default:
  5774. throw "unknown animationClip version.";
  5775. }
  5776. return clip;
  5777. }
  5778. static load(url, complete) {
  5779. Laya.ILaya.loader.create(url, complete, null, AnimationClip.ANIMATIONCLIP);
  5780. }
  5781. duration() {
  5782. return this._duration;
  5783. }
  5784. _hermiteInterpolate(frame, nextFrame, t, dur) {
  5785. var t0 = frame.outTangent, t1 = nextFrame.inTangent;
  5786. if (Number.isFinite(t0) && Number.isFinite(t1)) {
  5787. var t2 = t * t;
  5788. var t3 = t2 * t;
  5789. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  5790. var b = t3 - 2.0 * t2 + t;
  5791. var c = t3 - t2;
  5792. var d = -2.0 * t3 + 3.0 * t2;
  5793. return a * frame.value + b * t0 * dur + c * t1 * dur + d * nextFrame.value;
  5794. }
  5795. else
  5796. return frame.value;
  5797. }
  5798. _hermiteInterpolateVector3(frame, nextFrame, t, dur, out) {
  5799. var p0 = frame.value;
  5800. var tan0 = frame.outTangent;
  5801. var p1 = nextFrame.value;
  5802. var tan1 = nextFrame.inTangent;
  5803. var t2 = t * t;
  5804. var t3 = t2 * t;
  5805. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  5806. var b = t3 - 2.0 * t2 + t;
  5807. var c = t3 - t2;
  5808. var d = -2.0 * t3 + 3.0 * t2;
  5809. var t0 = tan0.x, t1 = tan1.x;
  5810. if (Number.isFinite(t0) && Number.isFinite(t1))
  5811. out.x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x;
  5812. else
  5813. out.x = p0.x;
  5814. t0 = tan0.y, t1 = tan1.y;
  5815. if (Number.isFinite(t0) && Number.isFinite(t1))
  5816. out.y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y;
  5817. else
  5818. out.y = p0.y;
  5819. t0 = tan0.z, t1 = tan1.z;
  5820. if (Number.isFinite(t0) && Number.isFinite(t1))
  5821. out.z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z;
  5822. else
  5823. out.z = p0.z;
  5824. }
  5825. _hermiteInterpolateQuaternion(frame, nextFrame, t, dur, out) {
  5826. var p0 = frame.value;
  5827. var tan0 = frame.outTangent;
  5828. var p1 = nextFrame.value;
  5829. var tan1 = nextFrame.inTangent;
  5830. var t2 = t * t;
  5831. var t3 = t2 * t;
  5832. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  5833. var b = t3 - 2.0 * t2 + t;
  5834. var c = t3 - t2;
  5835. var d = -2.0 * t3 + 3.0 * t2;
  5836. var t0 = tan0.x, t1 = tan1.x;
  5837. if (Number.isFinite(t0) && Number.isFinite(t1))
  5838. out.x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x;
  5839. else
  5840. out.x = p0.x;
  5841. t0 = tan0.y, t1 = tan1.y;
  5842. if (Number.isFinite(t0) && Number.isFinite(t1))
  5843. out.y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y;
  5844. else
  5845. out.y = p0.y;
  5846. t0 = tan0.z, t1 = tan1.z;
  5847. if (Number.isFinite(t0) && Number.isFinite(t1))
  5848. out.z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z;
  5849. else
  5850. out.z = p0.z;
  5851. t0 = tan0.w, t1 = tan1.w;
  5852. if (Number.isFinite(t0) && Number.isFinite(t1))
  5853. out.w = a * p0.w + b * t0 * dur + c * t1 * dur + d * p1.w;
  5854. else
  5855. out.w = p0.w;
  5856. }
  5857. _evaluateClipDatasRealTime(nodes, playCurTime, realTimeCurrentFrameIndexes, addtive, frontPlay, outDatas) {
  5858. for (var i = 0, n = nodes.count; i < n; i++) {
  5859. var node = nodes.getNodeByIndex(i);
  5860. var type = node.type;
  5861. var nextFrameIndex;
  5862. var keyFrames = node._keyFrames;
  5863. var keyFramesCount = keyFrames.length;
  5864. var frameIndex = realTimeCurrentFrameIndexes[i];
  5865. if (frontPlay) {
  5866. if ((frameIndex !== -1) && (playCurTime < keyFrames[frameIndex].time)) {
  5867. frameIndex = -1;
  5868. realTimeCurrentFrameIndexes[i] = frameIndex;
  5869. }
  5870. nextFrameIndex = frameIndex + 1;
  5871. while (nextFrameIndex < keyFramesCount) {
  5872. if (keyFrames[nextFrameIndex].time > playCurTime)
  5873. break;
  5874. frameIndex++;
  5875. nextFrameIndex++;
  5876. realTimeCurrentFrameIndexes[i] = frameIndex;
  5877. }
  5878. }
  5879. else {
  5880. nextFrameIndex = frameIndex + 1;
  5881. if ((nextFrameIndex !== keyFramesCount) && (playCurTime > keyFrames[nextFrameIndex].time)) {
  5882. frameIndex = keyFramesCount - 1;
  5883. realTimeCurrentFrameIndexes[i] = frameIndex;
  5884. }
  5885. nextFrameIndex = frameIndex + 1;
  5886. while (frameIndex > -1) {
  5887. if (keyFrames[frameIndex].time < playCurTime)
  5888. break;
  5889. frameIndex--;
  5890. nextFrameIndex--;
  5891. realTimeCurrentFrameIndexes[i] = frameIndex;
  5892. }
  5893. }
  5894. var isEnd = nextFrameIndex === keyFramesCount;
  5895. switch (type) {
  5896. case 0:
  5897. if (frameIndex !== -1) {
  5898. var frame = keyFrames[frameIndex];
  5899. if (isEnd) {
  5900. outDatas[i] = frame.value;
  5901. }
  5902. else {
  5903. var nextFarme = keyFrames[nextFrameIndex];
  5904. var d = nextFarme.time - frame.time;
  5905. var t;
  5906. if (d !== 0)
  5907. t = (playCurTime - frame.time) / d;
  5908. else
  5909. t = 0;
  5910. outDatas[i] = this._hermiteInterpolate(frame, nextFarme, t, d);
  5911. }
  5912. }
  5913. else {
  5914. outDatas[i] = keyFrames[0].value;
  5915. }
  5916. if (addtive)
  5917. outDatas[i] = outDatas[i] - keyFrames[0].value;
  5918. break;
  5919. case 1:
  5920. case 4:
  5921. var clipData = outDatas[i];
  5922. this._evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipData);
  5923. if (addtive) {
  5924. var firstFrameValue = keyFrames[0].value;
  5925. clipData.x -= firstFrameValue.x;
  5926. clipData.y -= firstFrameValue.y;
  5927. clipData.z -= firstFrameValue.z;
  5928. }
  5929. break;
  5930. case 2:
  5931. var clipQuat = outDatas[i];
  5932. this._evaluateFrameNodeQuaternionDatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipQuat);
  5933. if (addtive) {
  5934. var tempQuat = AnimationClip._tempQuaternion0;
  5935. var firstFrameValueQua = keyFrames[0].value;
  5936. Utils3D.quaternionConjugate(firstFrameValueQua, tempQuat);
  5937. Quaternion.multiply(tempQuat, clipQuat, clipQuat);
  5938. }
  5939. break;
  5940. case 3:
  5941. clipData = outDatas[i];
  5942. this._evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipData);
  5943. if (addtive) {
  5944. firstFrameValue = keyFrames[0].value;
  5945. clipData.x /= firstFrameValue.x;
  5946. clipData.y /= firstFrameValue.y;
  5947. clipData.z /= firstFrameValue.z;
  5948. }
  5949. break;
  5950. default:
  5951. throw "AnimationClip:unknown node type.";
  5952. }
  5953. }
  5954. }
  5955. _evaluateClipDatasRealTimeForNative(nodes, playCurTime, realTimeCurrentFrameIndexes, addtive) {
  5956. Laya.LayaGL.instance.evaluateClipDatasRealTime(nodes._nativeObj, playCurTime, realTimeCurrentFrameIndexes, addtive);
  5957. }
  5958. _evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, outDatas) {
  5959. if (frameIndex !== -1) {
  5960. var frame = keyFrames[frameIndex];
  5961. if (isEnd) {
  5962. var frameData = frame.value;
  5963. outDatas.x = frameData.x;
  5964. outDatas.y = frameData.y;
  5965. outDatas.z = frameData.z;
  5966. }
  5967. else {
  5968. var nextKeyFrame = keyFrames[frameIndex + 1];
  5969. var t;
  5970. var startTime = frame.time;
  5971. var d = nextKeyFrame.time - startTime;
  5972. if (d !== 0)
  5973. t = (playCurTime - startTime) / d;
  5974. else
  5975. t = 0;
  5976. this._hermiteInterpolateVector3(frame, nextKeyFrame, t, d, outDatas);
  5977. }
  5978. }
  5979. else {
  5980. var firstFrameDatas = keyFrames[0].value;
  5981. outDatas.x = firstFrameDatas.x;
  5982. outDatas.y = firstFrameDatas.y;
  5983. outDatas.z = firstFrameDatas.z;
  5984. }
  5985. }
  5986. _evaluateFrameNodeQuaternionDatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, outDatas) {
  5987. if (frameIndex !== -1) {
  5988. var frame = keyFrames[frameIndex];
  5989. if (isEnd) {
  5990. var frameData = frame.value;
  5991. outDatas.x = frameData.x;
  5992. outDatas.y = frameData.y;
  5993. outDatas.z = frameData.z;
  5994. outDatas.w = frameData.w;
  5995. }
  5996. else {
  5997. var nextKeyFrame = keyFrames[frameIndex + 1];
  5998. var t;
  5999. var startTime = frame.time;
  6000. var d = nextKeyFrame.time - startTime;
  6001. if (d !== 0)
  6002. t = (playCurTime - startTime) / d;
  6003. else
  6004. t = 0;
  6005. this._hermiteInterpolateQuaternion(frame, nextKeyFrame, t, d, outDatas);
  6006. }
  6007. }
  6008. else {
  6009. var firstFrameDatas = keyFrames[0].value;
  6010. outDatas.x = firstFrameDatas.x;
  6011. outDatas.y = firstFrameDatas.y;
  6012. outDatas.z = firstFrameDatas.z;
  6013. outDatas.w = firstFrameDatas.w;
  6014. }
  6015. }
  6016. _binarySearchEventIndex(time) {
  6017. var start = 0;
  6018. var end = this._animationEvents.length - 1;
  6019. var mid;
  6020. while (start <= end) {
  6021. mid = Math.floor((start + end) / 2);
  6022. var midValue = this._animationEvents[mid].time;
  6023. if (midValue == time)
  6024. return mid;
  6025. else if (midValue > time)
  6026. end = mid - 1;
  6027. else
  6028. start = mid + 1;
  6029. }
  6030. return start;
  6031. }
  6032. addEvent(event) {
  6033. var index = this._binarySearchEventIndex(event.time);
  6034. this._animationEvents.splice(index, 0, event);
  6035. }
  6036. _disposeResource() {
  6037. this._nodes = null;
  6038. this._nodesMap = null;
  6039. }
  6040. }
  6041. AnimationClip.ANIMATIONCLIP = "ANIMATIONCLIP";
  6042. AnimationClip._tempQuaternion0 = new Quaternion();
  6043. class AnimatorPlayState {
  6044. constructor() {
  6045. this._currentState = null;
  6046. }
  6047. get normalizedTime() {
  6048. return this._normalizedTime;
  6049. }
  6050. get duration() {
  6051. return this._duration;
  6052. }
  6053. get animatorState() {
  6054. return this._currentState;
  6055. }
  6056. _resetPlayState(startTime) {
  6057. this._finish = false;
  6058. this._startPlayTime = startTime;
  6059. this._elapsedTime = startTime;
  6060. this._playEventIndex = 0;
  6061. this._lastIsFront = true;
  6062. }
  6063. _cloneTo(dest) {
  6064. dest._finish = this._finish;
  6065. dest._startPlayTime = this._startPlayTime;
  6066. dest._elapsedTime = this._elapsedTime;
  6067. dest._normalizedTime = this._normalizedTime;
  6068. dest._normalizedPlayTime = this._normalizedPlayTime;
  6069. dest._playEventIndex = this._playEventIndex;
  6070. dest._lastIsFront = this._lastIsFront;
  6071. }
  6072. }
  6073. class AnimatorControllerLayer {
  6074. constructor(name) {
  6075. this._defaultState = null;
  6076. this._referenceCount = 0;
  6077. this._playType = -1;
  6078. this._crossDuration = -1;
  6079. this._crossMark = 0;
  6080. this._crossNodesOwnersCount = 0;
  6081. this._crossNodesOwners = [];
  6082. this._crossNodesOwnersIndicesMap = {};
  6083. this._srcCrossClipNodeIndices = [];
  6084. this._destCrossClipNodeIndices = [];
  6085. this._statesMap = {};
  6086. this._states = [];
  6087. this._playStateInfo = new AnimatorPlayState();
  6088. this._crossPlayStateInfo = new AnimatorPlayState();
  6089. this.blendingMode = AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  6090. this.defaultWeight = 1.0;
  6091. this.playOnWake = true;
  6092. this.name = name;
  6093. }
  6094. get defaultState() {
  6095. return this._defaultState;
  6096. }
  6097. set defaultState(value) {
  6098. this._defaultState = value;
  6099. this._statesMap[value.name] = value;
  6100. }
  6101. _removeClip(clipStateInfos, statesMap, index, state) {
  6102. var clip = state._clip;
  6103. var clipStateInfo = clipStateInfos[index];
  6104. clipStateInfos.splice(index, 1);
  6105. delete statesMap[state.name];
  6106. if (this._animator) {
  6107. var frameNodes = clip._nodes;
  6108. var nodeOwners = clipStateInfo._nodeOwners;
  6109. clip._removeReference();
  6110. for (var i = 0, n = frameNodes.count; i < n; i++)
  6111. this._animator._removeKeyframeNodeOwner(nodeOwners, frameNodes.getNodeByIndex(i));
  6112. }
  6113. }
  6114. _getReferenceCount() {
  6115. return this._referenceCount;
  6116. }
  6117. _addReference(count = 1) {
  6118. for (var i = 0, n = this._states.length; i < n; i++)
  6119. this._states[i]._addReference(count);
  6120. this._referenceCount += count;
  6121. }
  6122. _removeReference(count = 1) {
  6123. for (var i = 0, n = this._states.length; i < n; i++)
  6124. this._states[i]._removeReference(count);
  6125. this._referenceCount -= count;
  6126. }
  6127. _clearReference() {
  6128. this._removeReference(-this._referenceCount);
  6129. }
  6130. getCurrentPlayState() {
  6131. return this._playStateInfo;
  6132. }
  6133. getAnimatorState(name) {
  6134. var state = this._statesMap[name];
  6135. return state ? state : null;
  6136. }
  6137. addState(state) {
  6138. var stateName = state.name;
  6139. if (this._statesMap[stateName]) {
  6140. throw "AnimatorControllerLayer:this stat's name has exist.";
  6141. }
  6142. else {
  6143. this._statesMap[stateName] = state;
  6144. this._states.push(state);
  6145. if (this._animator) {
  6146. state._clip._addReference();
  6147. this._animator._getOwnersByClip(state);
  6148. }
  6149. }
  6150. }
  6151. removeState(state) {
  6152. var states = this._states;
  6153. var index = -1;
  6154. for (var i = 0, n = states.length; i < n; i++) {
  6155. if (states[i] === state) {
  6156. index = i;
  6157. break;
  6158. }
  6159. }
  6160. if (index !== -1)
  6161. this._removeClip(states, this._statesMap, index, state);
  6162. }
  6163. destroy() {
  6164. this._clearReference();
  6165. this._statesMap = null;
  6166. this._states = null;
  6167. this._playStateInfo = null;
  6168. this._crossPlayStateInfo = null;
  6169. this._defaultState = null;
  6170. }
  6171. cloneTo(destObject) {
  6172. var dest = destObject;
  6173. dest.name = this.name;
  6174. dest.blendingMode = this.blendingMode;
  6175. dest.defaultWeight = this.defaultWeight;
  6176. dest.playOnWake = this.playOnWake;
  6177. }
  6178. clone() {
  6179. var dest = new AnimatorControllerLayer(this.name);
  6180. this.cloneTo(dest);
  6181. return dest;
  6182. }
  6183. }
  6184. AnimatorControllerLayer.BLENDINGMODE_OVERRIDE = 0;
  6185. AnimatorControllerLayer.BLENDINGMODE_ADDTIVE = 1;
  6186. class ConchVector4 {
  6187. constructor(x = 0, y = 0, z = 0, w = 0) {
  6188. var v = this.elements = new Float32Array(4);
  6189. v[0] = x;
  6190. v[1] = y;
  6191. v[2] = z;
  6192. v[3] = w;
  6193. }
  6194. get x() {
  6195. return this.elements[0];
  6196. }
  6197. set x(value) {
  6198. this.elements[0] = value;
  6199. }
  6200. get y() {
  6201. return this.elements[1];
  6202. }
  6203. set y(value) {
  6204. this.elements[1] = value;
  6205. }
  6206. get z() {
  6207. return this.elements[2];
  6208. }
  6209. set z(value) {
  6210. this.elements[2] = value;
  6211. }
  6212. get w() {
  6213. return this.elements[3];
  6214. }
  6215. set w(value) {
  6216. this.elements[3] = value;
  6217. }
  6218. fromArray(array, offset = 0) {
  6219. this.elements[0] = array[offset + 0];
  6220. this.elements[1] = array[offset + 1];
  6221. this.elements[2] = array[offset + 2];
  6222. this.elements[3] = array[offset + 3];
  6223. }
  6224. cloneTo(destObject) {
  6225. var destVector4 = destObject;
  6226. var destE = destVector4.elements;
  6227. var s = this.elements;
  6228. destE[0] = s[0];
  6229. destE[1] = s[1];
  6230. destE[2] = s[2];
  6231. destE[3] = s[3];
  6232. }
  6233. clone() {
  6234. var destVector4 = new ConchVector4();
  6235. this.cloneTo(destVector4);
  6236. return destVector4;
  6237. }
  6238. static lerp(a, b, t, out) {
  6239. var e = out.elements;
  6240. var f = a.elements;
  6241. var g = b.elements;
  6242. var ax = f[0], ay = f[1], az = f[2], aw = f[3];
  6243. e[0] = ax + t * (g[0] - ax);
  6244. e[1] = ay + t * (g[1] - ay);
  6245. e[2] = az + t * (g[2] - az);
  6246. e[3] = aw + t * (g[3] - aw);
  6247. }
  6248. static transformByM4x4(vector4, m4x4, out) {
  6249. var ve = vector4.elements;
  6250. var vx = ve[0];
  6251. var vy = ve[1];
  6252. var vz = ve[2];
  6253. var vw = ve[3];
  6254. var me = m4x4.elements;
  6255. var oe = out.elements;
  6256. oe[0] = vx * me[0] + vy * me[4] + vz * me[8] + vw * me[12];
  6257. oe[1] = vx * me[1] + vy * me[5] + vz * me[9] + vw * me[13];
  6258. oe[2] = vx * me[2] + vy * me[6] + vz * me[10] + vw * me[14];
  6259. oe[3] = vx * me[3] + vy * me[7] + vz * me[11] + vw * me[15];
  6260. }
  6261. static equals(a, b) {
  6262. var ae = a.elements;
  6263. var be = b.elements;
  6264. 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]));
  6265. }
  6266. length() {
  6267. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6268. }
  6269. lengthSquared() {
  6270. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6271. }
  6272. static normalize(s, out) {
  6273. var se = s.elements;
  6274. var oe = out.elements;
  6275. var len = s.length();
  6276. if (len > 0) {
  6277. oe[0] = se[0] * len;
  6278. oe[1] = se[1] * len;
  6279. oe[2] = se[2] * len;
  6280. oe[3] = se[3] * len;
  6281. }
  6282. }
  6283. static add(a, b, out) {
  6284. var oe = out.elements;
  6285. var ae = a.elements;
  6286. var be = b.elements;
  6287. oe[0] = ae[0] + be[0];
  6288. oe[1] = ae[1] + be[1];
  6289. oe[2] = ae[2] + be[2];
  6290. oe[3] = ae[3] + be[3];
  6291. }
  6292. static subtract(a, b, out) {
  6293. var oe = out.elements;
  6294. var ae = a.elements;
  6295. var be = b.elements;
  6296. oe[0] = ae[0] - be[0];
  6297. oe[1] = ae[1] - be[1];
  6298. oe[2] = ae[2] - be[2];
  6299. oe[3] = ae[3] - be[3];
  6300. }
  6301. static multiply(a, b, out) {
  6302. var oe = out.elements;
  6303. var ae = a.elements;
  6304. var be = b.elements;
  6305. oe[0] = ae[0] * be[0];
  6306. oe[1] = ae[1] * be[1];
  6307. oe[2] = ae[2] * be[2];
  6308. oe[3] = ae[3] * be[3];
  6309. }
  6310. static scale(a, b, out) {
  6311. var oe = out.elements;
  6312. var ae = a.elements;
  6313. oe[0] = ae[0] * b;
  6314. oe[1] = ae[1] * b;
  6315. oe[2] = ae[2] * b;
  6316. oe[3] = ae[3] * b;
  6317. }
  6318. static Clamp(value, min, max, out) {
  6319. var valuee = value.elements;
  6320. var x = valuee[0];
  6321. var y = valuee[1];
  6322. var z = valuee[2];
  6323. var w = valuee[3];
  6324. var mine = min.elements;
  6325. var mineX = mine[0];
  6326. var mineY = mine[1];
  6327. var mineZ = mine[2];
  6328. var mineW = mine[3];
  6329. var maxe = max.elements;
  6330. var maxeX = maxe[0];
  6331. var maxeY = maxe[1];
  6332. var maxeZ = maxe[2];
  6333. var maxeW = maxe[3];
  6334. var oute = out.elements;
  6335. x = (x > maxeX) ? maxeX : x;
  6336. x = (x < mineX) ? mineX : x;
  6337. y = (y > maxeY) ? maxeY : y;
  6338. y = (y < mineY) ? mineY : y;
  6339. z = (z > maxeZ) ? maxeZ : z;
  6340. z = (z < mineZ) ? mineZ : z;
  6341. w = (w > maxeW) ? maxeW : w;
  6342. w = (w < mineW) ? mineW : w;
  6343. oute[0] = x;
  6344. oute[1] = y;
  6345. oute[2] = z;
  6346. oute[3] = w;
  6347. }
  6348. static distanceSquared(value1, value2) {
  6349. var value1e = value1.elements;
  6350. var value2e = value2.elements;
  6351. var x = value1e[0] - value2e[0];
  6352. var y = value1e[1] - value2e[1];
  6353. var z = value1e[2] - value2e[2];
  6354. var w = value1e[3] - value2e[3];
  6355. return (x * x) + (y * y) + (z * z) + (w * w);
  6356. }
  6357. static distance(value1, value2) {
  6358. var value1e = value1.elements;
  6359. var value2e = value2.elements;
  6360. var x = value1e[0] - value2e[0];
  6361. var y = value1e[1] - value2e[1];
  6362. var z = value1e[2] - value2e[2];
  6363. var w = value1e[3] - value2e[3];
  6364. return Math.sqrt((x * x) + (y * y) + (z * z) + (w * w));
  6365. }
  6366. static dot(a, b) {
  6367. var ae = a.elements;
  6368. var be = b.elements;
  6369. var r = (ae[0] * be[0]) + (ae[1] * be[1]) + (ae[2] * be[2]) + (ae[3] * be[3]);
  6370. return r;
  6371. }
  6372. static min(a, b, out) {
  6373. var e = out.elements;
  6374. var f = a.elements;
  6375. var g = b.elements;
  6376. e[0] = Math.min(f[0], g[0]);
  6377. e[1] = Math.min(f[1], g[1]);
  6378. e[2] = Math.min(f[2], g[2]);
  6379. e[3] = Math.min(f[3], g[3]);
  6380. }
  6381. static max(a, b, out) {
  6382. var e = out.elements;
  6383. var f = a.elements;
  6384. var g = b.elements;
  6385. e[0] = Math.max(f[0], g[0]);
  6386. e[1] = Math.max(f[1], g[1]);
  6387. e[2] = Math.max(f[2], g[2]);
  6388. e[3] = Math.max(f[3], g[3]);
  6389. }
  6390. }
  6391. ConchVector4.ZERO = new ConchVector4();
  6392. ConchVector4.ONE = new ConchVector4(1.0, 1.0, 1.0, 1.0);
  6393. ConchVector4.UnitX = new ConchVector4(1.0, 0.0, 0.0, 0.0);
  6394. ConchVector4.UnitY = new ConchVector4(0.0, 1.0, 0.0, 0.0);
  6395. ConchVector4.UnitZ = new ConchVector4(0.0, 0.0, 1.0, 0.0);
  6396. ConchVector4.UnitW = new ConchVector4(0.0, 0.0, 0.0, 1.0);
  6397. class ConchVector3 {
  6398. constructor(x = 0, y = 0, z = 0, nativeElements = null) {
  6399. var v;
  6400. if (nativeElements) {
  6401. v = nativeElements;
  6402. }
  6403. else {
  6404. v = new Float32Array(3);
  6405. }
  6406. this.elements = v;
  6407. v[0] = x;
  6408. v[1] = y;
  6409. v[2] = z;
  6410. }
  6411. static distanceSquared(value1, value2) {
  6412. var value1e = value1.elements;
  6413. var value2e = value2.elements;
  6414. var x = value1e[0] - value2e[0];
  6415. var y = value1e[1] - value2e[1];
  6416. var z = value1e[2] - value2e[2];
  6417. return (x * x) + (y * y) + (z * z);
  6418. }
  6419. static distance(value1, value2) {
  6420. var value1e = value1.elements;
  6421. var value2e = value2.elements;
  6422. var x = value1e[0] - value2e[0];
  6423. var y = value1e[1] - value2e[1];
  6424. var z = value1e[2] - value2e[2];
  6425. return Math.sqrt((x * x) + (y * y) + (z * z));
  6426. }
  6427. static min(a, b, out) {
  6428. var e = out.elements;
  6429. var f = a.elements;
  6430. var g = b.elements;
  6431. e[0] = Math.min(f[0], g[0]);
  6432. e[1] = Math.min(f[1], g[1]);
  6433. e[2] = Math.min(f[2], g[2]);
  6434. }
  6435. static max(a, b, out) {
  6436. var e = out.elements;
  6437. var f = a.elements;
  6438. var g = b.elements;
  6439. e[0] = Math.max(f[0], g[0]);
  6440. e[1] = Math.max(f[1], g[1]);
  6441. e[2] = Math.max(f[2], g[2]);
  6442. }
  6443. static transformQuat(source, rotation, out) {
  6444. var destination = out.elements;
  6445. var se = source.elements;
  6446. var re = rotation.elements;
  6447. 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;
  6448. destination[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  6449. destination[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  6450. destination[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  6451. }
  6452. static scalarLength(a) {
  6453. var f = a.elements;
  6454. var x = f[0], y = f[1], z = f[2];
  6455. return Math.sqrt(x * x + y * y + z * z);
  6456. }
  6457. static scalarLengthSquared(a) {
  6458. var f = a.elements;
  6459. var x = f[0], y = f[1], z = f[2];
  6460. return x * x + y * y + z * z;
  6461. }
  6462. static normalize(s, out) {
  6463. var se = s.elements;
  6464. var oe = out.elements;
  6465. var x = se[0], y = se[1], z = se[2];
  6466. var len = x * x + y * y + z * z;
  6467. if (len > 0) {
  6468. len = 1 / Math.sqrt(len);
  6469. oe[0] = se[0] * len;
  6470. oe[1] = se[1] * len;
  6471. oe[2] = se[2] * len;
  6472. }
  6473. }
  6474. static multiply(a, b, out) {
  6475. var e = out.elements;
  6476. var f = a.elements;
  6477. var g = b.elements;
  6478. e[0] = f[0] * g[0];
  6479. e[1] = f[1] * g[1];
  6480. e[2] = f[2] * g[2];
  6481. }
  6482. static scale(a, b, out) {
  6483. var e = out.elements;
  6484. var f = a.elements;
  6485. e[0] = f[0] * b;
  6486. e[1] = f[1] * b;
  6487. e[2] = f[2] * b;
  6488. }
  6489. static lerp(a, b, t, out) {
  6490. var e = out.elements;
  6491. var f = a.elements;
  6492. var g = b.elements;
  6493. var ax = f[0], ay = f[1], az = f[2];
  6494. e[0] = ax + t * (g[0] - ax);
  6495. e[1] = ay + t * (g[1] - ay);
  6496. e[2] = az + t * (g[2] - az);
  6497. }
  6498. static transformV3ToV3(vector, transform, result) {
  6499. var intermediate = ConchVector3._tempVector4;
  6500. ConchVector3.transformV3ToV4(vector, transform, intermediate);
  6501. var intermediateElem = intermediate.elements;
  6502. var resultElem = result.elements;
  6503. resultElem[0] = intermediateElem[0];
  6504. resultElem[1] = intermediateElem[1];
  6505. resultElem[2] = intermediateElem[2];
  6506. }
  6507. static transformV3ToV4(vector, transform, result) {
  6508. var vectorElem = vector.elements;
  6509. var vectorX = vectorElem[0];
  6510. var vectorY = vectorElem[1];
  6511. var vectorZ = vectorElem[2];
  6512. var transformElem = transform.elements;
  6513. var resultElem = result.elements;
  6514. resultElem[0] = (vectorX * transformElem[0]) + (vectorY * transformElem[4]) + (vectorZ * transformElem[8]) + transformElem[12];
  6515. resultElem[1] = (vectorX * transformElem[1]) + (vectorY * transformElem[5]) + (vectorZ * transformElem[9]) + transformElem[13];
  6516. resultElem[2] = (vectorX * transformElem[2]) + (vectorY * transformElem[6]) + (vectorZ * transformElem[10]) + transformElem[14];
  6517. resultElem[3] = (vectorX * transformElem[3]) + (vectorY * transformElem[7]) + (vectorZ * transformElem[11]) + transformElem[15];
  6518. }
  6519. static TransformNormal(normal, transform, result) {
  6520. var normalElem = normal.elements;
  6521. var normalX = normalElem[0];
  6522. var normalY = normalElem[1];
  6523. var normalZ = normalElem[2];
  6524. var transformElem = transform.elements;
  6525. var resultElem = result.elements;
  6526. resultElem[0] = (normalX * transformElem[0]) + (normalY * transformElem[4]) + (normalZ * transformElem[8]);
  6527. resultElem[1] = (normalX * transformElem[1]) + (normalY * transformElem[5]) + (normalZ * transformElem[9]);
  6528. resultElem[2] = (normalX * transformElem[2]) + (normalY * transformElem[6]) + (normalZ * transformElem[10]);
  6529. }
  6530. static transformCoordinate(coordinate, transform, result) {
  6531. var coordinateElem = coordinate.elements;
  6532. var coordinateX = coordinateElem[0];
  6533. var coordinateY = coordinateElem[1];
  6534. var coordinateZ = coordinateElem[2];
  6535. var transformElem = transform.elements;
  6536. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  6537. var resultElem = result.elements;
  6538. resultElem[0] = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  6539. resultElem[1] = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  6540. resultElem[2] = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  6541. }
  6542. static Clamp(value, min, max, out) {
  6543. var valuee = value.elements;
  6544. var x = valuee[0];
  6545. var y = valuee[1];
  6546. var z = valuee[2];
  6547. var mine = min.elements;
  6548. var mineX = mine[0];
  6549. var mineY = mine[1];
  6550. var mineZ = mine[2];
  6551. var maxe = max.elements;
  6552. var maxeX = maxe[0];
  6553. var maxeY = maxe[1];
  6554. var maxeZ = maxe[2];
  6555. var oute = out.elements;
  6556. x = (x > maxeX) ? maxeX : x;
  6557. x = (x < mineX) ? mineX : x;
  6558. y = (y > maxeY) ? maxeY : y;
  6559. y = (y < mineY) ? mineY : y;
  6560. z = (z > maxeZ) ? maxeZ : z;
  6561. z = (z < mineZ) ? mineZ : z;
  6562. oute[0] = x;
  6563. oute[1] = y;
  6564. oute[2] = z;
  6565. }
  6566. static add(a, b, out) {
  6567. var e = out.elements;
  6568. var f = a.elements;
  6569. var g = b.elements;
  6570. e[0] = f[0] + g[0];
  6571. e[1] = f[1] + g[1];
  6572. e[2] = f[2] + g[2];
  6573. }
  6574. static subtract(a, b, o) {
  6575. var oe = o.elements;
  6576. var ae = a.elements;
  6577. var be = b.elements;
  6578. oe[0] = ae[0] - be[0];
  6579. oe[1] = ae[1] - be[1];
  6580. oe[2] = ae[2] - be[2];
  6581. }
  6582. static cross(a, b, o) {
  6583. var ae = a.elements;
  6584. var be = b.elements;
  6585. var oe = o.elements;
  6586. var ax = ae[0], ay = ae[1], az = ae[2], bx = be[0], by = be[1], bz = be[2];
  6587. oe[0] = ay * bz - az * by;
  6588. oe[1] = az * bx - ax * bz;
  6589. oe[2] = ax * by - ay * bx;
  6590. }
  6591. static dot(a, b) {
  6592. var ae = a.elements;
  6593. var be = b.elements;
  6594. var r = (ae[0] * be[0]) + (ae[1] * be[1]) + (ae[2] * be[2]);
  6595. return r;
  6596. }
  6597. static equals(a, b) {
  6598. var ae = a.elements;
  6599. var be = b.elements;
  6600. return MathUtils3D.nearEqual(ae[0], be[0]) && MathUtils3D.nearEqual(ae[1], be[1]) && MathUtils3D.nearEqual(ae[2], be[2]);
  6601. }
  6602. get x() {
  6603. return this.elements[0];
  6604. }
  6605. set x(value) {
  6606. this.elements[0] = value;
  6607. }
  6608. get y() {
  6609. return this.elements[1];
  6610. }
  6611. set y(value) {
  6612. this.elements[1] = value;
  6613. }
  6614. get z() {
  6615. return this.elements[2];
  6616. }
  6617. set z(value) {
  6618. this.elements[2] = value;
  6619. }
  6620. setValue(x, y, z) {
  6621. this.elements[0] = x;
  6622. this.elements[1] = y;
  6623. this.elements[2] = z;
  6624. }
  6625. fromArray(array, offset = 0) {
  6626. this.elements[0] = array[offset + 0];
  6627. this.elements[1] = array[offset + 1];
  6628. this.elements[2] = array[offset + 2];
  6629. }
  6630. cloneTo(destObject) {
  6631. var destVector3 = destObject;
  6632. var destE = destVector3.elements;
  6633. var s = this.elements;
  6634. destE[0] = s[0];
  6635. destE[1] = s[1];
  6636. destE[2] = s[2];
  6637. }
  6638. clone() {
  6639. var destVector3 = new ConchVector3();
  6640. this.cloneTo(destVector3);
  6641. return destVector3;
  6642. }
  6643. toDefault() {
  6644. this.elements[0] = 0;
  6645. this.elements[1] = 0;
  6646. this.elements[2] = 0;
  6647. }
  6648. }
  6649. ConchVector3._tempVector4 = new ConchVector4();
  6650. ConchVector3.ZERO = new ConchVector3(0.0, 0.0, 0.0);
  6651. ConchVector3.ONE = new ConchVector3(1.0, 1.0, 1.0);
  6652. ConchVector3.NegativeUnitX = new ConchVector3(-1, 0, 0);
  6653. ConchVector3.UnitX = new ConchVector3(1, 0, 0);
  6654. ConchVector3.UnitY = new ConchVector3(0, 1, 0);
  6655. ConchVector3.UnitZ = new ConchVector3(0, 0, 1);
  6656. ConchVector3.ForwardRH = new ConchVector3(0, 0, -1);
  6657. ConchVector3.ForwardLH = new ConchVector3(0, 0, 1);
  6658. ConchVector3.Up = new ConchVector3(0, 1, 0);
  6659. ConchVector3.NAN = new ConchVector3(NaN, NaN, NaN);
  6660. class ConchQuaternion {
  6661. constructor(x = 0, y = 0, z = 0, w = 1, nativeElements = null) {
  6662. var v;
  6663. if (nativeElements) {
  6664. v = nativeElements;
  6665. }
  6666. else {
  6667. v = new Float32Array(4);
  6668. }
  6669. v[0] = x;
  6670. v[1] = y;
  6671. v[2] = z;
  6672. v[3] = w;
  6673. this.elements = v;
  6674. }
  6675. static _dotArray(l, r) {
  6676. return l[0] * r[0] + l[1] * r[1] + l[2] * r[2] + l[3] * r[3];
  6677. }
  6678. static _normalizeArray(f, o) {
  6679. var x = f[0], y = f[1], z = f[2], w = f[3];
  6680. var len = x * x + y * y + z * z + w * w;
  6681. if (len > 0) {
  6682. len = 1 / Math.sqrt(len);
  6683. o[0] = x * len;
  6684. o[1] = y * len;
  6685. o[2] = z * len;
  6686. o[3] = w * len;
  6687. }
  6688. }
  6689. static _lerpArray(l, r, amount, o) {
  6690. var inverse = 1.0 - amount;
  6691. if (ConchQuaternion._dotArray(l, r) >= 0) {
  6692. o[0] = (inverse * l[0]) + (amount * r[0]);
  6693. o[1] = (inverse * l[1]) + (amount * r[1]);
  6694. o[2] = (inverse * l[2]) + (amount * r[2]);
  6695. o[3] = (inverse * l[3]) + (amount * r[3]);
  6696. }
  6697. else {
  6698. o[0] = (inverse * l[0]) - (amount * r[0]);
  6699. o[1] = (inverse * l[1]) - (amount * r[1]);
  6700. o[2] = (inverse * l[2]) - (amount * r[2]);
  6701. o[3] = (inverse * l[3]) - (amount * r[3]);
  6702. }
  6703. ConchQuaternion._normalizeArray(o, o);
  6704. }
  6705. static createFromYawPitchRoll(yaw, pitch, roll, out) {
  6706. var halfRoll = roll * 0.5;
  6707. var halfPitch = pitch * 0.5;
  6708. var halfYaw = yaw * 0.5;
  6709. var sinRoll = Math.sin(halfRoll);
  6710. var cosRoll = Math.cos(halfRoll);
  6711. var sinPitch = Math.sin(halfPitch);
  6712. var cosPitch = Math.cos(halfPitch);
  6713. var sinYaw = Math.sin(halfYaw);
  6714. var cosYaw = Math.cos(halfYaw);
  6715. var oe = out.elements;
  6716. oe[0] = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  6717. oe[1] = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  6718. oe[2] = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  6719. oe[3] = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  6720. }
  6721. static multiply(left, right, out) {
  6722. var le = left.elements;
  6723. var re = right.elements;
  6724. var oe = out.elements;
  6725. var lx = le[0];
  6726. var ly = le[1];
  6727. var lz = le[2];
  6728. var lw = le[3];
  6729. var rx = re[0];
  6730. var ry = re[1];
  6731. var rz = re[2];
  6732. var rw = re[3];
  6733. var a = (ly * rz - lz * ry);
  6734. var b = (lz * rx - lx * rz);
  6735. var c = (lx * ry - ly * rx);
  6736. var d = (lx * rx + ly * ry + lz * rz);
  6737. oe[0] = (lx * rw + rx * lw) + a;
  6738. oe[1] = (ly * rw + ry * lw) + b;
  6739. oe[2] = (lz * rw + rz * lw) + c;
  6740. oe[3] = lw * rw - d;
  6741. }
  6742. static arcTanAngle(x, y) {
  6743. if (x == 0) {
  6744. if (y == 1)
  6745. return Math.PI / 2;
  6746. return -Math.PI / 2;
  6747. }
  6748. if (x > 0)
  6749. return Math.atan(y / x);
  6750. if (x < 0) {
  6751. if (y > 0)
  6752. return Math.atan(y / x) + Math.PI;
  6753. return Math.atan(y / x) - Math.PI;
  6754. }
  6755. return 0;
  6756. }
  6757. static angleTo(from, location, angle) {
  6758. ConchVector3.subtract(location, from, ConchQuaternion.TEMPVector30);
  6759. ConchVector3.normalize(ConchQuaternion.TEMPVector30, ConchQuaternion.TEMPVector30);
  6760. angle.elements[0] = Math.asin(ConchQuaternion.TEMPVector30.y);
  6761. angle.elements[1] = ConchQuaternion.arcTanAngle(-ConchQuaternion.TEMPVector30.z, -ConchQuaternion.TEMPVector30.x);
  6762. }
  6763. static createFromAxisAngle(axis, rad, out) {
  6764. var e = out.elements;
  6765. var f = axis.elements;
  6766. rad = rad * 0.5;
  6767. var s = Math.sin(rad);
  6768. e[0] = s * f[0];
  6769. e[1] = s * f[1];
  6770. e[2] = s * f[2];
  6771. e[3] = Math.cos(rad);
  6772. }
  6773. static createFromMatrix3x3(sou, out) {
  6774. var e = out.elements;
  6775. var f = sou.elements;
  6776. var fTrace = f[0] + f[4] + f[8];
  6777. var fRoot;
  6778. if (fTrace > 0.0) {
  6779. fRoot = Math.sqrt(fTrace + 1.0);
  6780. e[3] = 0.5 * fRoot;
  6781. fRoot = 0.5 / fRoot;
  6782. e[0] = (f[5] - f[7]) * fRoot;
  6783. e[1] = (f[6] - f[2]) * fRoot;
  6784. e[2] = (f[1] - f[3]) * fRoot;
  6785. }
  6786. else {
  6787. var i = 0;
  6788. if (f[4] > f[0])
  6789. i = 1;
  6790. if (f[8] > f[i * 3 + i])
  6791. i = 2;
  6792. var j = (i + 1) % 3;
  6793. var k = (i + 2) % 3;
  6794. fRoot = Math.sqrt(f[i * 3 + i] - f[j * 3 + j] - f[k * 3 + k] + 1.0);
  6795. e[i] = 0.5 * fRoot;
  6796. fRoot = 0.5 / fRoot;
  6797. e[3] = (f[j * 3 + k] - f[k * 3 + j]) * fRoot;
  6798. e[j] = (f[j * 3 + i] + f[i * 3 + j]) * fRoot;
  6799. e[k] = (f[k * 3 + i] + f[i * 3 + k]) * fRoot;
  6800. }
  6801. return;
  6802. }
  6803. static createFromMatrix4x4(mat, out) {
  6804. var me = mat.elements;
  6805. var oe = out.elements;
  6806. var sqrt;
  6807. var half;
  6808. var scale = me[0] + me[5] + me[10];
  6809. if (scale > 0.0) {
  6810. sqrt = Math.sqrt(scale + 1.0);
  6811. oe[3] = sqrt * 0.5;
  6812. sqrt = 0.5 / sqrt;
  6813. oe[0] = (me[6] - me[9]) * sqrt;
  6814. oe[1] = (me[8] - me[2]) * sqrt;
  6815. oe[2] = (me[1] - me[4]) * sqrt;
  6816. }
  6817. else if ((me[0] >= me[5]) && (me[0] >= me[10])) {
  6818. sqrt = Math.sqrt(1.0 + me[0] - me[5] - me[10]);
  6819. half = 0.5 / sqrt;
  6820. oe[0] = 0.5 * sqrt;
  6821. oe[1] = (me[1] + me[4]) * half;
  6822. oe[2] = (me[2] + me[8]) * half;
  6823. oe[3] = (me[6] - me[9]) * half;
  6824. }
  6825. else if (me[5] > me[10]) {
  6826. sqrt = Math.sqrt(1.0 + me[5] - me[0] - me[10]);
  6827. half = 0.5 / sqrt;
  6828. oe[0] = (me[4] + me[1]) * half;
  6829. oe[1] = 0.5 * sqrt;
  6830. oe[2] = (me[9] + me[6]) * half;
  6831. oe[3] = (me[8] - me[2]) * half;
  6832. }
  6833. else {
  6834. sqrt = Math.sqrt(1.0 + me[10] - me[0] - me[5]);
  6835. half = 0.5 / sqrt;
  6836. oe[0] = (me[8] + me[2]) * half;
  6837. oe[1] = (me[9] + me[6]) * half;
  6838. oe[2] = 0.5 * sqrt;
  6839. oe[3] = (me[1] - me[4]) * half;
  6840. }
  6841. }
  6842. static slerp(left, right, t, out) {
  6843. var a = left.elements;
  6844. var b = right.elements;
  6845. var oe = out.elements;
  6846. 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];
  6847. var omega, cosom, sinom, scale0, scale1;
  6848. cosom = ax * bx + ay * by + az * bz + aw * bw;
  6849. if (cosom < 0.0) {
  6850. cosom = -cosom;
  6851. bx = -bx;
  6852. by = -by;
  6853. bz = -bz;
  6854. bw = -bw;
  6855. }
  6856. if ((1.0 - cosom) > 0.000001) {
  6857. omega = Math.acos(cosom);
  6858. sinom = Math.sin(omega);
  6859. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  6860. scale1 = Math.sin(t * omega) / sinom;
  6861. }
  6862. else {
  6863. scale0 = 1.0 - t;
  6864. scale1 = t;
  6865. }
  6866. oe[0] = scale0 * ax + scale1 * bx;
  6867. oe[1] = scale0 * ay + scale1 * by;
  6868. oe[2] = scale0 * az + scale1 * bz;
  6869. oe[3] = scale0 * aw + scale1 * bw;
  6870. return oe;
  6871. }
  6872. static lerp(left, right, amount, out) {
  6873. ConchQuaternion._lerpArray(left.elements, right.elements, amount, out.elements);
  6874. }
  6875. static add(left, right, out) {
  6876. var e = out.elements;
  6877. var f = left.elements;
  6878. var g = right.elements;
  6879. e[0] = f[0] + g[0];
  6880. e[1] = f[1] + g[1];
  6881. e[2] = f[2] + g[2];
  6882. e[3] = f[3] + g[3];
  6883. }
  6884. static dot(left, right) {
  6885. return ConchQuaternion._dotArray(left.elements, right.elements);
  6886. }
  6887. get x() {
  6888. return this.elements[0];
  6889. }
  6890. set x(value) {
  6891. this.elements[0] = value;
  6892. }
  6893. get y() {
  6894. return this.elements[1];
  6895. }
  6896. set y(value) {
  6897. this.elements[1] = value;
  6898. }
  6899. get z() {
  6900. return this.elements[2];
  6901. }
  6902. set z(value) {
  6903. this.elements[2] = value;
  6904. }
  6905. get w() {
  6906. return this.elements[3];
  6907. }
  6908. set w(value) {
  6909. this.elements[3] = value;
  6910. }
  6911. scaling(scaling, out) {
  6912. var e = out.elements;
  6913. var f = this.elements;
  6914. e[0] = f[0] * scaling;
  6915. e[1] = f[1] * scaling;
  6916. e[2] = f[2] * scaling;
  6917. e[3] = f[3] * scaling;
  6918. }
  6919. normalize(out) {
  6920. ConchQuaternion._normalizeArray(this.elements, out.elements);
  6921. }
  6922. length() {
  6923. var f = this.elements;
  6924. var x = f[0], y = f[1], z = f[2], w = f[3];
  6925. return Math.sqrt(x * x + y * y + z * z + w * w);
  6926. }
  6927. rotateX(rad, out) {
  6928. var e = out.elements;
  6929. var f = this.elements;
  6930. rad *= 0.5;
  6931. var ax = f[0], ay = f[1], az = f[2], aw = f[3];
  6932. var bx = Math.sin(rad), bw = Math.cos(rad);
  6933. e[0] = ax * bw + aw * bx;
  6934. e[1] = ay * bw + az * bx;
  6935. e[2] = az * bw - ay * bx;
  6936. e[3] = aw * bw - ax * bx;
  6937. }
  6938. rotateY(rad, out) {
  6939. var e = out.elements;
  6940. var f = this.elements;
  6941. rad *= 0.5;
  6942. var ax = f[0], ay = f[1], az = f[2], aw = f[3], by = Math.sin(rad), bw = Math.cos(rad);
  6943. e[0] = ax * bw - az * by;
  6944. e[1] = ay * bw + aw * by;
  6945. e[2] = az * bw + ax * by;
  6946. e[3] = aw * bw - ay * by;
  6947. }
  6948. rotateZ(rad, out) {
  6949. var e = out.elements;
  6950. var f = this.elements;
  6951. rad *= 0.5;
  6952. var ax = f[0], ay = f[1], az = f[2], aw = f[3], bz = Math.sin(rad), bw = Math.cos(rad);
  6953. e[0] = ax * bw + ay * bz;
  6954. e[1] = ay * bw - ax * bz;
  6955. e[2] = az * bw + aw * bz;
  6956. e[3] = aw * bw - az * bz;
  6957. }
  6958. getYawPitchRoll(out) {
  6959. ConchVector3.transformQuat(ConchVector3.ForwardRH, this, ConchQuaternion.TEMPVector31);
  6960. ConchVector3.transformQuat(ConchVector3.Up, this, ConchQuaternion.TEMPVector32);
  6961. var upe = ConchQuaternion.TEMPVector32.elements;
  6962. ConchQuaternion.angleTo(ConchVector3.ZERO, ConchQuaternion.TEMPVector31, ConchQuaternion.TEMPVector33);
  6963. var anglee = ConchQuaternion.TEMPVector33.elements;
  6964. if (anglee[0] == Math.PI / 2) {
  6965. anglee[1] = ConchQuaternion.arcTanAngle(upe[2], upe[0]);
  6966. anglee[2] = 0;
  6967. }
  6968. else if (anglee[0] == -Math.PI / 2) {
  6969. anglee[1] = ConchQuaternion.arcTanAngle(-upe[2], -upe[0]);
  6970. anglee[2] = 0;
  6971. }
  6972. else {
  6973. Matrix4x4.createRotationY(-anglee[1], ConchQuaternion.TEMPMatrix0);
  6974. Matrix4x4.createRotationX(-anglee[0], ConchQuaternion.TEMPMatrix1);
  6975. ConchVector3.transformCoordinate(ConchQuaternion.TEMPVector32, ConchQuaternion.TEMPMatrix0, ConchQuaternion.TEMPVector32);
  6976. ConchVector3.transformCoordinate(ConchQuaternion.TEMPVector32, ConchQuaternion.TEMPMatrix1, ConchQuaternion.TEMPVector32);
  6977. anglee[2] = ConchQuaternion.arcTanAngle(upe[1], -upe[0]);
  6978. }
  6979. if (anglee[1] <= -Math.PI)
  6980. anglee[1] = Math.PI;
  6981. if (anglee[2] <= -Math.PI)
  6982. anglee[2] = Math.PI;
  6983. if (anglee[1] >= Math.PI && anglee[2] >= Math.PI) {
  6984. anglee[1] = 0;
  6985. anglee[2] = 0;
  6986. anglee[0] = Math.PI - anglee[0];
  6987. }
  6988. var oe = out.elements;
  6989. oe[0] = anglee[1];
  6990. oe[1] = anglee[0];
  6991. oe[2] = anglee[2];
  6992. }
  6993. invert(out) {
  6994. var e = out.elements;
  6995. var f = this.elements;
  6996. var a0 = f[0], a1 = f[1], a2 = f[2], a3 = f[3];
  6997. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  6998. var invDot = dot ? 1.0 / dot : 0;
  6999. e[0] = -a0 * invDot;
  7000. e[1] = -a1 * invDot;
  7001. e[2] = -a2 * invDot;
  7002. e[3] = a3 * invDot;
  7003. }
  7004. identity() {
  7005. var e = this.elements;
  7006. e[0] = 0;
  7007. e[1] = 0;
  7008. e[2] = 0;
  7009. e[3] = 1;
  7010. }
  7011. fromArray(array, offset = 0) {
  7012. this.elements[0] = array[offset + 0];
  7013. this.elements[1] = array[offset + 1];
  7014. this.elements[2] = array[offset + 2];
  7015. this.elements[3] = array[offset + 3];
  7016. }
  7017. cloneTo(destObject) {
  7018. var i, s, d;
  7019. s = this.elements;
  7020. d = destObject.elements;
  7021. if (s === d) {
  7022. return;
  7023. }
  7024. for (i = 0; i < 4; ++i) {
  7025. d[i] = s[i];
  7026. }
  7027. }
  7028. clone() {
  7029. var dest = new ConchQuaternion();
  7030. this.cloneTo(dest);
  7031. return dest;
  7032. }
  7033. equals(b) {
  7034. var ae = this.elements;
  7035. var be = b.elements;
  7036. 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]);
  7037. }
  7038. static rotationLookAt(forward, up, out) {
  7039. ConchQuaternion.lookAt(ConchVector3.ZERO, forward, up, out);
  7040. }
  7041. static lookAt(eye, target, up, out) {
  7042. Matrix3x3.lookAt(eye, target, up, ConchQuaternion._tempMatrix3x3);
  7043. ConchQuaternion.rotationMatrix(ConchQuaternion._tempMatrix3x3, out);
  7044. }
  7045. lengthSquared() {
  7046. var x = this.elements[0];
  7047. var y = this.elements[1];
  7048. var z = this.elements[2];
  7049. var w = this.elements[3];
  7050. return (x * x) + (y * y) + (z * z) + (w * w);
  7051. }
  7052. static invert(value, out) {
  7053. var vE = value.elements;
  7054. var oE = out.elements;
  7055. var lengthSq = value.lengthSquared();
  7056. if (!MathUtils3D.isZero(lengthSq)) {
  7057. lengthSq = 1.0 / lengthSq;
  7058. oE[0] = -vE[0] * lengthSq;
  7059. oE[1] = -vE[1] * lengthSq;
  7060. oE[2] = -vE[2] * lengthSq;
  7061. oE[3] = vE[3] * lengthSq;
  7062. }
  7063. }
  7064. static rotationMatrix(matrix3x3, out) {
  7065. var me = matrix3x3.elements;
  7066. var m11 = me[0];
  7067. var m12 = me[1];
  7068. var m13 = me[2];
  7069. var m21 = me[3];
  7070. var m22 = me[4];
  7071. var m23 = me[5];
  7072. var m31 = me[6];
  7073. var m32 = me[7];
  7074. var m33 = me[8];
  7075. var oe = out.elements;
  7076. var sqrt, half;
  7077. var scale = m11 + m22 + m33;
  7078. if (scale > 0) {
  7079. sqrt = Math.sqrt(scale + 1);
  7080. oe[3] = sqrt * 0.5;
  7081. sqrt = 0.5 / sqrt;
  7082. oe[0] = (m23 - m32) * sqrt;
  7083. oe[1] = (m31 - m13) * sqrt;
  7084. oe[2] = (m12 - m21) * sqrt;
  7085. }
  7086. else if ((m11 >= m22) && (m11 >= m33)) {
  7087. sqrt = Math.sqrt(1 + m11 - m22 - m33);
  7088. half = 0.5 / sqrt;
  7089. oe[0] = 0.5 * sqrt;
  7090. oe[1] = (m12 + m21) * half;
  7091. oe[2] = (m13 + m31) * half;
  7092. oe[3] = (m23 - m32) * half;
  7093. }
  7094. else if (m22 > m33) {
  7095. sqrt = Math.sqrt(1 + m22 - m11 - m33);
  7096. half = 0.5 / sqrt;
  7097. oe[0] = (m21 + m12) * half;
  7098. oe[1] = 0.5 * sqrt;
  7099. oe[2] = (m32 + m23) * half;
  7100. oe[3] = (m31 - m13) * half;
  7101. }
  7102. else {
  7103. sqrt = Math.sqrt(1 + m33 - m11 - m22);
  7104. half = 0.5 / sqrt;
  7105. oe[0] = (m31 + m13) * half;
  7106. oe[1] = (m32 + m23) * half;
  7107. oe[2] = 0.5 * sqrt;
  7108. oe[3] = (m12 - m21) * half;
  7109. }
  7110. }
  7111. }
  7112. ConchQuaternion.TEMPVector30 = new ConchVector3();
  7113. ConchQuaternion.TEMPVector31 = new ConchVector3();
  7114. ConchQuaternion.TEMPVector32 = new ConchVector3();
  7115. ConchQuaternion.TEMPVector33 = new ConchVector3();
  7116. ConchQuaternion.TEMPMatrix0 = new Matrix4x4();
  7117. ConchQuaternion.TEMPMatrix1 = new Matrix4x4();
  7118. ConchQuaternion._tempMatrix3x3 = new Matrix3x3();
  7119. ConchQuaternion.DEFAULT = new ConchQuaternion();
  7120. ConchQuaternion.NAN = new ConchQuaternion(NaN, NaN, NaN, NaN);
  7121. class AnimatorState {
  7122. constructor() {
  7123. this._referenceCount = 0;
  7124. this._clip = null;
  7125. this._nodeOwners = [];
  7126. this._currentFrameIndices = null;
  7127. this._realtimeDatas = [];
  7128. this._scripts = null;
  7129. this.speed = 1.0;
  7130. this.clipStart = 0.0;
  7131. this.clipEnd = 1.0;
  7132. }
  7133. get clip() {
  7134. return this._clip;
  7135. }
  7136. set clip(value) {
  7137. if (this._clip !== value) {
  7138. if (this._clip)
  7139. (this._referenceCount > 0) && (this._clip._removeReference(this._referenceCount));
  7140. if (value) {
  7141. var realtimeDatas = this._realtimeDatas;
  7142. var clipNodes = value._nodes;
  7143. var count = clipNodes.count;
  7144. this._currentFrameIndices = new Int16Array(count);
  7145. this._resetFrameIndices();
  7146. (this._referenceCount > 0) && (value._addReference(this._referenceCount));
  7147. this._realtimeDatas.length = count;
  7148. for (var i = 0; i < count; i++) {
  7149. switch (clipNodes.getNodeByIndex(i).type) {
  7150. case 0:
  7151. break;
  7152. case 1:
  7153. case 3:
  7154. case 4:
  7155. realtimeDatas[i] = Laya.Render.supportWebGLPlusAnimation ? new ConchVector3 : new Vector3();
  7156. break;
  7157. case 2:
  7158. realtimeDatas[i] = Laya.Render.supportWebGLPlusAnimation ? new ConchQuaternion : new Quaternion();
  7159. break;
  7160. default:
  7161. throw "AnimationClipParser04:unknown type.";
  7162. }
  7163. }
  7164. }
  7165. this._clip = value;
  7166. }
  7167. }
  7168. _getReferenceCount() {
  7169. return this._referenceCount;
  7170. }
  7171. _addReference(count = 1) {
  7172. (this._clip) && (this._clip._addReference(count));
  7173. this._referenceCount += count;
  7174. }
  7175. _removeReference(count = 1) {
  7176. (this._clip) && (this._clip._removeReference(count));
  7177. this._referenceCount -= count;
  7178. }
  7179. _clearReference() {
  7180. this._removeReference(-this._referenceCount);
  7181. }
  7182. _resetFrameIndices() {
  7183. for (var i = 0, n = this._currentFrameIndices.length; i < n; i++)
  7184. this._currentFrameIndices[i] = -1;
  7185. }
  7186. addScript(type) {
  7187. var script = new type();
  7188. this._scripts = this._scripts || [];
  7189. this._scripts.push(script);
  7190. return script;
  7191. }
  7192. getScript(type) {
  7193. if (this._scripts) {
  7194. for (var i = 0, n = this._scripts.length; i < n; i++) {
  7195. var script = this._scripts[i];
  7196. if (script instanceof type)
  7197. return script;
  7198. }
  7199. }
  7200. return null;
  7201. }
  7202. getScripts(type) {
  7203. var coms;
  7204. if (this._scripts) {
  7205. for (var i = 0, n = this._scripts.length; i < n; i++) {
  7206. var script = this._scripts[i];
  7207. if (script instanceof type) {
  7208. coms = coms || [];
  7209. coms.push(script);
  7210. }
  7211. }
  7212. }
  7213. return coms;
  7214. }
  7215. cloneTo(destObject) {
  7216. var dest = destObject;
  7217. dest.name = this.name;
  7218. dest.speed = this.speed;
  7219. dest.clipStart = this.clipStart;
  7220. dest.clipEnd = this.clipEnd;
  7221. dest.clip = this._clip;
  7222. }
  7223. clone() {
  7224. var dest = new AnimatorState();
  7225. this.cloneTo(dest);
  7226. return dest;
  7227. }
  7228. }
  7229. class KeyframeNodeOwner {
  7230. constructor() {
  7231. this.indexInList = -1;
  7232. this.referenceCount = 0;
  7233. this.updateMark = -1;
  7234. this.type = -1;
  7235. this.fullPath = null;
  7236. this.propertyOwner = null;
  7237. this.property = null;
  7238. this.defaultValue = null;
  7239. this.value = null;
  7240. this.crossFixedValue = null;
  7241. }
  7242. saveCrossFixedValue() {
  7243. var pro = this.propertyOwner;
  7244. if (pro) {
  7245. switch (this.type) {
  7246. case 0:
  7247. this.crossFixedValue = this.value;
  7248. break;
  7249. case 1:
  7250. case 3:
  7251. case 4:
  7252. this.value.cloneTo(this.crossFixedValue);
  7253. break;
  7254. case 2:
  7255. this.value.cloneTo(this.crossFixedValue);
  7256. break;
  7257. default:
  7258. throw "Animator:unknown type.";
  7259. }
  7260. }
  7261. }
  7262. }
  7263. class Animator extends Laya.Component {
  7264. constructor() {
  7265. super();
  7266. this._keyframeNodeOwners = [];
  7267. this._linkAvatarSpritesData = {};
  7268. this._linkAvatarSprites = [];
  7269. this._renderableSprites = [];
  7270. this.cullingMode = Animator.CULLINGMODE_CULLCOMPLETELY;
  7271. this._controllerLayers = [];
  7272. this._linkSprites = {};
  7273. this._speed = 1.0;
  7274. this._keyframeNodeOwnerMap = {};
  7275. this._updateMark = 0;
  7276. }
  7277. static _update(scene) {
  7278. var pool = scene._animatorPool;
  7279. var elements = pool.elements;
  7280. for (var i = 0, n = pool.length; i < n; i++) {
  7281. var animator = elements[i];
  7282. (animator && animator.enabled) && (animator._update());
  7283. }
  7284. }
  7285. get speed() {
  7286. return this._speed;
  7287. }
  7288. set speed(value) {
  7289. this._speed = value;
  7290. }
  7291. _linkToSprites(linkSprites) {
  7292. for (var k in linkSprites) {
  7293. var nodeOwner = this.owner;
  7294. var path = linkSprites[k];
  7295. for (var j = 0, m = path.length; j < m; j++) {
  7296. var p = path[j];
  7297. if (p === "") {
  7298. break;
  7299. }
  7300. else {
  7301. nodeOwner = nodeOwner.getChildByName(p);
  7302. if (!nodeOwner)
  7303. break;
  7304. }
  7305. }
  7306. (nodeOwner) && (this.linkSprite3DToAvatarNode(k, nodeOwner));
  7307. }
  7308. }
  7309. _addKeyframeNodeOwner(clipOwners, node, propertyOwner) {
  7310. var nodeIndex = node._indexInList;
  7311. var fullPath = node.fullPath;
  7312. var keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath];
  7313. if (keyframeNodeOwner) {
  7314. keyframeNodeOwner.referenceCount++;
  7315. clipOwners[nodeIndex] = keyframeNodeOwner;
  7316. }
  7317. else {
  7318. var property = propertyOwner;
  7319. for (var i = 0, n = node.propertyCount; i < n; i++) {
  7320. property = property[node.getPropertyByIndex(i)];
  7321. if (!property)
  7322. break;
  7323. }
  7324. keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath] = new KeyframeNodeOwner();
  7325. keyframeNodeOwner.fullPath = fullPath;
  7326. keyframeNodeOwner.indexInList = this._keyframeNodeOwners.length;
  7327. keyframeNodeOwner.referenceCount = 1;
  7328. keyframeNodeOwner.propertyOwner = propertyOwner;
  7329. var propertyCount = node.propertyCount;
  7330. var propertys = [];
  7331. for (i = 0; i < propertyCount; i++)
  7332. propertys[i] = node.getPropertyByIndex(i);
  7333. keyframeNodeOwner.property = propertys;
  7334. keyframeNodeOwner.type = node.type;
  7335. if (property) {
  7336. if (node.type === 0) {
  7337. keyframeNodeOwner.defaultValue = property;
  7338. }
  7339. else {
  7340. var defaultValue = new property.constructor();
  7341. property.cloneTo(defaultValue);
  7342. keyframeNodeOwner.defaultValue = defaultValue;
  7343. keyframeNodeOwner.value = new property.constructor();
  7344. keyframeNodeOwner.crossFixedValue = new property.constructor();
  7345. }
  7346. }
  7347. this._keyframeNodeOwners.push(keyframeNodeOwner);
  7348. clipOwners[nodeIndex] = keyframeNodeOwner;
  7349. }
  7350. }
  7351. _removeKeyframeNodeOwner(nodeOwners, node) {
  7352. var fullPath = node.fullPath;
  7353. var keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath];
  7354. if (keyframeNodeOwner) {
  7355. keyframeNodeOwner.referenceCount--;
  7356. if (keyframeNodeOwner.referenceCount === 0) {
  7357. delete this._keyframeNodeOwnerMap[fullPath];
  7358. this._keyframeNodeOwners.splice(this._keyframeNodeOwners.indexOf(keyframeNodeOwner), 1);
  7359. }
  7360. nodeOwners[node._indexInList] = null;
  7361. }
  7362. }
  7363. _getOwnersByClip(clipStateInfo) {
  7364. var frameNodes = clipStateInfo._clip._nodes;
  7365. var frameNodesCount = frameNodes.count;
  7366. var nodeOwners = clipStateInfo._nodeOwners;
  7367. nodeOwners.length = frameNodesCount;
  7368. for (var i = 0; i < frameNodesCount; i++) {
  7369. var node = frameNodes.getNodeByIndex(i);
  7370. var property = this._avatar ? this._avatarNodeMap[this._avatar._rootNode.name] : this.owner;
  7371. for (var j = 0, m = node.ownerPathCount; j < m; j++) {
  7372. var ownPat = node.getOwnerPathByIndex(j);
  7373. if (ownPat === "") {
  7374. break;
  7375. }
  7376. else {
  7377. property = property.getChildByName(ownPat);
  7378. if (!property)
  7379. break;
  7380. }
  7381. }
  7382. if (property) {
  7383. var propertyOwner = node.propertyOwner;
  7384. (propertyOwner) && (property = property[propertyOwner]);
  7385. property && this._addKeyframeNodeOwner(nodeOwners, node, property);
  7386. }
  7387. }
  7388. }
  7389. _updatePlayer(animatorState, playState, elapsedTime, islooping) {
  7390. var clipDuration = animatorState._clip._duration * (animatorState.clipEnd - animatorState.clipStart);
  7391. var lastElapsedTime = playState._elapsedTime;
  7392. var elapsedPlaybackTime = lastElapsedTime + elapsedTime;
  7393. playState._lastElapsedTime = lastElapsedTime;
  7394. playState._elapsedTime = elapsedPlaybackTime;
  7395. var normalizedTime = elapsedPlaybackTime / clipDuration;
  7396. playState._normalizedTime = normalizedTime;
  7397. var playTime = normalizedTime % 1.0;
  7398. playState._normalizedPlayTime = playTime < 0 ? playTime + 1.0 : playTime;
  7399. playState._duration = clipDuration;
  7400. var scripts = animatorState._scripts;
  7401. if ((!islooping && elapsedPlaybackTime >= clipDuration)) {
  7402. playState._finish = true;
  7403. playState._elapsedTime = clipDuration;
  7404. playState._normalizedPlayTime = 1.0;
  7405. if (scripts) {
  7406. for (var i = 0, n = scripts.length; i < n; i++)
  7407. scripts[i].onStateExit();
  7408. }
  7409. return;
  7410. }
  7411. if (scripts) {
  7412. for (i = 0, n = scripts.length; i < n; i++)
  7413. scripts[i].onStateUpdate();
  7414. }
  7415. }
  7416. _eventScript(scripts, events, eventIndex, endTime, front) {
  7417. if (front) {
  7418. for (var n = events.length; eventIndex < n; eventIndex++) {
  7419. var event = events[eventIndex];
  7420. if (event.time <= endTime) {
  7421. for (var j = 0, m = scripts.length; j < m; j++) {
  7422. var script = scripts[j];
  7423. var fun = script[event.eventName];
  7424. (fun) && (fun.apply(script, event.params));
  7425. }
  7426. }
  7427. else {
  7428. break;
  7429. }
  7430. }
  7431. }
  7432. else {
  7433. for (; eventIndex >= 0; eventIndex--) {
  7434. event = events[eventIndex];
  7435. if (event.time >= endTime) {
  7436. for (j = 0, m = scripts.length; j < m; j++) {
  7437. script = scripts[j];
  7438. fun = script[event.eventName];
  7439. (fun) && (fun.apply(script, event.params));
  7440. }
  7441. }
  7442. else {
  7443. break;
  7444. }
  7445. }
  7446. }
  7447. return eventIndex;
  7448. }
  7449. _updateEventScript(stateInfo, playStateInfo) {
  7450. var scripts = this.owner._scripts;
  7451. if (scripts) {
  7452. var clip = stateInfo._clip;
  7453. var events = clip._animationEvents;
  7454. var clipDuration = clip._duration;
  7455. var elapsedTime = playStateInfo._elapsedTime;
  7456. var time = elapsedTime % clipDuration;
  7457. var loopCount = Math.abs(Math.floor(elapsedTime / clipDuration) - Math.floor(playStateInfo._lastElapsedTime / clipDuration));
  7458. var frontPlay = playStateInfo._elapsedTime >= playStateInfo._lastElapsedTime;
  7459. if (playStateInfo._lastIsFront !== frontPlay) {
  7460. if (frontPlay)
  7461. playStateInfo._playEventIndex++;
  7462. else
  7463. playStateInfo._playEventIndex--;
  7464. playStateInfo._lastIsFront = frontPlay;
  7465. }
  7466. if (frontPlay) {
  7467. playStateInfo._playEventIndex = this._eventScript(scripts, events, playStateInfo._playEventIndex, loopCount > 0 ? clipDuration : time, true);
  7468. for (var i = 0, n = loopCount - 1; i < n; i++)
  7469. this._eventScript(scripts, events, 0, clipDuration, true);
  7470. (loopCount > 0 && time > 0) && (playStateInfo._playEventIndex = this._eventScript(scripts, events, 0, time, true));
  7471. }
  7472. else {
  7473. playStateInfo._playEventIndex = this._eventScript(scripts, events, playStateInfo._playEventIndex, loopCount > 0 ? 0 : time, false);
  7474. var eventIndex = events.length - 1;
  7475. for (i = 0, n = loopCount - 1; i < n; i++)
  7476. this._eventScript(scripts, events, eventIndex, 0, false);
  7477. (loopCount > 0 && time > 0) && (playStateInfo._playEventIndex = this._eventScript(scripts, events, eventIndex, time, false));
  7478. }
  7479. }
  7480. }
  7481. _updateClipDatas(animatorState, addtive, playStateInfo, scale) {
  7482. var clip = animatorState._clip;
  7483. var clipDuration = clip._duration;
  7484. var curPlayTime = animatorState.clipStart * clipDuration + playStateInfo._normalizedPlayTime * playStateInfo._duration;
  7485. var currentFrameIndices = animatorState._currentFrameIndices;
  7486. var frontPlay = playStateInfo._elapsedTime > playStateInfo._lastElapsedTime;
  7487. clip._evaluateClipDatasRealTime(clip._nodes, curPlayTime, currentFrameIndices, addtive, frontPlay, animatorState._realtimeDatas);
  7488. }
  7489. _applyFloat(pro, proName, nodeOwner, additive, weight, isFirstLayer, data) {
  7490. if (nodeOwner.updateMark === this._updateMark) {
  7491. if (additive) {
  7492. pro[proName] += weight * data;
  7493. }
  7494. else {
  7495. var oriValue = pro[proName];
  7496. pro[proName] = oriValue + weight * (data - oriValue);
  7497. }
  7498. }
  7499. else {
  7500. if (isFirstLayer) {
  7501. if (additive)
  7502. pro[proName] = nodeOwner.defaultValue + data;
  7503. else
  7504. pro[proName] = data;
  7505. }
  7506. else {
  7507. if (additive) {
  7508. pro[proName] = nodeOwner.defaultValue + weight * (data);
  7509. }
  7510. else {
  7511. var defValue = nodeOwner.defaultValue;
  7512. pro[proName] = defValue + weight * (data - defValue);
  7513. }
  7514. }
  7515. }
  7516. }
  7517. _applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, data, out) {
  7518. if (nodeOwner.updateMark === this._updateMark) {
  7519. if (additive) {
  7520. out.x += weight * data.x;
  7521. out.y += weight * data.y;
  7522. out.z += weight * data.z;
  7523. }
  7524. else {
  7525. var oriX = out.x;
  7526. var oriY = out.y;
  7527. var oriZ = out.z;
  7528. out.x = oriX + weight * (data.x - oriX);
  7529. out.y = oriY + weight * (data.y - oriY);
  7530. out.z = oriZ + weight * (data.z - oriZ);
  7531. }
  7532. }
  7533. else {
  7534. if (isFirstLayer) {
  7535. if (additive) {
  7536. var defValue = nodeOwner.defaultValue;
  7537. out.x = defValue.x + data.x;
  7538. out.y = defValue.y + data.y;
  7539. out.z = defValue.z + data.z;
  7540. }
  7541. else {
  7542. out.x = data.x;
  7543. out.y = data.y;
  7544. out.z = data.z;
  7545. }
  7546. }
  7547. else {
  7548. defValue = nodeOwner.defaultValue;
  7549. if (additive) {
  7550. out.x = defValue.x + weight * data.x;
  7551. out.y = defValue.y + weight * data.y;
  7552. out.z = defValue.z + weight * data.z;
  7553. }
  7554. else {
  7555. var defX = defValue.x;
  7556. var defY = defValue.y;
  7557. var defZ = defValue.z;
  7558. out.x = defX + weight * (data.x - defX);
  7559. out.y = defY + weight * (data.y - defY);
  7560. out.z = defZ + weight * (data.z - defZ);
  7561. }
  7562. }
  7563. }
  7564. }
  7565. _applyRotation(nodeOwner, additive, weight, isFirstLayer, clipRot, localRotation) {
  7566. if (nodeOwner.updateMark === this._updateMark) {
  7567. if (additive) {
  7568. var tempQuat = Animator._tempQuaternion1;
  7569. Utils3D.quaternionWeight(clipRot, weight, tempQuat);
  7570. tempQuat.normalize(tempQuat);
  7571. Quaternion.multiply(localRotation, tempQuat, localRotation);
  7572. }
  7573. else {
  7574. Quaternion.lerp(localRotation, clipRot, weight, localRotation);
  7575. }
  7576. }
  7577. else {
  7578. if (isFirstLayer) {
  7579. if (additive) {
  7580. var defaultRot = nodeOwner.defaultValue;
  7581. Quaternion.multiply(defaultRot, clipRot, localRotation);
  7582. }
  7583. else {
  7584. localRotation.x = clipRot.x;
  7585. localRotation.y = clipRot.y;
  7586. localRotation.z = clipRot.z;
  7587. localRotation.w = clipRot.w;
  7588. }
  7589. }
  7590. else {
  7591. defaultRot = nodeOwner.defaultValue;
  7592. if (additive) {
  7593. tempQuat = Animator._tempQuaternion1;
  7594. Utils3D.quaternionWeight(clipRot, weight, tempQuat);
  7595. tempQuat.normalize(tempQuat);
  7596. Quaternion.multiply(defaultRot, tempQuat, localRotation);
  7597. }
  7598. else {
  7599. Quaternion.lerp(defaultRot, clipRot, weight, localRotation);
  7600. }
  7601. }
  7602. }
  7603. }
  7604. _applyScale(nodeOwner, additive, weight, isFirstLayer, clipSca, localScale) {
  7605. if (nodeOwner.updateMark === this._updateMark) {
  7606. if (additive) {
  7607. var scale = Animator._tempVector31;
  7608. Utils3D.scaleWeight(clipSca, weight, scale);
  7609. localScale.x = localScale.x * scale.x;
  7610. localScale.y = localScale.y * scale.y;
  7611. localScale.z = localScale.z * scale.z;
  7612. }
  7613. else {
  7614. Utils3D.scaleBlend(localScale, clipSca, weight, localScale);
  7615. }
  7616. }
  7617. else {
  7618. if (isFirstLayer) {
  7619. if (additive) {
  7620. var defaultSca = nodeOwner.defaultValue;
  7621. localScale.x = defaultSca.x * clipSca.x;
  7622. localScale.y = defaultSca.y * clipSca.y;
  7623. localScale.z = defaultSca.z * clipSca.z;
  7624. }
  7625. else {
  7626. localScale.x = clipSca.x;
  7627. localScale.y = clipSca.y;
  7628. localScale.z = clipSca.z;
  7629. }
  7630. }
  7631. else {
  7632. defaultSca = nodeOwner.defaultValue;
  7633. if (additive) {
  7634. scale = Animator._tempVector31;
  7635. Utils3D.scaleWeight(clipSca, weight, scale);
  7636. localScale.x = defaultSca.x * scale.x;
  7637. localScale.y = defaultSca.y * scale.y;
  7638. localScale.z = defaultSca.z * scale.z;
  7639. }
  7640. else {
  7641. Utils3D.scaleBlend(defaultSca, clipSca, weight, localScale);
  7642. }
  7643. }
  7644. }
  7645. }
  7646. _applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight) {
  7647. var pro = nodeOwner.propertyOwner;
  7648. if (pro) {
  7649. switch (nodeOwner.type) {
  7650. case 0:
  7651. var proPat = nodeOwner.property;
  7652. var m = proPat.length - 1;
  7653. for (var j = 0; j < m; j++) {
  7654. pro = pro[proPat[j]];
  7655. if (!pro)
  7656. break;
  7657. }
  7658. var crossValue = srcValue + crossWeight * (desValue - srcValue);
  7659. nodeOwner.value = crossValue;
  7660. this._applyFloat(pro, proPat[m], nodeOwner, additive, weight, isFirstLayer, crossValue);
  7661. break;
  7662. case 1:
  7663. var localPos = pro.localPosition;
  7664. var position = nodeOwner.value;
  7665. var srcX = srcValue.x, srcY = srcValue.y, srcZ = srcValue.z;
  7666. position.x = srcX + crossWeight * (desValue.x - srcX);
  7667. position.y = srcY + crossWeight * (desValue.y - srcY);
  7668. position.z = srcZ + crossWeight * (desValue.z - srcZ);
  7669. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, position, localPos);
  7670. pro.localPosition = localPos;
  7671. break;
  7672. case 2:
  7673. var localRot = pro.localRotation;
  7674. var rotation = nodeOwner.value;
  7675. Quaternion.lerp(srcValue, desValue, crossWeight, rotation);
  7676. this._applyRotation(nodeOwner, additive, weight, isFirstLayer, rotation, localRot);
  7677. pro.localRotation = localRot;
  7678. break;
  7679. case 3:
  7680. var localSca = pro.localScale;
  7681. var scale = nodeOwner.value;
  7682. Utils3D.scaleBlend(srcValue, desValue, crossWeight, scale);
  7683. this._applyScale(nodeOwner, additive, weight, isFirstLayer, scale, localSca);
  7684. pro.localScale = localSca;
  7685. break;
  7686. case 4:
  7687. var localEuler = pro.localRotationEuler;
  7688. var rotationEuler = nodeOwner.value;
  7689. srcX = srcValue.x, srcY = srcValue.y, srcZ = srcValue.z;
  7690. rotationEuler.x = srcX + crossWeight * (desValue.x - srcX);
  7691. rotationEuler.y = srcY + crossWeight * (desValue.y - srcY);
  7692. rotationEuler.z = srcZ + crossWeight * (desValue.z - srcZ);
  7693. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, rotationEuler, localEuler);
  7694. pro.localRotationEuler = localEuler;
  7695. break;
  7696. }
  7697. nodeOwner.updateMark = this._updateMark;
  7698. }
  7699. }
  7700. _setClipDatasToNode(stateInfo, additive, weight, isFirstLayer) {
  7701. var realtimeDatas = stateInfo._realtimeDatas;
  7702. var nodes = stateInfo._clip._nodes;
  7703. var nodeOwners = stateInfo._nodeOwners;
  7704. for (var i = 0, n = nodes.count; i < n; i++) {
  7705. var nodeOwner = nodeOwners[i];
  7706. if (nodeOwner) {
  7707. var pro = nodeOwner.propertyOwner;
  7708. if (pro) {
  7709. switch (nodeOwner.type) {
  7710. case 0:
  7711. var proPat = nodeOwner.property;
  7712. var m = proPat.length - 1;
  7713. for (var j = 0; j < m; j++) {
  7714. pro = pro[proPat[j]];
  7715. if (!pro)
  7716. break;
  7717. }
  7718. this._applyFloat(pro, proPat[m], nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i]);
  7719. break;
  7720. case 1:
  7721. var localPos = pro.localPosition;
  7722. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localPos);
  7723. pro.localPosition = localPos;
  7724. break;
  7725. case 2:
  7726. var localRot = pro.localRotation;
  7727. this._applyRotation(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localRot);
  7728. pro.localRotation = localRot;
  7729. break;
  7730. case 3:
  7731. var localSca = pro.localScale;
  7732. this._applyScale(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localSca);
  7733. pro.localScale = localSca;
  7734. break;
  7735. case 4:
  7736. var localEuler = pro.localRotationEuler;
  7737. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localEuler);
  7738. pro.localRotationEuler = localEuler;
  7739. break;
  7740. }
  7741. nodeOwner.updateMark = this._updateMark;
  7742. }
  7743. }
  7744. }
  7745. }
  7746. _setCrossClipDatasToNode(controllerLayer, srcState, destState, crossWeight, isFirstLayer) {
  7747. var nodeOwners = controllerLayer._crossNodesOwners;
  7748. var ownerCount = controllerLayer._crossNodesOwnersCount;
  7749. var additive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  7750. var weight = controllerLayer.defaultWeight;
  7751. var destRealtimeDatas = destState._realtimeDatas;
  7752. var destDataIndices = controllerLayer._destCrossClipNodeIndices;
  7753. var destNodeOwners = destState._nodeOwners;
  7754. var srcRealtimeDatas = srcState._realtimeDatas;
  7755. var srcDataIndices = controllerLayer._srcCrossClipNodeIndices;
  7756. var srcNodeOwners = srcState._nodeOwners;
  7757. for (var i = 0; i < ownerCount; i++) {
  7758. var nodeOwner = nodeOwners[i];
  7759. if (nodeOwner) {
  7760. var srcIndex = srcDataIndices[i];
  7761. var destIndex = destDataIndices[i];
  7762. var srcValue = srcIndex !== -1 ? srcRealtimeDatas[srcIndex] : destNodeOwners[destIndex].defaultValue;
  7763. var desValue = destIndex !== -1 ? destRealtimeDatas[destIndex] : srcNodeOwners[srcIndex].defaultValue;
  7764. this._applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight);
  7765. }
  7766. }
  7767. }
  7768. _setFixedCrossClipDatasToNode(controllerLayer, destState, crossWeight, isFirstLayer) {
  7769. var nodeOwners = controllerLayer._crossNodesOwners;
  7770. var ownerCount = controllerLayer._crossNodesOwnersCount;
  7771. var additive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  7772. var weight = controllerLayer.defaultWeight;
  7773. var destRealtimeDatas = destState._realtimeDatas;
  7774. var destDataIndices = controllerLayer._destCrossClipNodeIndices;
  7775. for (var i = 0; i < ownerCount; i++) {
  7776. var nodeOwner = nodeOwners[i];
  7777. if (nodeOwner) {
  7778. var destIndex = destDataIndices[i];
  7779. var srcValue = nodeOwner.crossFixedValue;
  7780. var desValue = destIndex !== -1 ? destRealtimeDatas[destIndex] : nodeOwner.defaultValue;
  7781. this._applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight);
  7782. }
  7783. }
  7784. }
  7785. _revertDefaultKeyframeNodes(clipStateInfo) {
  7786. var nodeOwners = clipStateInfo._nodeOwners;
  7787. for (var i = 0, n = nodeOwners.length; i < n; i++) {
  7788. var nodeOwner = nodeOwners[i];
  7789. if (nodeOwner) {
  7790. var pro = nodeOwner.propertyOwner;
  7791. if (pro) {
  7792. switch (nodeOwner.type) {
  7793. case 0:
  7794. var proPat = nodeOwner.property;
  7795. var m = proPat.length - 1;
  7796. for (var j = 0; j < m; j++) {
  7797. pro = pro[proPat[j]];
  7798. if (!pro)
  7799. break;
  7800. }
  7801. pro[proPat[m]] = nodeOwner.defaultValue;
  7802. break;
  7803. case 1:
  7804. var locPos = pro.localPosition;
  7805. var def = nodeOwner.defaultValue;
  7806. locPos.x = def.x;
  7807. locPos.y = def.y;
  7808. locPos.z = def.z;
  7809. pro.localPosition = locPos;
  7810. break;
  7811. case 2:
  7812. var locRot = pro.localRotation;
  7813. var defQua = nodeOwner.defaultValue;
  7814. locRot.x = defQua.x;
  7815. locRot.y = defQua.y;
  7816. locRot.z = defQua.z;
  7817. locRot.w = defQua.w;
  7818. pro.localRotation = locRot;
  7819. break;
  7820. case 3:
  7821. var locSca = pro.localScale;
  7822. def = nodeOwner.defaultValue;
  7823. locSca.x = def.x;
  7824. locSca.y = def.y;
  7825. locSca.z = def.z;
  7826. pro.localScale = locSca;
  7827. break;
  7828. case 4:
  7829. var locEul = pro.localRotationEuler;
  7830. def = nodeOwner.defaultValue;
  7831. locEul.x = def.x;
  7832. locEul.y = def.y;
  7833. locEul.z = def.z;
  7834. pro.localRotationEuler = locEul;
  7835. break;
  7836. default:
  7837. throw "Animator:unknown type.";
  7838. }
  7839. }
  7840. }
  7841. }
  7842. }
  7843. _onAdded() {
  7844. var parent = this.owner._parent;
  7845. this.owner._setHierarchyAnimator(this, parent ? parent._hierarchyAnimator : null);
  7846. this.owner._changeAnimatorToLinkSprite3DNoAvatar(this, true, []);
  7847. }
  7848. _onDestroy() {
  7849. for (var i = 0, n = this._controllerLayers.length; i < n; i++)
  7850. this._controllerLayers[i]._removeReference();
  7851. var parent = this.owner._parent;
  7852. this.owner._clearHierarchyAnimator(this, parent ? parent._hierarchyAnimator : null);
  7853. }
  7854. _onEnable() {
  7855. this.owner._scene._animatorPool.add(this);
  7856. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  7857. if (this._controllerLayers[i].playOnWake) {
  7858. var defaultClip = this.getDefaultState(i);
  7859. (defaultClip) && (this.play(null, i, 0));
  7860. }
  7861. }
  7862. }
  7863. _onDisable() {
  7864. this.owner._scene._animatorPool.remove(this);
  7865. }
  7866. _handleSpriteOwnersBySprite(isLink, path, sprite) {
  7867. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  7868. var clipStateInfos = this._controllerLayers[i]._states;
  7869. for (var j = 0, m = clipStateInfos.length; j < m; j++) {
  7870. var clipStateInfo = clipStateInfos[j];
  7871. var clip = clipStateInfo._clip;
  7872. var nodePath = path.join("/");
  7873. var ownersNodes = clip._nodesMap[nodePath];
  7874. if (ownersNodes) {
  7875. var nodeOwners = clipStateInfo._nodeOwners;
  7876. for (var k = 0, p = ownersNodes.length; k < p; k++) {
  7877. if (isLink)
  7878. this._addKeyframeNodeOwner(nodeOwners, ownersNodes[k], sprite);
  7879. else
  7880. this._removeKeyframeNodeOwner(nodeOwners, ownersNodes[k]);
  7881. }
  7882. }
  7883. }
  7884. }
  7885. }
  7886. _parse(data) {
  7887. var avatarData = data.avatar;
  7888. if (avatarData) {
  7889. this.avatar = Laya.Loader.getRes(avatarData.path);
  7890. var linkSprites = avatarData.linkSprites;
  7891. this._linkSprites = linkSprites;
  7892. this._linkToSprites(linkSprites);
  7893. }
  7894. var clipPaths = data.clipPaths;
  7895. var play = data.playOnWake;
  7896. var layersData = data.layers;
  7897. for (var i = 0; i < layersData.length; i++) {
  7898. var layerData = layersData[i];
  7899. var animatorLayer = new AnimatorControllerLayer(layerData.name);
  7900. if (i === 0)
  7901. animatorLayer.defaultWeight = 1.0;
  7902. else
  7903. animatorLayer.defaultWeight = layerData.weight;
  7904. var blendingModeData = layerData.blendingMode;
  7905. (blendingModeData) && (animatorLayer.blendingMode = blendingModeData);
  7906. this.addControllerLayer(animatorLayer);
  7907. var states = layerData.states;
  7908. for (var j = 0, m = states.length; j < m; j++) {
  7909. var state = states[j];
  7910. var clipPath = state.clipPath;
  7911. if (clipPath) {
  7912. var name = state.name;
  7913. var motion;
  7914. motion = Laya.Loader.getRes(clipPath);
  7915. if (motion) {
  7916. var animatorState = new AnimatorState();
  7917. animatorState.name = name;
  7918. animatorState.clip = motion;
  7919. animatorLayer.addState(animatorState);
  7920. (j === 0) && (this.getControllerLayer(i).defaultState = animatorState);
  7921. }
  7922. }
  7923. }
  7924. (play !== undefined) && (animatorLayer.playOnWake = play);
  7925. }
  7926. var cullingModeData = data.cullingMode;
  7927. (cullingModeData !== undefined) && (this.cullingMode = cullingModeData);
  7928. }
  7929. _update() {
  7930. var timer = this.owner._scene.timer;
  7931. var delta = timer._delta / 1000.0;
  7932. if (this._speed === 0 || delta === 0)
  7933. return;
  7934. var needRender;
  7935. if (this.cullingMode === Animator.CULLINGMODE_CULLCOMPLETELY) {
  7936. needRender = false;
  7937. for (var i = 0, n = this._renderableSprites.length; i < n; i++) {
  7938. if (this._renderableSprites[i]._render.isRender) {
  7939. needRender = true;
  7940. break;
  7941. }
  7942. }
  7943. }
  7944. else {
  7945. needRender = true;
  7946. }
  7947. this._updateMark++;
  7948. var timerScale = timer.scale;
  7949. for (i = 0, n = this._controllerLayers.length; i < n; i++) {
  7950. var controllerLayer = this._controllerLayers[i];
  7951. var playStateInfo = controllerLayer._playStateInfo;
  7952. var crossPlayStateInfo = controllerLayer._crossPlayStateInfo;
  7953. addtive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  7954. switch (controllerLayer._playType) {
  7955. case 0:
  7956. var animatorState = playStateInfo._currentState;
  7957. var clip = animatorState._clip;
  7958. var speed = this._speed * animatorState.speed;
  7959. var finish = playStateInfo._finish;
  7960. finish || this._updatePlayer(animatorState, playStateInfo, delta * speed, clip.islooping);
  7961. if (needRender) {
  7962. var addtive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  7963. this._updateClipDatas(animatorState, addtive, playStateInfo, timerScale * speed);
  7964. this._setClipDatasToNode(animatorState, addtive, controllerLayer.defaultWeight, i === 0);
  7965. finish || this._updateEventScript(animatorState, playStateInfo);
  7966. }
  7967. break;
  7968. case 1:
  7969. animatorState = playStateInfo._currentState;
  7970. clip = animatorState._clip;
  7971. var crossState = controllerLayer._crossPlayState;
  7972. var crossClip = crossState._clip;
  7973. var crossDuratuion = controllerLayer._crossDuration;
  7974. var startPlayTime = crossPlayStateInfo._startPlayTime;
  7975. var crossClipDuration = crossClip._duration - startPlayTime;
  7976. var crossScale = crossDuratuion > crossClipDuration ? crossClipDuration / crossDuratuion : 1.0;
  7977. var crossSpeed = this._speed * crossState.speed;
  7978. this._updatePlayer(crossState, crossPlayStateInfo, delta * crossScale * crossSpeed, crossClip.islooping);
  7979. var crossWeight = ((crossPlayStateInfo._elapsedTime - startPlayTime) / crossScale) / crossDuratuion;
  7980. if (crossWeight >= 1.0) {
  7981. if (needRender) {
  7982. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossSpeed);
  7983. this._setClipDatasToNode(crossState, addtive, controllerLayer.defaultWeight, i === 0);
  7984. controllerLayer._playType = 0;
  7985. playStateInfo._currentState = crossState;
  7986. crossPlayStateInfo._cloneTo(playStateInfo);
  7987. }
  7988. }
  7989. else {
  7990. if (!playStateInfo._finish) {
  7991. speed = this._speed * animatorState.speed;
  7992. this._updatePlayer(animatorState, playStateInfo, delta * speed, clip.islooping);
  7993. if (needRender)
  7994. this._updateClipDatas(animatorState, addtive, playStateInfo, timerScale * speed);
  7995. }
  7996. if (needRender) {
  7997. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossScale * crossSpeed);
  7998. this._setCrossClipDatasToNode(controllerLayer, animatorState, crossState, crossWeight, i === 0);
  7999. }
  8000. }
  8001. if (needRender) {
  8002. this._updateEventScript(animatorState, playStateInfo);
  8003. this._updateEventScript(crossState, crossPlayStateInfo);
  8004. }
  8005. break;
  8006. case 2:
  8007. crossState = controllerLayer._crossPlayState;
  8008. crossClip = crossState._clip;
  8009. crossDuratuion = controllerLayer._crossDuration;
  8010. startPlayTime = crossPlayStateInfo._startPlayTime;
  8011. crossClipDuration = crossClip._duration - startPlayTime;
  8012. crossScale = crossDuratuion > crossClipDuration ? crossClipDuration / crossDuratuion : 1.0;
  8013. crossSpeed = this._speed * crossState.speed;
  8014. this._updatePlayer(crossState, crossPlayStateInfo, delta * crossScale * crossSpeed, crossClip.islooping);
  8015. if (needRender) {
  8016. crossWeight = ((crossPlayStateInfo._elapsedTime - startPlayTime) / crossScale) / crossDuratuion;
  8017. if (crossWeight >= 1.0) {
  8018. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossSpeed);
  8019. this._setClipDatasToNode(crossState, addtive, 1.0, i === 0);
  8020. controllerLayer._playType = 0;
  8021. playStateInfo._currentState = crossState;
  8022. crossPlayStateInfo._cloneTo(playStateInfo);
  8023. }
  8024. else {
  8025. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossScale * crossSpeed);
  8026. this._setFixedCrossClipDatasToNode(controllerLayer, crossState, crossWeight, i === 0);
  8027. }
  8028. this._updateEventScript(crossState, crossPlayStateInfo);
  8029. }
  8030. break;
  8031. }
  8032. }
  8033. if (needRender) {
  8034. if (this._avatar) {
  8035. Laya.Render.supportWebGLPlusAnimation && this._updateAnimationNodeWorldMatix(this._animationNodeLocalPositions, this._animationNodeLocalRotations, this._animationNodeLocalScales, this._animationNodeWorldMatrixs, this._animationNodeParentIndices);
  8036. this._updateAvatarNodesToSprite();
  8037. }
  8038. }
  8039. }
  8040. _cloneTo(dest) {
  8041. var animator = dest;
  8042. animator.avatar = this.avatar;
  8043. animator.cullingMode = this.cullingMode;
  8044. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  8045. var controllLayer = this._controllerLayers[i];
  8046. animator.addControllerLayer(controllLayer.clone());
  8047. var animatorStates = controllLayer._states;
  8048. for (var j = 0, m = animatorStates.length; j < m; j++) {
  8049. var state = animatorStates[j].clone();
  8050. var cloneLayer = animator.getControllerLayer(i);
  8051. cloneLayer.addState(state);
  8052. (j == 0) && (cloneLayer.defaultState = state);
  8053. }
  8054. }
  8055. animator._linkSprites = this._linkSprites;
  8056. animator._linkToSprites(this._linkSprites);
  8057. }
  8058. getDefaultState(layerIndex = 0) {
  8059. var controllerLayer = this._controllerLayers[layerIndex];
  8060. return controllerLayer.defaultState;
  8061. }
  8062. addState(state, layerIndex = 0) {
  8063. var controllerLayer = this._controllerLayers[layerIndex];
  8064. controllerLayer.addState(state);
  8065. console.warn("Animator:this function is discard,please use animatorControllerLayer.addState() instead.");
  8066. }
  8067. removeState(state, layerIndex = 0) {
  8068. var controllerLayer = this._controllerLayers[layerIndex];
  8069. controllerLayer.removeState(state);
  8070. console.warn("Animator:this function is discard,please use animatorControllerLayer.removeState() instead.");
  8071. }
  8072. addControllerLayer(controllderLayer) {
  8073. this._controllerLayers.push(controllderLayer);
  8074. controllderLayer._animator = this;
  8075. controllderLayer._addReference();
  8076. var states = controllderLayer._states;
  8077. for (var i = 0, n = states.length; i < n; i++)
  8078. this._getOwnersByClip(states[i]);
  8079. }
  8080. getControllerLayer(layerInex = 0) {
  8081. return this._controllerLayers[layerInex];
  8082. }
  8083. play(name = null, layerIndex = 0, normalizedTime = Number.NEGATIVE_INFINITY) {
  8084. var controllerLayer = this._controllerLayers[layerIndex];
  8085. if (controllerLayer) {
  8086. var defaultState = controllerLayer.defaultState;
  8087. if (!name && !defaultState)
  8088. throw new Error("Animator:must have default clip value,please set clip property.");
  8089. var playStateInfo = controllerLayer._playStateInfo;
  8090. var curPlayState = playStateInfo._currentState;
  8091. var animatorState = name ? controllerLayer._statesMap[name] : defaultState;
  8092. var clipDuration = animatorState._clip._duration;
  8093. if (curPlayState !== animatorState) {
  8094. if (normalizedTime !== Number.NEGATIVE_INFINITY)
  8095. playStateInfo._resetPlayState(clipDuration * normalizedTime);
  8096. else
  8097. playStateInfo._resetPlayState(0.0);
  8098. (curPlayState !== null && curPlayState !== animatorState) && (this._revertDefaultKeyframeNodes(curPlayState));
  8099. controllerLayer._playType = 0;
  8100. playStateInfo._currentState = animatorState;
  8101. }
  8102. else {
  8103. if (normalizedTime !== Number.NEGATIVE_INFINITY) {
  8104. playStateInfo._resetPlayState(clipDuration * normalizedTime);
  8105. controllerLayer._playType = 0;
  8106. }
  8107. }
  8108. var scripts = animatorState._scripts;
  8109. if (scripts) {
  8110. for (var i = 0, n = scripts.length; i < n; i++)
  8111. scripts[i].onStateEnter();
  8112. }
  8113. }
  8114. else {
  8115. console.warn("Invalid layerIndex " + layerIndex + ".");
  8116. }
  8117. }
  8118. crossFade(name, transitionDuration, layerIndex = 0, normalizedTime = Number.NEGATIVE_INFINITY) {
  8119. var controllerLayer = this._controllerLayers[layerIndex];
  8120. if (controllerLayer) {
  8121. var destAnimatorState = controllerLayer._statesMap[name];
  8122. if (destAnimatorState) {
  8123. var playType = controllerLayer._playType;
  8124. if (playType === -1) {
  8125. this.play(name, layerIndex, normalizedTime);
  8126. return;
  8127. }
  8128. var crossPlayStateInfo = controllerLayer._crossPlayStateInfo;
  8129. var crossNodeOwners = controllerLayer._crossNodesOwners;
  8130. var crossNodeOwnerIndicesMap = controllerLayer._crossNodesOwnersIndicesMap;
  8131. var srcAnimatorState = controllerLayer._playStateInfo._currentState;
  8132. var destNodeOwners = destAnimatorState._nodeOwners;
  8133. var destCrossClipNodeIndices = controllerLayer._destCrossClipNodeIndices;
  8134. var destClip = destAnimatorState._clip;
  8135. var destNodes = destClip._nodes;
  8136. var destNodesMap = destClip._nodesDic;
  8137. switch (playType) {
  8138. case 0:
  8139. var srcNodeOwners = srcAnimatorState._nodeOwners;
  8140. var scrCrossClipNodeIndices = controllerLayer._srcCrossClipNodeIndices;
  8141. var srcClip = srcAnimatorState._clip;
  8142. var srcNodes = srcClip._nodes;
  8143. var srcNodesMap = srcClip._nodesDic;
  8144. controllerLayer._playType = 1;
  8145. var crossMark = ++controllerLayer._crossMark;
  8146. var crossCount = controllerLayer._crossNodesOwnersCount = 0;
  8147. for (var i = 0, n = srcNodes.count; i < n; i++) {
  8148. var srcNode = srcNodes.getNodeByIndex(i);
  8149. var srcIndex = srcNode._indexInList;
  8150. var srcNodeOwner = srcNodeOwners[srcIndex];
  8151. if (srcNodeOwner) {
  8152. var srcFullPath = srcNode.fullPath;
  8153. scrCrossClipNodeIndices[crossCount] = srcIndex;
  8154. var destNode = destNodesMap[srcFullPath];
  8155. if (destNode)
  8156. destCrossClipNodeIndices[crossCount] = destNode._indexInList;
  8157. else
  8158. destCrossClipNodeIndices[crossCount] = -1;
  8159. crossNodeOwnerIndicesMap[srcFullPath] = crossMark;
  8160. crossNodeOwners[crossCount] = srcNodeOwner;
  8161. crossCount++;
  8162. }
  8163. }
  8164. for (i = 0, n = destNodes.count; i < n; i++) {
  8165. destNode = destNodes.getNodeByIndex(i);
  8166. var destIndex = destNode._indexInList;
  8167. var destNodeOwner = destNodeOwners[destIndex];
  8168. if (destNodeOwner) {
  8169. var destFullPath = destNode.fullPath;
  8170. if (!srcNodesMap[destFullPath]) {
  8171. scrCrossClipNodeIndices[crossCount] = -1;
  8172. destCrossClipNodeIndices[crossCount] = destIndex;
  8173. crossNodeOwnerIndicesMap[destFullPath] = crossMark;
  8174. crossNodeOwners[crossCount] = destNodeOwner;
  8175. crossCount++;
  8176. }
  8177. }
  8178. }
  8179. break;
  8180. case 1:
  8181. case 2:
  8182. controllerLayer._playType = 2;
  8183. for (i = 0, n = crossNodeOwners.length; i < n; i++) {
  8184. var nodeOwner = crossNodeOwners[i];
  8185. nodeOwner.saveCrossFixedValue();
  8186. destNode = destNodesMap[nodeOwner.fullPath];
  8187. if (destNode)
  8188. destCrossClipNodeIndices[i] = destNode._indexInList;
  8189. else
  8190. destCrossClipNodeIndices[i] = -1;
  8191. }
  8192. crossCount = controllerLayer._crossNodesOwnersCount;
  8193. crossMark = controllerLayer._crossMark;
  8194. for (i = 0, n = destNodes.count; i < n; i++) {
  8195. destNode = destNodes.getNodeByIndex(i);
  8196. destIndex = destNode._indexInList;
  8197. destNodeOwner = destNodeOwners[destIndex];
  8198. if (destNodeOwner) {
  8199. destFullPath = destNode.fullPath;
  8200. if (crossNodeOwnerIndicesMap[destFullPath] !== crossMark) {
  8201. destCrossClipNodeIndices[crossCount] = destIndex;
  8202. crossNodeOwnerIndicesMap[destFullPath] = crossMark;
  8203. nodeOwner = destNodeOwners[destIndex];
  8204. crossNodeOwners[crossCount] = nodeOwner;
  8205. nodeOwner.saveCrossFixedValue();
  8206. crossCount++;
  8207. }
  8208. }
  8209. }
  8210. break;
  8211. default:
  8212. }
  8213. controllerLayer._crossNodesOwnersCount = crossCount;
  8214. controllerLayer._crossPlayState = destAnimatorState;
  8215. controllerLayer._crossDuration = srcAnimatorState._clip._duration * transitionDuration;
  8216. if (normalizedTime !== Number.NEGATIVE_INFINITY)
  8217. crossPlayStateInfo._resetPlayState(destClip._duration * normalizedTime);
  8218. else
  8219. crossPlayStateInfo._resetPlayState(0.0);
  8220. var scripts = destAnimatorState._scripts;
  8221. if (scripts) {
  8222. for (i = 0, n = scripts.length; i < n; i++)
  8223. scripts[i].onStateEnter();
  8224. }
  8225. }
  8226. else {
  8227. console.warn("Invalid name " + layerIndex + ".");
  8228. }
  8229. }
  8230. else {
  8231. console.warn("Invalid layerIndex " + layerIndex + ".");
  8232. }
  8233. }
  8234. getCurrentAnimatorPlayState(layerInex = 0) {
  8235. return this._controllerLayers[layerInex]._playStateInfo;
  8236. }
  8237. get avatar() {
  8238. return this._avatar;
  8239. }
  8240. set avatar(value) {
  8241. if (this._avatar !== value) {
  8242. this._avatar = value;
  8243. if (value) {
  8244. this._getAvatarOwnersAndInitDatasAsync();
  8245. this.owner._changeHierarchyAnimatorAvatar(this, value);
  8246. }
  8247. else {
  8248. var parent = this.owner._parent;
  8249. this.owner._changeHierarchyAnimatorAvatar(this, parent ? parent._hierarchyAnimator._avatar : null);
  8250. }
  8251. }
  8252. }
  8253. _isLinkSpriteToAnimationNodeData(sprite, nodeName, isLink) {
  8254. var linkSprites = this._linkAvatarSpritesData[nodeName];
  8255. if (isLink) {
  8256. linkSprites || (this._linkAvatarSpritesData[nodeName] = linkSprites = []);
  8257. linkSprites.push(sprite);
  8258. }
  8259. else {
  8260. var index = linkSprites.indexOf(sprite);
  8261. linkSprites.splice(index, 1);
  8262. }
  8263. }
  8264. _getAvatarOwnersAndInitDatasAsync() {
  8265. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  8266. var clipStateInfos = this._controllerLayers[i]._states;
  8267. for (var j = 0, m = clipStateInfos.length; j < m; j++)
  8268. this._getOwnersByClip(clipStateInfos[j]);
  8269. }
  8270. this._avatar._cloneDatasToAnimator(this);
  8271. for (var k in this._linkAvatarSpritesData) {
  8272. var sprites = this._linkAvatarSpritesData[k];
  8273. if (sprites) {
  8274. for (var c = 0, p = sprites.length; c < p; c++)
  8275. this._isLinkSpriteToAnimationNode(sprites[c], k, true);
  8276. }
  8277. }
  8278. }
  8279. _isLinkSpriteToAnimationNode(sprite, nodeName, isLink) {
  8280. if (this._avatar) {
  8281. var node = this._avatarNodeMap[nodeName];
  8282. if (node) {
  8283. if (isLink) {
  8284. sprite._transform._dummy = node.transform;
  8285. this._linkAvatarSprites.push(sprite);
  8286. var nodeTransform = node.transform;
  8287. var spriteTransform = sprite.transform;
  8288. if (!spriteTransform.owner.isStatic && nodeTransform) {
  8289. var spriteWorldMatrix = spriteTransform.worldMatrix;
  8290. var ownParTra = this.owner._transform._parent;
  8291. if (ownParTra) {
  8292. Utils3D.matrix4x4MultiplyMFM(ownParTra.worldMatrix, nodeTransform.getWorldMatrix(), spriteWorldMatrix);
  8293. }
  8294. else {
  8295. var sprWorE = spriteWorldMatrix.elements;
  8296. var nodWorE = nodeTransform.getWorldMatrix();
  8297. for (var i = 0; i < 16; i++)
  8298. sprWorE[i] = nodWorE[i];
  8299. }
  8300. spriteTransform.worldMatrix = spriteWorldMatrix;
  8301. }
  8302. }
  8303. else {
  8304. sprite._transform._dummy = null;
  8305. this._linkAvatarSprites.splice(this._linkAvatarSprites.indexOf(sprite), 1);
  8306. }
  8307. }
  8308. }
  8309. }
  8310. _updateAvatarNodesToSprite() {
  8311. for (var i = 0, n = this._linkAvatarSprites.length; i < n; i++) {
  8312. var sprite = this._linkAvatarSprites[i];
  8313. var nodeTransform = sprite.transform._dummy;
  8314. var spriteTransform = sprite.transform;
  8315. if (!spriteTransform.owner.isStatic && nodeTransform) {
  8316. var spriteWorldMatrix = spriteTransform.worldMatrix;
  8317. var ownTra = this.owner._transform;
  8318. Utils3D.matrix4x4MultiplyMFM(ownTra.worldMatrix, nodeTransform.getWorldMatrix(), spriteWorldMatrix);
  8319. spriteTransform.worldMatrix = spriteWorldMatrix;
  8320. }
  8321. }
  8322. }
  8323. linkSprite3DToAvatarNode(nodeName, sprite3D) {
  8324. this._isLinkSpriteToAnimationNodeData(sprite3D, nodeName, true);
  8325. this._isLinkSpriteToAnimationNode(sprite3D, nodeName, true);
  8326. return true;
  8327. }
  8328. unLinkSprite3DToAvatarNode(sprite3D) {
  8329. var dummy = sprite3D.transform._dummy;
  8330. if (dummy) {
  8331. var nodeName = dummy._owner.name;
  8332. this._isLinkSpriteToAnimationNodeData(sprite3D, nodeName, false);
  8333. this._isLinkSpriteToAnimationNode(sprite3D, nodeName, false);
  8334. return true;
  8335. }
  8336. else {
  8337. return false;
  8338. }
  8339. }
  8340. _updateAnimationNodeWorldMatix(localPositions, localRotations, localScales, worldMatrixs, parentIndices) {
  8341. Laya.LayaGL.instance.updateAnimationNodeWorldMatix(localPositions, localRotations, localScales, parentIndices, worldMatrixs);
  8342. }
  8343. }
  8344. Animator._tempVector30 = new Vector3();
  8345. Animator._tempVector31 = new Vector3();
  8346. Animator._tempQuaternion0 = new Quaternion();
  8347. Animator._tempQuaternion1 = new Quaternion();
  8348. Animator.CULLINGMODE_ALWAYSANIMATE = 0;
  8349. Animator.CULLINGMODE_CULLCOMPLETELY = 2;
  8350. class PostProcessRenderContext {
  8351. constructor() {
  8352. this.source = null;
  8353. this.destination = null;
  8354. this.camera = null;
  8355. this.compositeShaderData = null;
  8356. this.command = null;
  8357. this.deferredReleaseTextures = [];
  8358. }
  8359. }
  8360. class RenderContext3D {
  8361. constructor() {
  8362. this.invertY = false;
  8363. }
  8364. }
  8365. RenderContext3D._instance = new RenderContext3D();
  8366. class RenderTexture extends Laya.BaseTexture {
  8367. constructor(width, height, format = Laya.RenderTextureFormat.R8G8B8, depthStencilFormat = Laya.RenderTextureDepthFormat.DEPTH_16) {
  8368. super(format, false);
  8369. this._inPool = false;
  8370. this._isCameraTarget = false;
  8371. this._glTextureType = Laya.LayaGL.instance.TEXTURE_2D;
  8372. this._width = width;
  8373. this._height = height;
  8374. this._depthStencilFormat = depthStencilFormat;
  8375. this._mipmapCount = 1;
  8376. this._create(width, height);
  8377. }
  8378. static get currentActive() {
  8379. return RenderTexture._currentActive;
  8380. }
  8381. static createFromPool(width, height, format = Laya.RenderTextureFormat.R8G8B8, depthStencilFormat = Laya.RenderTextureDepthFormat.DEPTH_16) {
  8382. var tex;
  8383. for (var i = 0, n = RenderTexture._pool.length; i < n; i++) {
  8384. tex = RenderTexture._pool[i];
  8385. if (tex._width == width && tex._height == height && tex._format == format && tex._depthStencilFormat == depthStencilFormat) {
  8386. tex._inPool = false;
  8387. var end = RenderTexture._pool[n - 1];
  8388. RenderTexture._pool[i] = end;
  8389. RenderTexture._pool.length -= 1;
  8390. return tex;
  8391. }
  8392. }
  8393. tex = new RenderTexture(width, height, format, depthStencilFormat);
  8394. tex.lock = true;
  8395. return tex;
  8396. }
  8397. static recoverToPool(renderTexture) {
  8398. if (renderTexture._inPool)
  8399. return;
  8400. RenderTexture._pool.push(renderTexture);
  8401. renderTexture._inPool = true;
  8402. }
  8403. get depthStencilFormat() {
  8404. return this._depthStencilFormat;
  8405. }
  8406. get defaulteTexture() {
  8407. return Laya.Texture2D.grayTexture;
  8408. }
  8409. _create(width, height) {
  8410. var gl = Laya.LayaGL.instance;
  8411. var gl2 = gl;
  8412. var glTextureType = this._glTextureType;
  8413. var layaGPU = Laya.LayaGL.layaGPUInstance;
  8414. var isWebGL2 = layaGPU._isWebGL2;
  8415. var format = this._format;
  8416. this._frameBuffer = gl.createFramebuffer();
  8417. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  8418. if (format !== Laya.RenderTextureFormat.Depth && format !== Laya.RenderTextureFormat.ShadowMap) {
  8419. Laya.WebGLContext.bindTexture(gl, glTextureType, this._glTexture);
  8420. switch (format) {
  8421. case Laya.RenderTextureFormat.R8G8B8:
  8422. if (isWebGL2)
  8423. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.RGB8, width, height);
  8424. else
  8425. gl.texImage2D(glTextureType, 0, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, null);
  8426. break;
  8427. case Laya.RenderTextureFormat.R8G8B8A8:
  8428. if (isWebGL2)
  8429. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.RGBA8, width, height);
  8430. else
  8431. gl.texImage2D(glTextureType, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8432. break;
  8433. case Laya.RenderTextureFormat.Alpha8:
  8434. if (isWebGL2)
  8435. gl2.texStorage2D(glTextureType, 0, gl2.R8, width, height);
  8436. else
  8437. gl.texImage2D(glTextureType, 0, gl.ALPHA, width, height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, null);
  8438. break;
  8439. case Laya.RenderTextureFormat.R16G16B16A16:
  8440. if (isWebGL2)
  8441. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.RGBA16F, width, height);
  8442. else
  8443. gl.texImage2D(glTextureType, 0, gl.RGBA, width, height, 0, gl.RGBA, layaGPU._oesTextureHalfFloat.HALF_FLOAT_OES, null);
  8444. break;
  8445. }
  8446. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._glTexture, 0);
  8447. }
  8448. if (format == Laya.RenderTextureFormat.Depth || format == Laya.RenderTextureFormat.ShadowMap) {
  8449. Laya.WebGLContext.bindTexture(gl, glTextureType, this._glTexture);
  8450. switch (this._depthStencilFormat) {
  8451. case Laya.RenderTextureDepthFormat.DEPTH_16:
  8452. if (isWebGL2)
  8453. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.DEPTH_COMPONENT16, width, height);
  8454. else
  8455. gl.texImage2D(glTextureType, 0, gl.DEPTH_COMPONENT, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  8456. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, this._glTexture, 0);
  8457. break;
  8458. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_24_8:
  8459. if (isWebGL2)
  8460. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.DEPTH24_STENCIL8, width, height);
  8461. else
  8462. gl.texImage2D(glTextureType, 0, gl.DEPTH_STENCIL, width, height, 0, gl.DEPTH_STENCIL, layaGPU._webgl_depth_texture.UNSIGNED_INT_24_8_WEBGL, null);
  8463. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, this._glTexture, 0);
  8464. break;
  8465. default:
  8466. throw "RenderTexture: depth format RenderTexture must use depthFormat with DEPTH_16 and DEPTHSTENCIL_16_8.";
  8467. }
  8468. if (isWebGL2 && format == Laya.RenderTextureFormat.ShadowMap)
  8469. gl2.texParameteri(glTextureType, gl2.TEXTURE_COMPARE_MODE, gl2.COMPARE_REF_TO_TEXTURE);
  8470. }
  8471. else {
  8472. if (this._depthStencilFormat !== Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE) {
  8473. this._depthStencilBuffer = gl.createRenderbuffer();
  8474. gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthStencilBuffer);
  8475. switch (this._depthStencilFormat) {
  8476. case Laya.RenderTextureDepthFormat.DEPTH_16:
  8477. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8478. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  8479. break;
  8480. case Laya.RenderTextureDepthFormat.STENCIL_8:
  8481. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
  8482. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  8483. break;
  8484. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_24_8:
  8485. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8486. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  8487. break;
  8488. default:
  8489. throw "RenderTexture: unkonw depth format.";
  8490. }
  8491. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8492. }
  8493. }
  8494. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8495. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  8496. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  8497. this._setFilterMode(this._filterMode);
  8498. this._setAnisotropy(this._anisoLevel);
  8499. this._readyed = true;
  8500. this._activeResource();
  8501. this._setGPUMemory(width * height * 4);
  8502. }
  8503. _start() {
  8504. var gl = Laya.LayaGL.instance;
  8505. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  8506. RenderTexture._currentActive = this;
  8507. (this._isCameraTarget) && (RenderContext3D._instance.invertY = true);
  8508. this._readyed = false;
  8509. }
  8510. _end() {
  8511. var gl = Laya.LayaGL.instance;
  8512. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8513. RenderTexture._currentActive = null;
  8514. (this._isCameraTarget) && (RenderContext3D._instance.invertY = false);
  8515. this._readyed = true;
  8516. }
  8517. getData(x, y, width, height, out) {
  8518. if (Laya.Render.isConchApp && window.conchConfig.threadMode == 2) {
  8519. throw "native 2 thread mode use getDataAsync";
  8520. }
  8521. var gl = Laya.LayaGL.instance;
  8522. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  8523. var canRead = (gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE);
  8524. if (!canRead) {
  8525. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8526. return null;
  8527. }
  8528. gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, out);
  8529. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8530. return out;
  8531. }
  8532. _disposeResource() {
  8533. if (this._frameBuffer) {
  8534. var gl = Laya.LayaGL.instance;
  8535. gl.deleteTexture(this._glTexture);
  8536. gl.deleteFramebuffer(this._frameBuffer);
  8537. gl.deleteRenderbuffer(this._depthStencilBuffer);
  8538. this._glTexture = null;
  8539. this._frameBuffer = null;
  8540. this._depthStencilBuffer = null;
  8541. this._setGPUMemory(0);
  8542. }
  8543. }
  8544. getDataAsync(x, y, width, height, callBack) {
  8545. var gl = Laya.LayaGL.instance;
  8546. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  8547. gl.readPixelsAsync(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, function (data) {
  8548. callBack(new Uint8Array(data));
  8549. });
  8550. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8551. }
  8552. }
  8553. RenderTexture._pool = [];
  8554. class DefineDatas {
  8555. constructor() {
  8556. this._mask = [];
  8557. this._length = 0;
  8558. }
  8559. _intersectionDefineDatas(define) {
  8560. var unionMask = define._mask;
  8561. var mask = this._mask;
  8562. for (var i = this._length - 1; i >= 0; i--) {
  8563. var value = mask[i] & unionMask[i];
  8564. if (value == 0 && i == this._length - 1)
  8565. this._length--;
  8566. else
  8567. mask[i] = value;
  8568. }
  8569. }
  8570. add(define) {
  8571. var index = define._index;
  8572. var size = index + 1;
  8573. var mask = this._mask;
  8574. var maskStart = this._length;
  8575. if (maskStart < size) {
  8576. (mask.length < size) && (mask.length = size);
  8577. for (; maskStart < index; maskStart++)
  8578. mask[maskStart] = 0;
  8579. mask[index] = define._value;
  8580. this._length = size;
  8581. }
  8582. else {
  8583. if (size > this._length) {
  8584. mask[index] = define._value;
  8585. this._length = size;
  8586. }
  8587. else {
  8588. mask[index] |= define._value;
  8589. }
  8590. }
  8591. }
  8592. remove(define) {
  8593. var index = define._index;
  8594. var mask = this._mask;
  8595. var endIndex = this._length - 1;
  8596. if (index > endIndex)
  8597. return;
  8598. var newValue = mask[index] & ~define._value;
  8599. if (index == endIndex && newValue === 0)
  8600. this._length--;
  8601. else
  8602. mask[index] = newValue;
  8603. }
  8604. addDefineDatas(define) {
  8605. var addMask = define._mask;
  8606. var size = define._length;
  8607. var mask = this._mask;
  8608. var maskStart = mask.length;
  8609. if (maskStart < size) {
  8610. mask.length = size;
  8611. for (var i = 0; i < maskStart; i++)
  8612. mask[i] |= addMask[i];
  8613. for (; maskStart < size; maskStart++)
  8614. mask[maskStart] = addMask[maskStart];
  8615. this._length = size;
  8616. }
  8617. else {
  8618. for (var i = 0; i < size; i++)
  8619. mask[i] |= addMask[i];
  8620. this._length = Math.max(this._length, size);
  8621. }
  8622. }
  8623. removeDefineDatas(define) {
  8624. var removeMask = define._mask;
  8625. var mask = this._mask;
  8626. var endIndex = this._length - 1;
  8627. for (var i = define._length - 1; i >= 0; i--) {
  8628. if (i > endIndex)
  8629. continue;
  8630. var newValue = mask[i] & ~removeMask[i];
  8631. if (i == endIndex && newValue === 0) {
  8632. endIndex--;
  8633. this._length--;
  8634. }
  8635. else {
  8636. mask[i] = newValue;
  8637. }
  8638. }
  8639. }
  8640. has(define) {
  8641. var index = define._index;
  8642. if (index >= this._length)
  8643. return false;
  8644. return (this._mask[index] & define._value) !== 0;
  8645. }
  8646. clear() {
  8647. this._length = 0;
  8648. }
  8649. cloneTo(destObject) {
  8650. var destDefineData = destObject;
  8651. var destMask = destDefineData._mask;
  8652. var mask = this._mask;
  8653. var count = this._length;
  8654. destMask.length = count;
  8655. for (var i = 0; i < count; i++)
  8656. destMask[i] = mask[i];
  8657. destDefineData._length = count;
  8658. }
  8659. clone() {
  8660. var dest = new DefineDatas();
  8661. this.cloneTo(dest);
  8662. return dest;
  8663. }
  8664. }
  8665. class ShaderDefine {
  8666. constructor(index, value) {
  8667. this._index = index;
  8668. this._value = value;
  8669. }
  8670. }
  8671. class ShaderVariant {
  8672. constructor(shader, subShaderIndex, passIndex, defines) {
  8673. this._subShaderIndex = 0;
  8674. this._passIndex = 0;
  8675. this.setValue(shader, subShaderIndex, passIndex, defines);
  8676. }
  8677. get shader() {
  8678. return this._shader;
  8679. }
  8680. get subShaderIndex() {
  8681. return this._subShaderIndex;
  8682. }
  8683. get passIndex() {
  8684. return this._passIndex;
  8685. }
  8686. get defineNames() {
  8687. return this._defineNames;
  8688. }
  8689. setValue(shader, subShaderIndex, passIndex, defineNames) {
  8690. if (shader) {
  8691. var subShader = shader.getSubShaderAt(subShaderIndex);
  8692. if (subShader) {
  8693. var pass = subShader._passes[passIndex];
  8694. if (pass) {
  8695. var validDefine = pass._validDefine;
  8696. for (var i = 0, n = defineNames.length; i < n; i++) {
  8697. var defname = defineNames[i];
  8698. if (!validDefine.has(ILaya3D.Shader3D.getDefineByName(defname)))
  8699. throw `ShaderVariantInfo:Invalid defineName ${defname} in ${shader._name} subShaderIndex of ${subShaderIndex} passIndex of ${passIndex}.`;
  8700. }
  8701. }
  8702. else {
  8703. throw `ShaderVariantInfo:Shader don't have passIndex of ${passIndex}.`;
  8704. }
  8705. }
  8706. else {
  8707. throw `ShaderVariantInfo:Shader don't have subShaderIndex of ${subShaderIndex}.`;
  8708. }
  8709. }
  8710. else {
  8711. throw `ShaderVariantInfo:Shader can't be null.`;
  8712. }
  8713. this._shader = shader;
  8714. this._subShaderIndex = subShaderIndex;
  8715. this._passIndex = passIndex;
  8716. this._defineNames = defineNames;
  8717. }
  8718. equal(other) {
  8719. if (this._shader !== other._shader || this._subShaderIndex !== other._subShaderIndex || this._passIndex !== other._passIndex)
  8720. return false;
  8721. var defines = this._defineNames;
  8722. var otherDefines = other._defineNames;
  8723. if (defines.length !== otherDefines.length)
  8724. return false;
  8725. for (var i = 0, n = this._defineNames.length; i < n; i++) {
  8726. if (defines[i] !== otherDefines[i])
  8727. return false;
  8728. }
  8729. return true;
  8730. }
  8731. clone() {
  8732. var dest = new ShaderVariant(this._shader, this._subShaderIndex, this._passIndex, this._defineNames.slice());
  8733. return dest;
  8734. }
  8735. }
  8736. class ShaderVariantCollection {
  8737. constructor() {
  8738. this._allCompiled = false;
  8739. this._variants = [];
  8740. }
  8741. get allCompiled() {
  8742. return this._allCompiled;
  8743. }
  8744. get variantCount() {
  8745. return this._variants.length;
  8746. }
  8747. add(variant) {
  8748. for (var i = 0, n = this._variants.length; i < n; i++) {
  8749. if (this._variants[i].equal(variant))
  8750. return false;
  8751. }
  8752. this._variants.push(variant.clone());
  8753. this._allCompiled = false;
  8754. return true;
  8755. }
  8756. remove(variant) {
  8757. for (var i = 0, n = this._variants.length; i < n; i++) {
  8758. if (this._variants[i].equal(variant)) {
  8759. this._variants.splice(i, 1);
  8760. return true;
  8761. }
  8762. }
  8763. return false;
  8764. }
  8765. contatins(variant) {
  8766. for (var i = 0, n = this._variants.length; i < n; i++) {
  8767. if (this._variants[i].equal(variant))
  8768. return true;
  8769. }
  8770. return false;
  8771. }
  8772. getByIndex(index) {
  8773. return this._variants[index];
  8774. }
  8775. clear() {
  8776. this._variants.length = 0;
  8777. }
  8778. compile() {
  8779. if (!this._allCompiled) {
  8780. var variants = this._variants;
  8781. for (var i = 0, n = variants.length; i < n; i++) {
  8782. var variant = variants[i];
  8783. ILaya3D.Shader3D.compileShaderByDefineNames(variant._shader._name, variant._subShaderIndex, variant._passIndex, variant._defineNames);
  8784. }
  8785. this._allCompiled = true;
  8786. }
  8787. }
  8788. }
  8789. class Shader3D {
  8790. constructor(name, attributeMap, uniformMap, enableInstancing) {
  8791. this._attributeMap = null;
  8792. this._uniformMap = null;
  8793. this._enableInstancing = false;
  8794. this._subShaders = [];
  8795. this._name = name;
  8796. this._attributeMap = attributeMap;
  8797. this._uniformMap = uniformMap;
  8798. this._enableInstancing = enableInstancing;
  8799. }
  8800. static _getNamesByDefineData(defineData, out) {
  8801. var maskMap = Shader3D._maskMap;
  8802. var mask = defineData._mask;
  8803. out.length = 0;
  8804. for (var i = 0, n = defineData._length; i < n; i++) {
  8805. var subMaskMap = maskMap[i];
  8806. var subMask = mask[i];
  8807. for (var j = 0; j < 32; j++) {
  8808. var d = 1 << j;
  8809. if (subMask > 0 && d > subMask)
  8810. break;
  8811. if (subMask & d)
  8812. out.push(subMaskMap[d]);
  8813. }
  8814. }
  8815. }
  8816. static getDefineByName(name) {
  8817. var define = Shader3D._defineMap[name];
  8818. if (!define) {
  8819. var maskMap = Shader3D._maskMap;
  8820. var counter = Shader3D._defineCounter;
  8821. var index = Math.floor(counter / 32);
  8822. var value = 1 << counter % 32;
  8823. define = new ShaderDefine(index, value);
  8824. Shader3D._defineMap[name] = define;
  8825. if (index == maskMap.length) {
  8826. maskMap.length++;
  8827. maskMap[index] = {};
  8828. }
  8829. maskMap[index][value] = name;
  8830. Shader3D._defineCounter++;
  8831. }
  8832. return define;
  8833. }
  8834. static propertyNameToID(name) {
  8835. if (Shader3D._propertyNameMap[name] != null) {
  8836. return Shader3D._propertyNameMap[name];
  8837. }
  8838. else {
  8839. var id = Shader3D._propertyNameCounter++;
  8840. Shader3D._propertyNameMap[name] = id;
  8841. return id;
  8842. }
  8843. }
  8844. static addInclude(fileName, txt) {
  8845. txt = txt.replace(Laya.ShaderCompile._clearCR, "");
  8846. Laya.ShaderCompile.addInclude(fileName, txt);
  8847. }
  8848. static compileShaderByDefineNames(shaderName, subShaderIndex, passIndex, defineNames) {
  8849. var shader = Shader3D.find(shaderName);
  8850. if (shader) {
  8851. var subShader = shader.getSubShaderAt(subShaderIndex);
  8852. if (subShader) {
  8853. var pass = subShader._passes[passIndex];
  8854. if (pass) {
  8855. var compileDefineDatas = Shader3D._compileDefineDatas;
  8856. compileDefineDatas.clear();
  8857. for (var i = 0, n = defineNames.length; i < n; i++)
  8858. compileDefineDatas.add(Shader3D.getDefineByName(defineNames[i]));
  8859. pass.withCompile(compileDefineDatas);
  8860. }
  8861. else {
  8862. console.warn("Shader3D: unknown passIndex.");
  8863. }
  8864. }
  8865. else {
  8866. console.warn("Shader3D: unknown subShaderIndex.");
  8867. }
  8868. }
  8869. else {
  8870. console.warn("Shader3D: unknown shader name.");
  8871. }
  8872. }
  8873. static add(name, attributeMap = null, uniformMap = null, enableInstancing = false) {
  8874. return Shader3D._preCompileShader[name] = new Shader3D(name, attributeMap, uniformMap, enableInstancing);
  8875. }
  8876. static find(name) {
  8877. return Shader3D._preCompileShader[name];
  8878. }
  8879. get name() {
  8880. return this._name;
  8881. }
  8882. addSubShader(subShader) {
  8883. this._subShaders.push(subShader);
  8884. subShader._owner = this;
  8885. }
  8886. getSubShaderAt(index) {
  8887. return this._subShaders[index];
  8888. }
  8889. static compileShader(shaderName, subShaderIndex, passIndex, ...defineMask) {
  8890. var shader = Shader3D.find(shaderName);
  8891. if (shader) {
  8892. var subShader = shader.getSubShaderAt(subShaderIndex);
  8893. if (subShader) {
  8894. var pass = subShader._passes[passIndex];
  8895. if (pass) {
  8896. var compileDefineDatas = Shader3D._compileDefineDatas;
  8897. var mask = compileDefineDatas._mask;
  8898. mask.length = 0;
  8899. for (var i = 0, n = defineMask.length; i < n; i++)
  8900. mask.push(defineMask[i]);
  8901. compileDefineDatas._length = defineMask.length;
  8902. pass.withCompile(compileDefineDatas);
  8903. }
  8904. else {
  8905. console.warn("Shader3D: unknown passIndex.");
  8906. }
  8907. }
  8908. else {
  8909. console.warn("Shader3D: unknown subShaderIndex.");
  8910. }
  8911. }
  8912. else {
  8913. console.warn("Shader3D: unknown shader name.");
  8914. }
  8915. }
  8916. }
  8917. Shader3D._compileDefineDatas = new DefineDatas();
  8918. Shader3D.RENDER_STATE_CULL = 0;
  8919. Shader3D.RENDER_STATE_BLEND = 1;
  8920. Shader3D.RENDER_STATE_BLEND_SRC = 2;
  8921. Shader3D.RENDER_STATE_BLEND_DST = 3;
  8922. Shader3D.RENDER_STATE_BLEND_SRC_RGB = 4;
  8923. Shader3D.RENDER_STATE_BLEND_DST_RGB = 5;
  8924. Shader3D.RENDER_STATE_BLEND_SRC_ALPHA = 6;
  8925. Shader3D.RENDER_STATE_BLEND_DST_ALPHA = 7;
  8926. Shader3D.RENDER_STATE_BLEND_CONST_COLOR = 8;
  8927. Shader3D.RENDER_STATE_BLEND_EQUATION = 9;
  8928. Shader3D.RENDER_STATE_BLEND_EQUATION_RGB = 10;
  8929. Shader3D.RENDER_STATE_BLEND_EQUATION_ALPHA = 11;
  8930. Shader3D.RENDER_STATE_DEPTH_TEST = 12;
  8931. Shader3D.RENDER_STATE_DEPTH_WRITE = 13;
  8932. Shader3D.PERIOD_CUSTOM = 0;
  8933. Shader3D.PERIOD_MATERIAL = 1;
  8934. Shader3D.PERIOD_SPRITE = 2;
  8935. Shader3D.PERIOD_CAMERA = 3;
  8936. Shader3D.PERIOD_SCENE = 4;
  8937. Shader3D._propertyNameCounter = 0;
  8938. Shader3D._propertyNameMap = {};
  8939. Shader3D._defineCounter = 0;
  8940. Shader3D._defineMap = {};
  8941. Shader3D._preCompileShader = {};
  8942. Shader3D._maskMap = [];
  8943. Shader3D.debugMode = false;
  8944. Shader3D.debugShaderVariantCollection = new ShaderVariantCollection();
  8945. class ShaderData {
  8946. constructor(ownerResource = null) {
  8947. this._ownerResource = null;
  8948. this._data = null;
  8949. this._defineDatas = new DefineDatas();
  8950. this._runtimeCopyValues = [];
  8951. this._ownerResource = ownerResource;
  8952. this._initData();
  8953. }
  8954. _initData() {
  8955. this._data = new Object();
  8956. }
  8957. getData() {
  8958. return this._data;
  8959. }
  8960. addDefine(define) {
  8961. this._defineDatas.add(define);
  8962. }
  8963. removeDefine(define) {
  8964. this._defineDatas.remove(define);
  8965. }
  8966. hasDefine(define) {
  8967. return this._defineDatas.has(define);
  8968. }
  8969. clearDefine() {
  8970. this._defineDatas.clear();
  8971. }
  8972. getBool(index) {
  8973. return this._data[index];
  8974. }
  8975. setBool(index, value) {
  8976. this._data[index] = value;
  8977. }
  8978. getInt(index) {
  8979. return this._data[index];
  8980. }
  8981. setInt(index, value) {
  8982. this._data[index] = value;
  8983. }
  8984. getNumber(index) {
  8985. return this._data[index];
  8986. }
  8987. setNumber(index, value) {
  8988. this._data[index] = value;
  8989. }
  8990. getVector2(index) {
  8991. return this._data[index];
  8992. }
  8993. setVector2(index, value) {
  8994. this._data[index] = value;
  8995. }
  8996. getVector3(index) {
  8997. return this._data[index];
  8998. }
  8999. setVector3(index, value) {
  9000. this._data[index] = value;
  9001. }
  9002. getVector(index) {
  9003. return this._data[index];
  9004. }
  9005. setVector(index, value) {
  9006. this._data[index] = value;
  9007. }
  9008. getQuaternion(index) {
  9009. return this._data[index];
  9010. }
  9011. setQuaternion(index, value) {
  9012. this._data[index] = value;
  9013. }
  9014. getMatrix4x4(index) {
  9015. return this._data[index];
  9016. }
  9017. setMatrix4x4(index, value) {
  9018. this._data[index] = value;
  9019. }
  9020. getBuffer(shaderIndex) {
  9021. return this._data[shaderIndex];
  9022. }
  9023. setBuffer(index, value) {
  9024. this._data[index] = value;
  9025. }
  9026. setTexture(index, value) {
  9027. var lastValue = this._data[index];
  9028. this._data[index] = value;
  9029. if (this._ownerResource && this._ownerResource.referenceCount > 0) {
  9030. (lastValue) && (lastValue._removeReference());
  9031. (value) && (value._addReference());
  9032. }
  9033. }
  9034. getTexture(index) {
  9035. return this._data[index];
  9036. }
  9037. setAttribute(index, value) {
  9038. this._data[index] = value;
  9039. }
  9040. getAttribute(index) {
  9041. return this._data[index];
  9042. }
  9043. getLength() {
  9044. return this._data.length;
  9045. }
  9046. setLength(value) {
  9047. this._data.length = value;
  9048. }
  9049. cloneTo(destObject) {
  9050. var dest = destObject;
  9051. var destData = dest._data;
  9052. for (var k in this._data) {
  9053. var value = this._data[k];
  9054. if (value != null) {
  9055. if (typeof (value) == 'number') {
  9056. destData[k] = value;
  9057. }
  9058. else if (typeof (value) == 'number') {
  9059. destData[k] = value;
  9060. }
  9061. else if (typeof (value) == "boolean") {
  9062. destData[k] = value;
  9063. }
  9064. else if (value instanceof Vector2) {
  9065. var v2 = (destData[k]) || (destData[k] = new Vector2());
  9066. value.cloneTo(v2);
  9067. destData[k] = v2;
  9068. }
  9069. else if (value instanceof Vector3) {
  9070. var v3 = (destData[k]) || (destData[k] = new Vector3());
  9071. value.cloneTo(v3);
  9072. destData[k] = v3;
  9073. }
  9074. else if (value instanceof Vector4) {
  9075. var v4 = (destData[k]) || (destData[k] = new Vector4());
  9076. value.cloneTo(v4);
  9077. destData[k] = v4;
  9078. }
  9079. else if (value instanceof Matrix4x4) {
  9080. var mat = (destData[k]) || (destData[k] = new Matrix4x4());
  9081. value.cloneTo(mat);
  9082. destData[k] = mat;
  9083. }
  9084. else if (value instanceof Laya.BaseTexture) {
  9085. destData[k] = value;
  9086. }
  9087. }
  9088. }
  9089. this._defineDatas.cloneTo(dest._defineDatas);
  9090. }
  9091. clone() {
  9092. var dest = new ShaderData();
  9093. this.cloneTo(dest);
  9094. return dest;
  9095. }
  9096. cloneToForNative(destObject) {
  9097. var dest = destObject;
  9098. var diffSize = this._int32Data.length - dest._int32Data.length;
  9099. if (diffSize > 0) {
  9100. dest.needRenewArrayBufferForNative(this._int32Data.length);
  9101. }
  9102. dest._int32Data.set(this._int32Data, 0);
  9103. var destData = dest._nativeArray;
  9104. var dataCount = this._nativeArray.length;
  9105. destData.length = dataCount;
  9106. for (var i = 0; i < dataCount; i++) {
  9107. var value = this._nativeArray[i];
  9108. if (value) {
  9109. if (typeof (value) == 'number') {
  9110. destData[i] = value;
  9111. dest.setNumber(i, value);
  9112. }
  9113. else if (typeof (value) == 'number') {
  9114. destData[i] = value;
  9115. dest.setInt(i, value);
  9116. }
  9117. else if (typeof (value) == "boolean") {
  9118. destData[i] = value;
  9119. dest.setBool(i, value);
  9120. }
  9121. else if (value instanceof Vector2) {
  9122. var v2 = (destData[i]) || (destData[i] = new Vector2());
  9123. value.cloneTo(v2);
  9124. destData[i] = v2;
  9125. dest.setVector2(i, v2);
  9126. }
  9127. else if (value instanceof Vector3) {
  9128. var v3 = (destData[i]) || (destData[i] = new Vector3());
  9129. value.cloneTo(v3);
  9130. destData[i] = v3;
  9131. dest.setVector3(i, v3);
  9132. }
  9133. else if (value instanceof Vector4) {
  9134. var v4 = (destData[i]) || (destData[i] = new Vector4());
  9135. value.cloneTo(v4);
  9136. destData[i] = v4;
  9137. dest.setVector(i, v4);
  9138. }
  9139. else if (value instanceof Matrix4x4) {
  9140. var mat = (destData[i]) || (destData[i] = new Matrix4x4());
  9141. value.cloneTo(mat);
  9142. destData[i] = mat;
  9143. dest.setMatrix4x4(i, mat);
  9144. }
  9145. else if (value instanceof Laya.BaseTexture) {
  9146. destData[i] = value;
  9147. dest.setTexture(i, value);
  9148. }
  9149. }
  9150. }
  9151. this._defineDatas.cloneTo(dest._defineDatas);
  9152. }
  9153. _initDataForNative() {
  9154. var length = 8;
  9155. this._frameCount = -1;
  9156. this._runtimeCopyValues.length = 0;
  9157. this._nativeArray = [];
  9158. this._data = new ArrayBuffer(length * 4);
  9159. this._int32Data = new Int32Array(this._data);
  9160. this._float32Data = new Float32Array(this._data);
  9161. Laya.LayaGL.instance.createArrayBufferRef(this._data, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true);
  9162. }
  9163. needRenewArrayBufferForNative(index) {
  9164. if (index >= this._int32Data.length) {
  9165. var nByteLen = (index + 1) * 4;
  9166. var pre = this._int32Data;
  9167. var preConchRef = this._data["conchRef"];
  9168. var prePtrID = this._data["_ptrID"];
  9169. this._data = new ArrayBuffer(nByteLen);
  9170. this._int32Data = new Int32Array(this._data);
  9171. this._float32Data = new Float32Array(this._data);
  9172. this._data["conchRef"] = preConchRef;
  9173. this._data["_ptrID"] = prePtrID;
  9174. pre && this._int32Data.set(pre, 0);
  9175. var layagl = Laya.LayaGL.instance;
  9176. if (layagl.updateArrayBufferRef) {
  9177. layagl.updateArrayBufferRef(this._data['_ptrID'], preConchRef.isSyncToRender(), this._data);
  9178. }
  9179. else {
  9180. window.conch.updateArrayBufferRef(this._data['_ptrID'], preConchRef.isSyncToRender(), this._data);
  9181. }
  9182. }
  9183. }
  9184. getDataForNative() {
  9185. return this._nativeArray;
  9186. }
  9187. getIntForNative(index) {
  9188. return this._int32Data[index];
  9189. }
  9190. setIntForNative(index, value) {
  9191. this.needRenewArrayBufferForNative(index);
  9192. this._int32Data[index] = value;
  9193. this._nativeArray[index] = value;
  9194. }
  9195. getBoolForNative(index) {
  9196. return this._int32Data[index] == 1;
  9197. }
  9198. setBoolForNative(index, value) {
  9199. this.needRenewArrayBufferForNative(index);
  9200. this._int32Data[index] = value ? 1 : 0;
  9201. this._nativeArray[index] = value;
  9202. }
  9203. getNumberForNative(index) {
  9204. return this._float32Data[index];
  9205. }
  9206. setNumberForNative(index, value) {
  9207. this.needRenewArrayBufferForNative(index);
  9208. this._float32Data[index] = value;
  9209. this._nativeArray[index] = value;
  9210. }
  9211. getMatrix4x4ForNative(index) {
  9212. return this._nativeArray[index];
  9213. }
  9214. setMatrix4x4ForNative(index, value) {
  9215. this.needRenewArrayBufferForNative(index);
  9216. this._nativeArray[index] = value;
  9217. var nPtrID = this.setReferenceForNative(value.elements);
  9218. this._int32Data[index] = nPtrID;
  9219. }
  9220. getVectorForNative(index) {
  9221. return this._nativeArray[index];
  9222. }
  9223. setVectorForNative(index, value) {
  9224. this.needRenewArrayBufferForNative(index);
  9225. this._nativeArray[index] = value;
  9226. if (!value.elements) {
  9227. value.forNativeElement();
  9228. }
  9229. var nPtrID = this.setReferenceForNative(value.elements);
  9230. this._int32Data[index] = nPtrID;
  9231. }
  9232. getVector2ForNative(index) {
  9233. return this._nativeArray[index];
  9234. }
  9235. setVector2ForNative(index, value) {
  9236. this.needRenewArrayBufferForNative(index);
  9237. this._nativeArray[index] = value;
  9238. if (!value.elements) {
  9239. value.forNativeElement();
  9240. }
  9241. var nPtrID = this.setReferenceForNative(value.elements);
  9242. this._int32Data[index] = nPtrID;
  9243. }
  9244. getVector3ForNative(index) {
  9245. return this._nativeArray[index];
  9246. }
  9247. setVector3ForNative(index, value) {
  9248. this.needRenewArrayBufferForNative(index);
  9249. this._nativeArray[index] = value;
  9250. if (!value.elements) {
  9251. value.forNativeElement();
  9252. }
  9253. var nPtrID = this.setReferenceForNative(value.elements);
  9254. this._int32Data[index] = nPtrID;
  9255. }
  9256. getQuaternionForNative(index) {
  9257. return this._nativeArray[index];
  9258. }
  9259. setQuaternionForNative(index, value) {
  9260. this.needRenewArrayBufferForNative(index);
  9261. this._nativeArray[index] = value;
  9262. if (!value.elements) {
  9263. value.forNativeElement();
  9264. }
  9265. var nPtrID = this.setReferenceForNative(value.elements);
  9266. this._int32Data[index] = nPtrID;
  9267. }
  9268. getBufferForNative(shaderIndex) {
  9269. return this._nativeArray[shaderIndex];
  9270. }
  9271. setBufferForNative(index, value) {
  9272. this.needRenewArrayBufferForNative(index);
  9273. this._nativeArray[index] = value;
  9274. var nPtrID = this.setReferenceForNative(value);
  9275. this._int32Data[index] = nPtrID;
  9276. }
  9277. getAttributeForNative(index) {
  9278. return this._nativeArray[index];
  9279. }
  9280. setAttributeForNative(index, value) {
  9281. this._nativeArray[index] = value;
  9282. if (!value["_ptrID"]) {
  9283. Laya.LayaGL.instance.createArrayBufferRef(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true);
  9284. }
  9285. Laya.LayaGL.instance.syncBufferToRenderThread(value);
  9286. this._int32Data[index] = value["_ptrID"];
  9287. }
  9288. getTextureForNative(index) {
  9289. return this._nativeArray[index];
  9290. }
  9291. setTextureForNative(index, value) {
  9292. if (!value)
  9293. return;
  9294. this.needRenewArrayBufferForNative(index);
  9295. var lastValue = this._nativeArray[index];
  9296. this._nativeArray[index] = value;
  9297. var glTexture = value._getSource() || value.defaulteTexture._getSource();
  9298. this._int32Data[index] = glTexture.id;
  9299. if (this._ownerResource && this._ownerResource.referenceCount > 0) {
  9300. (lastValue) && (lastValue._removeReference());
  9301. (value) && (value._addReference());
  9302. }
  9303. }
  9304. setReferenceForNative(value) {
  9305. this.clearRuntimeCopyArray();
  9306. var nRefID = 0;
  9307. var nPtrID = 0;
  9308. if (ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_) {
  9309. Laya.LayaGL.instance.createArrayBufferRefs(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true, Laya.LayaGL.ARRAY_BUFFER_REF_REFERENCE);
  9310. nRefID = 0;
  9311. nPtrID = value.getPtrID(nRefID);
  9312. }
  9313. else {
  9314. Laya.LayaGL.instance.createArrayBufferRefs(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true, Laya.LayaGL.ARRAY_BUFFER_REF_COPY);
  9315. nRefID = value.getRefNum() - 1;
  9316. nPtrID = value.getPtrID(nRefID);
  9317. this._runtimeCopyValues.push({ "obj": value, "refID": nRefID, "ptrID": nPtrID });
  9318. }
  9319. Laya.LayaGL.instance.syncBufferToRenderThread(value, nRefID);
  9320. return nPtrID;
  9321. }
  9322. static setRuntimeValueMode(bReference) {
  9323. ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_ = bReference;
  9324. }
  9325. clearRuntimeCopyArray() {
  9326. var currentFrame = Laya.Stat.loopCount;
  9327. if (this._frameCount != currentFrame) {
  9328. this._frameCount = currentFrame;
  9329. for (var i = 0, n = this._runtimeCopyValues.length; i < n; i++) {
  9330. var obj = this._runtimeCopyValues[i];
  9331. obj.obj.clearRefNum();
  9332. }
  9333. this._runtimeCopyValues.length = 0;
  9334. }
  9335. }
  9336. }
  9337. ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_ = true;
  9338. class PostProcess {
  9339. constructor() {
  9340. this._compositeShader = Shader3D.find("PostProcessComposite");
  9341. this._compositeShaderData = new ShaderData();
  9342. this._effects = [];
  9343. this._context = null;
  9344. this._context = new PostProcessRenderContext();
  9345. this._context.compositeShaderData = this._compositeShaderData;
  9346. }
  9347. static __init__() {
  9348. PostProcess.SHADERDEFINE_BLOOM_LOW = Shader3D.getDefineByName("BLOOM_LOW");
  9349. PostProcess.SHADERDEFINE_BLOOM = Shader3D.getDefineByName("BLOOM");
  9350. PostProcess.SHADERDEFINE_FINALPASS = Shader3D.getDefineByName("FINALPASS");
  9351. }
  9352. _init(camera, command) {
  9353. this._context.camera = camera;
  9354. this._context.command = command;
  9355. }
  9356. _render() {
  9357. var noteValue = ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_;
  9358. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(false);
  9359. var camera = this._context.camera;
  9360. var viewport = camera.viewport;
  9361. var screenTexture = RenderTexture.createFromPool(RenderContext3D.clientWidth, RenderContext3D.clientHeight, camera._getRenderTextureFormat(), Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE);
  9362. var cameraTarget = camera._internalRenderTexture;
  9363. this._context.command.clear();
  9364. this._context.source = screenTexture;
  9365. this._context.destination = cameraTarget;
  9366. this._context.compositeShaderData.clearDefine();
  9367. this._context.command.blitScreenTriangle(cameraTarget, screenTexture);
  9368. this._context.compositeShaderData.setTexture(PostProcess.SHADERVALUE_AUTOEXPOSURETEX, Laya.Texture2D.whiteTexture);
  9369. for (var i = 0, n = this._effects.length; i < n; i++)
  9370. this._effects[i].render(this._context);
  9371. this._compositeShaderData.addDefine(PostProcess.SHADERDEFINE_FINALPASS);
  9372. var offScreenTex = camera._offScreenRenderTexture;
  9373. var dest = offScreenTex ? offScreenTex : null;
  9374. this._context.destination = dest;
  9375. var canvasWidth = camera._getCanvasWidth(), canvasHeight = camera._getCanvasHeight();
  9376. camera._screenOffsetScale.setValue(viewport.x / canvasWidth, viewport.y / canvasHeight, viewport.width / canvasWidth, viewport.height / canvasHeight);
  9377. this._context.command.blitScreenTriangle(this._context.source, dest, camera._screenOffsetScale, this._compositeShader, this._compositeShaderData);
  9378. RenderTexture.recoverToPool(screenTexture);
  9379. var tempRenderTextures = this._context.deferredReleaseTextures;
  9380. for (i = 0, n = tempRenderTextures.length; i < n; i++)
  9381. RenderTexture.recoverToPool(tempRenderTextures[i]);
  9382. tempRenderTextures.length = 0;
  9383. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(noteValue);
  9384. }
  9385. addEffect(effect) {
  9386. this._effects.push(effect);
  9387. }
  9388. removeEffect(effect) {
  9389. var index = this._effects.indexOf(effect);
  9390. if (index !== -1)
  9391. this._effects.splice(index, 1);
  9392. }
  9393. }
  9394. PostProcess.SHADERVALUE_MAINTEX = Shader3D.propertyNameToID("u_MainTex");
  9395. PostProcess.SHADERVALUE_BLOOMTEX = Shader3D.propertyNameToID("u_BloomTex");
  9396. PostProcess.SHADERVALUE_AUTOEXPOSURETEX = Shader3D.propertyNameToID("u_AutoExposureTex");
  9397. PostProcess.SHADERVALUE_BLOOM_DIRTTEX = Shader3D.propertyNameToID("u_Bloom_DirtTex");
  9398. PostProcess.SHADERVALUE_BLOOMTEX_TEXELSIZE = Shader3D.propertyNameToID("u_BloomTex_TexelSize");
  9399. PostProcess.SHADERVALUE_BLOOM_DIRTTILEOFFSET = Shader3D.propertyNameToID("u_Bloom_DirtTileOffset");
  9400. PostProcess.SHADERVALUE_BLOOM_SETTINGS = Shader3D.propertyNameToID("u_Bloom_Settings");
  9401. PostProcess.SHADERVALUE_BLOOM_COLOR = Shader3D.propertyNameToID("u_Bloom_Color");
  9402. class AnimationTransform3D extends Laya.EventDispatcher {
  9403. constructor(owner, localPosition = null, localRotation = null, localScale = null, worldMatrix = null) {
  9404. super();
  9405. this._owner = owner;
  9406. this._children = [];
  9407. this._localMatrix = new Float32Array(16);
  9408. if (Laya.Render.supportWebGLPlusAnimation) {
  9409. this._localPosition = new ConchVector3(0, 0, 0, localPosition);
  9410. this._localRotation = new ConchQuaternion(0, 0, 0, 1, localRotation);
  9411. this._localScale = new ConchVector3(0, 0, 0, localScale);
  9412. this._worldMatrix = worldMatrix;
  9413. }
  9414. else {
  9415. this._localPosition = new Vector3();
  9416. this._localRotation = new Quaternion();
  9417. this._localScale = new Vector3();
  9418. this._worldMatrix = new Float32Array(16);
  9419. }
  9420. this._localQuaternionUpdate = false;
  9421. this._locaEulerlUpdate = false;
  9422. this._localUpdate = false;
  9423. this._worldUpdate = true;
  9424. }
  9425. _getlocalMatrix() {
  9426. if (this._localUpdate) {
  9427. Utils3D._createAffineTransformationArray(this._localPosition, this._localRotation, this._localScale, this._localMatrix);
  9428. this._localUpdate = false;
  9429. }
  9430. return this._localMatrix;
  9431. }
  9432. _onWorldTransform() {
  9433. if (!this._worldUpdate) {
  9434. this._worldUpdate = true;
  9435. this.event(Laya.Event.TRANSFORM_CHANGED);
  9436. for (var i = 0, n = this._children.length; i < n; i++)
  9437. this._children[i]._onWorldTransform();
  9438. }
  9439. }
  9440. get localPosition() {
  9441. return this._localPosition;
  9442. }
  9443. set localPosition(value) {
  9444. this._localPosition = value;
  9445. this._localUpdate = true;
  9446. this._onWorldTransform();
  9447. }
  9448. get localRotation() {
  9449. if (this._localQuaternionUpdate) {
  9450. var euler = this._localRotationEuler;
  9451. Quaternion.createFromYawPitchRoll(euler.y / AnimationTransform3D._angleToRandin, euler.x / AnimationTransform3D._angleToRandin, euler.z / AnimationTransform3D._angleToRandin, this._localRotation);
  9452. this._localQuaternionUpdate = false;
  9453. }
  9454. return this._localRotation;
  9455. }
  9456. set localRotation(value) {
  9457. this._localRotation = value;
  9458. this._locaEulerlUpdate = true;
  9459. this._localQuaternionUpdate = false;
  9460. this._localUpdate = true;
  9461. this._onWorldTransform();
  9462. }
  9463. get localScale() {
  9464. return this._localScale;
  9465. }
  9466. set localScale(value) {
  9467. this._localScale = value;
  9468. this._localUpdate = true;
  9469. this._onWorldTransform();
  9470. }
  9471. get localRotationEuler() {
  9472. if (this._locaEulerlUpdate) {
  9473. this._localRotation.getYawPitchRoll(AnimationTransform3D._tempVector3);
  9474. var euler = AnimationTransform3D._tempVector3;
  9475. var localRotationEuler = this._localRotationEuler;
  9476. localRotationEuler.x = euler.y * AnimationTransform3D._angleToRandin;
  9477. localRotationEuler.y = euler.x * AnimationTransform3D._angleToRandin;
  9478. localRotationEuler.z = euler.z * AnimationTransform3D._angleToRandin;
  9479. this._locaEulerlUpdate = false;
  9480. }
  9481. return this._localRotationEuler;
  9482. }
  9483. set localRotationEuler(value) {
  9484. this._localRotationEuler = value;
  9485. this._locaEulerlUpdate = false;
  9486. this._localQuaternionUpdate = true;
  9487. this._localUpdate = true;
  9488. this._onWorldTransform();
  9489. }
  9490. getWorldMatrix() {
  9491. if (!Laya.Render.supportWebGLPlusAnimation && this._worldUpdate) {
  9492. if (this._parent != null) {
  9493. Utils3D.matrix4x4MultiplyFFF(this._parent.getWorldMatrix(), this._getlocalMatrix(), this._worldMatrix);
  9494. }
  9495. else {
  9496. var e = this._worldMatrix;
  9497. 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;
  9498. e[0] = e[5] = e[10] = e[15] = 1;
  9499. }
  9500. this._worldUpdate = false;
  9501. }
  9502. if (Laya.Render.supportWebGLPlusAnimation && this._worldUpdate) {
  9503. this._worldUpdate = false;
  9504. }
  9505. return this._worldMatrix;
  9506. }
  9507. setParent(value) {
  9508. if (this._parent !== value) {
  9509. if (this._parent) {
  9510. var parentChilds = this._parent._children;
  9511. var index = parentChilds.indexOf(this);
  9512. parentChilds.splice(index, 1);
  9513. }
  9514. if (value) {
  9515. value._children.push(this);
  9516. (value) && (this._onWorldTransform());
  9517. }
  9518. this._parent = value;
  9519. }
  9520. }
  9521. }
  9522. AnimationTransform3D._tempVector3 = new Vector3();
  9523. AnimationTransform3D._angleToRandin = 180 / Math.PI;
  9524. class AnimationNode {
  9525. constructor(localPosition = null, localRotation = null, localScale = null, worldMatrix = null) {
  9526. this._children = [];
  9527. this.transform = new AnimationTransform3D(this, localPosition, localRotation, localScale, worldMatrix);
  9528. }
  9529. addChild(child) {
  9530. child._parent = this;
  9531. child.transform.setParent(this.transform);
  9532. this._children.push(child);
  9533. }
  9534. removeChild(child) {
  9535. var index = this._children.indexOf(child);
  9536. (index !== -1) && (this._children.splice(index, 1));
  9537. }
  9538. getChildByName(name) {
  9539. for (var i = 0, n = this._children.length; i < n; i++) {
  9540. var child = this._children[i];
  9541. if (child.name === name)
  9542. return child;
  9543. }
  9544. return null;
  9545. }
  9546. getChildByIndex(index) {
  9547. return this._children[index];
  9548. }
  9549. getChildCount() {
  9550. return this._children.length;
  9551. }
  9552. cloneTo(destObject) {
  9553. var destNode = destObject;
  9554. destNode.name = this.name;
  9555. for (var i = 0, n = this._children.length; i < n; i++) {
  9556. var child = this._children[i];
  9557. var destChild = child.clone();
  9558. destNode.addChild(destChild);
  9559. var transform = child.transform;
  9560. var destTransform = destChild.transform;
  9561. var destLocalPosition = destTransform.localPosition;
  9562. var destLocalRotation = destTransform.localRotation;
  9563. var destLocalScale = destTransform.localScale;
  9564. transform.localPosition.cloneTo(destLocalPosition);
  9565. transform.localRotation.cloneTo(destLocalRotation);
  9566. transform.localScale.cloneTo(destLocalScale);
  9567. destTransform.localPosition = destLocalPosition;
  9568. destTransform.localRotation = destLocalRotation;
  9569. destTransform.localScale = destLocalScale;
  9570. }
  9571. }
  9572. clone() {
  9573. var dest = new AnimationNode();
  9574. this.cloneTo(dest);
  9575. return dest;
  9576. }
  9577. _cloneNative(localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar) {
  9578. var curID = avatar._nativeCurCloneCount;
  9579. animationNodeParentIndices[curID] = parentIndex;
  9580. var localPosition = new Float32Array(localPositions.buffer, curID * 3 * 4, 3);
  9581. var localRotation = new Float32Array(localRotations.buffer, curID * 4 * 4, 4);
  9582. var localScale = new Float32Array(localScales.buffer, curID * 3 * 4, 3);
  9583. var worldMatrix = new Float32Array(animationNodeWorldMatrixs.buffer, curID * 16 * 4, 16);
  9584. var dest = new AnimationNode(localPosition, localRotation, localScale, worldMatrix);
  9585. dest._worldMatrixIndex = curID;
  9586. this._cloneToNative(dest, localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, curID, avatar);
  9587. return dest;
  9588. }
  9589. _cloneToNative(destObject, localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar) {
  9590. var destNode = destObject;
  9591. destNode.name = this.name;
  9592. for (var i = 0, n = this._children.length; i < n; i++) {
  9593. var child = this._children[i];
  9594. avatar._nativeCurCloneCount++;
  9595. var destChild = child._cloneNative(localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar);
  9596. destNode.addChild(destChild);
  9597. var transform = child.transform;
  9598. var destTransform = destChild.transform;
  9599. var destLocalPosition = destTransform.localPosition;
  9600. var destLocalRotation = destTransform.localRotation;
  9601. var destLocalScale = destTransform.localScale;
  9602. transform.localPosition.cloneTo(destLocalPosition);
  9603. transform.localRotation.cloneTo(destLocalRotation);
  9604. transform.localScale.cloneTo(destLocalScale);
  9605. destTransform.localPosition = destLocalPosition;
  9606. destTransform.localRotation = destLocalRotation;
  9607. destTransform.localScale = destLocalScale;
  9608. }
  9609. }
  9610. }
  9611. class Avatar extends Laya.Resource {
  9612. constructor() {
  9613. super();
  9614. this._nativeNodeCount = 0;
  9615. this._nativeCurCloneCount = 0;
  9616. }
  9617. static _parse(data, propertyParams = null, constructParams = null) {
  9618. var avatar = new Avatar();
  9619. avatar._rootNode = new AnimationNode(new Float32Array(3), new Float32Array(4), new Float32Array(3), new Float32Array(16));
  9620. if (Laya.Render.supportWebGLPlusAnimation)
  9621. avatar._nativeNodeCount++;
  9622. if (data.version) {
  9623. var rootNode = data.rootNode;
  9624. (rootNode) && (avatar._parseNode(rootNode, avatar._rootNode));
  9625. }
  9626. return avatar;
  9627. }
  9628. static load(url, complete) {
  9629. Laya.ILaya.loader.create(url, complete, null, Avatar.AVATAR);
  9630. }
  9631. _initCloneToAnimator(destNode, destAnimator) {
  9632. destAnimator._avatarNodeMap[destNode.name] = destNode;
  9633. for (var i = 0, n = destNode.getChildCount(); i < n; i++)
  9634. this._initCloneToAnimator(destNode.getChildByIndex(i), destAnimator);
  9635. }
  9636. _parseNode(nodaData, node) {
  9637. var name = nodaData.props.name;
  9638. node.name = name;
  9639. var props = nodaData.props;
  9640. var transform = node.transform;
  9641. var pos = transform.localPosition;
  9642. var rot = transform.localRotation;
  9643. var sca = transform.localScale;
  9644. pos.fromArray(props.translate);
  9645. rot.fromArray(props.rotation);
  9646. sca.fromArray(props.scale);
  9647. transform.localPosition = pos;
  9648. transform.localRotation = rot;
  9649. transform.localScale = sca;
  9650. var childrenData = nodaData.child;
  9651. for (var j = 0, n = childrenData.length; j < n; j++) {
  9652. var childData = childrenData[j];
  9653. var childBone = new AnimationNode(new Float32Array(3), new Float32Array(4), new Float32Array(3), new Float32Array(16));
  9654. node.addChild(childBone);
  9655. if (Laya.Render.supportWebGLPlusAnimation)
  9656. this._nativeNodeCount++;
  9657. this._parseNode(childData, childBone);
  9658. }
  9659. }
  9660. _cloneDatasToAnimator(destAnimator) {
  9661. var destRoot;
  9662. destRoot = this._rootNode.clone();
  9663. var transform = this._rootNode.transform;
  9664. var destTransform = destRoot.transform;
  9665. var destPosition = destTransform.localPosition;
  9666. var destRotation = destTransform.localRotation;
  9667. var destScale = destTransform.localScale;
  9668. transform.localPosition.cloneTo(destPosition);
  9669. transform.localRotation.cloneTo(destRotation);
  9670. transform.localScale.cloneTo(destScale);
  9671. destTransform.localPosition = destPosition;
  9672. destTransform.localRotation = destRotation;
  9673. destTransform.localScale = destScale;
  9674. destAnimator._avatarNodeMap = {};
  9675. this._initCloneToAnimator(destRoot, destAnimator);
  9676. }
  9677. cloneTo(destObject) {
  9678. var destAvatar = destObject;
  9679. var destRoot = this._rootNode.clone();
  9680. destAvatar._rootNode = destRoot;
  9681. }
  9682. clone() {
  9683. var dest = new Avatar();
  9684. this.cloneTo(dest);
  9685. return dest;
  9686. }
  9687. _cloneDatasToAnimatorNative(destAnimator) {
  9688. var animationNodeLocalPositions = new Float32Array(this._nativeNodeCount * 3);
  9689. var animationNodeLocalRotations = new Float32Array(this._nativeNodeCount * 4);
  9690. var animationNodeLocalScales = new Float32Array(this._nativeNodeCount * 3);
  9691. var animationNodeWorldMatrixs = new Float32Array(this._nativeNodeCount * 16);
  9692. var animationNodeParentIndices = new Int16Array(this._nativeNodeCount);
  9693. destAnimator._animationNodeLocalPositions = animationNodeLocalPositions;
  9694. destAnimator._animationNodeLocalRotations = animationNodeLocalRotations;
  9695. destAnimator._animationNodeLocalScales = animationNodeLocalScales;
  9696. destAnimator._animationNodeWorldMatrixs = animationNodeWorldMatrixs;
  9697. destAnimator._animationNodeParentIndices = animationNodeParentIndices;
  9698. this._nativeCurCloneCount = 0;
  9699. var destRoot = this._rootNode._cloneNative(animationNodeLocalPositions, animationNodeLocalRotations, animationNodeLocalScales, animationNodeWorldMatrixs, animationNodeParentIndices, -1, this);
  9700. var transform = this._rootNode.transform;
  9701. var destTransform = destRoot.transform;
  9702. var destPosition = destTransform.localPosition;
  9703. var destRotation = destTransform.localRotation;
  9704. var destScale = destTransform.localScale;
  9705. transform.localPosition.cloneTo(destPosition);
  9706. transform.localRotation.cloneTo(destRotation);
  9707. transform.localScale.cloneTo(destScale);
  9708. destTransform.localPosition = destPosition;
  9709. destTransform.localRotation = destRotation;
  9710. destTransform.localScale = destScale;
  9711. destAnimator._avatarNodeMap = {};
  9712. this._initCloneToAnimator(destRoot, destAnimator);
  9713. }
  9714. }
  9715. Avatar.AVATAR = "AVATAR";
  9716. class Material extends Laya.Resource {
  9717. constructor() {
  9718. super();
  9719. this._shaderValues = null;
  9720. this._shaderValues = new ShaderData(this);
  9721. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  9722. this._alphaTest = false;
  9723. }
  9724. static load(url, complete) {
  9725. Laya.Laya.loader.create(url, complete, null, Material.MATERIAL);
  9726. }
  9727. static __initDefine__() {
  9728. Material.SHADERDEFINE_ALPHATEST = Shader3D.getDefineByName("ALPHATEST");
  9729. }
  9730. static _parse(data, propertyParams = null, constructParams = null) {
  9731. var jsonData = data;
  9732. var props = jsonData.props;
  9733. var material;
  9734. var classType = props.type;
  9735. var clas = Laya.ClassUtils.getRegClass(classType);
  9736. if (clas)
  9737. material = new clas();
  9738. else
  9739. throw ('_getSprite3DHierarchyInnerUrls 错误: ' + data.type + ' 不是类');
  9740. switch (jsonData.version) {
  9741. case "LAYAMATERIAL:01":
  9742. case "LAYAMATERIAL:02":
  9743. var i, n;
  9744. for (var key in props) {
  9745. switch (key) {
  9746. case "type":
  9747. break;
  9748. case "vectors":
  9749. var vectors = props[key];
  9750. for (i = 0, n = vectors.length; i < n; i++) {
  9751. var vector = vectors[i];
  9752. var vectorValue = vector.value;
  9753. switch (vectorValue.length) {
  9754. case 2:
  9755. material[vector.name] = new Vector2(vectorValue[0], vectorValue[1]);
  9756. break;
  9757. case 3:
  9758. material[vector.name] = new Vector3(vectorValue[0], vectorValue[1], vectorValue[2]);
  9759. break;
  9760. case 4:
  9761. material[vector.name] = new Vector4(vectorValue[0], vectorValue[1], vectorValue[2], vectorValue[3]);
  9762. break;
  9763. default:
  9764. throw new Error("BaseMaterial:unkonwn color length.");
  9765. }
  9766. }
  9767. break;
  9768. case "textures":
  9769. var textures = props[key];
  9770. for (i = 0, n = textures.length; i < n; i++) {
  9771. var texture = textures[i];
  9772. var path = texture.path;
  9773. (path) && (material[texture.name] = Laya.Loader.getRes(path));
  9774. }
  9775. break;
  9776. case "defines":
  9777. var defineNames = props[key];
  9778. for (i = 0, n = defineNames.length; i < n; i++) {
  9779. var define = Shader3D.getDefineByName(defineNames[i]);
  9780. material._shaderValues.addDefine(define);
  9781. }
  9782. break;
  9783. case "renderStates":
  9784. var renderStatesData = props[key];
  9785. var renderStateData = renderStatesData[0];
  9786. var mat = material;
  9787. mat.blend = renderStateData.blend;
  9788. mat.cull = renderStateData.cull;
  9789. mat.depthTest = renderStateData.depthTest;
  9790. mat.depthWrite = renderStateData.depthWrite;
  9791. mat.blendSrc = renderStateData.srcBlend;
  9792. mat.blendDst = renderStateData.dstBlend;
  9793. break;
  9794. case "cull":
  9795. material.cull = props[key];
  9796. break;
  9797. case "blend":
  9798. material.blend = props[key];
  9799. break;
  9800. case "depthWrite":
  9801. material.depthWrite = props[key];
  9802. break;
  9803. case "srcBlend":
  9804. material.blendSrc = props[key];
  9805. break;
  9806. case "dstBlend":
  9807. material.blendDst = props[key];
  9808. break;
  9809. default:
  9810. material[key] = props[key];
  9811. }
  9812. }
  9813. break;
  9814. default:
  9815. throw new Error("BaseMaterial:unkonwn version.");
  9816. }
  9817. return material;
  9818. }
  9819. get shaderData() {
  9820. return this._shaderValues;
  9821. }
  9822. get alphaTestValue() {
  9823. return this._shaderValues.getNumber(Material.ALPHATESTVALUE);
  9824. }
  9825. set alphaTestValue(value) {
  9826. this._shaderValues.setNumber(Material.ALPHATESTVALUE, value);
  9827. }
  9828. get alphaTest() {
  9829. return this._alphaTest;
  9830. }
  9831. set alphaTest(value) {
  9832. this._alphaTest = value;
  9833. if (value)
  9834. this._shaderValues.addDefine(Material.SHADERDEFINE_ALPHATEST);
  9835. else
  9836. this._shaderValues.removeDefine(Material.SHADERDEFINE_ALPHATEST);
  9837. }
  9838. _removeTetxureReference() {
  9839. var data = this._shaderValues.getData();
  9840. for (var k in data) {
  9841. var value = data[k];
  9842. if (value && value instanceof Laya.BaseTexture)
  9843. value._removeReference();
  9844. }
  9845. }
  9846. _disposeResource() {
  9847. if (this._referenceCount > 0)
  9848. this._removeTetxureReference();
  9849. this._shaderValues = null;
  9850. }
  9851. _addReference(count = 1) {
  9852. super._addReference(count);
  9853. var data = this._shaderValues.getData();
  9854. for (var k in data) {
  9855. var value = data[k];
  9856. if (value && value instanceof Laya.BaseTexture)
  9857. value._addReference();
  9858. }
  9859. }
  9860. _removeReference(count = 1) {
  9861. super._removeReference(count);
  9862. this._removeTetxureReference();
  9863. }
  9864. setShaderName(name) {
  9865. this._shader = Shader3D.find(name);
  9866. if (!this._shader)
  9867. throw new Error("BaseMaterial: unknown shader name.");
  9868. }
  9869. cloneTo(destObject) {
  9870. var destBaseMaterial = destObject;
  9871. destBaseMaterial.name = this.name;
  9872. destBaseMaterial.renderQueue = this.renderQueue;
  9873. this._shaderValues.cloneTo(destBaseMaterial._shaderValues);
  9874. }
  9875. clone() {
  9876. var dest = new Material();
  9877. this.cloneTo(dest);
  9878. return dest;
  9879. }
  9880. get _defineDatas() {
  9881. return this._shaderValues._defineDatas;
  9882. }
  9883. }
  9884. Material.MATERIAL = "MATERIAL";
  9885. Material.RENDERQUEUE_OPAQUE = 2000;
  9886. Material.RENDERQUEUE_ALPHATEST = 2450;
  9887. Material.RENDERQUEUE_TRANSPARENT = 3000;
  9888. Material.ALPHATESTVALUE = Shader3D.propertyNameToID("u_AlphaTestValue");
  9889. Material.SHADERDEFINE_ALPHATEST = null;
  9890. class BaseMaterial {
  9891. static load(url, complete) {
  9892. Laya.Laya.loader.create(url, complete, null, Material.MATERIAL);
  9893. }
  9894. static __initDefine__() {
  9895. BaseMaterial.SHADERDEFINE_ALPHATEST = Material.SHADERDEFINE_ALPHATEST;
  9896. }
  9897. }
  9898. BaseMaterial.MATERIAL = "MATERIAL";
  9899. BaseMaterial.RENDERQUEUE_OPAQUE = 2000;
  9900. BaseMaterial.RENDERQUEUE_ALPHATEST = 2450;
  9901. BaseMaterial.RENDERQUEUE_TRANSPARENT = 3000;
  9902. BaseMaterial.ALPHATESTVALUE = Shader3D.propertyNameToID("u_AlphaTestValue");
  9903. BaseMaterial.SHADERDEFINE_ALPHATEST = null;
  9904. class RenderState {
  9905. constructor() {
  9906. this.cull = RenderState.CULL_BACK;
  9907. this.blend = RenderState.BLEND_DISABLE;
  9908. this.srcBlend = RenderState.BLENDPARAM_ONE;
  9909. this.dstBlend = RenderState.BLENDPARAM_ZERO;
  9910. this.srcBlendRGB = RenderState.BLENDPARAM_ONE;
  9911. this.dstBlendRGB = RenderState.BLENDPARAM_ZERO;
  9912. this.srcBlendAlpha = RenderState.BLENDPARAM_ONE;
  9913. this.dstBlendAlpha = RenderState.BLENDPARAM_ZERO;
  9914. this.blendConstColor = new Vector4(1, 1, 1, 1);
  9915. this.blendEquation = RenderState.BLENDEQUATION_ADD;
  9916. this.blendEquationRGB = RenderState.BLENDEQUATION_ADD;
  9917. this.blendEquationAlpha = RenderState.BLENDEQUATION_ADD;
  9918. this.depthTest = RenderState.DEPTHTEST_LEQUAL;
  9919. this.depthWrite = true;
  9920. }
  9921. cloneTo(dest) {
  9922. var destState = dest;
  9923. destState.cull = this.cull;
  9924. destState.blend = this.blend;
  9925. destState.srcBlend = this.srcBlend;
  9926. destState.dstBlend = this.dstBlend;
  9927. destState.srcBlendRGB = this.srcBlendRGB;
  9928. destState.dstBlendRGB = this.dstBlendRGB;
  9929. destState.srcBlendAlpha = this.srcBlendAlpha;
  9930. destState.dstBlendAlpha = this.dstBlendAlpha;
  9931. this.blendConstColor.cloneTo(destState.blendConstColor);
  9932. destState.blendEquation = this.blendEquation;
  9933. destState.blendEquationRGB = this.blendEquationRGB;
  9934. destState.blendEquationAlpha = this.blendEquationAlpha;
  9935. destState.depthTest = this.depthTest;
  9936. destState.depthWrite = this.depthWrite;
  9937. }
  9938. clone() {
  9939. var dest = new RenderState();
  9940. this.cloneTo(dest);
  9941. return dest;
  9942. }
  9943. }
  9944. RenderState.CULL_NONE = 0;
  9945. RenderState.CULL_FRONT = 1;
  9946. RenderState.CULL_BACK = 2;
  9947. RenderState.BLEND_DISABLE = 0;
  9948. RenderState.BLEND_ENABLE_ALL = 1;
  9949. RenderState.BLEND_ENABLE_SEPERATE = 2;
  9950. RenderState.BLENDPARAM_ZERO = 0;
  9951. RenderState.BLENDPARAM_ONE = 1;
  9952. RenderState.BLENDPARAM_SRC_COLOR = 0x0300;
  9953. RenderState.BLENDPARAM_ONE_MINUS_SRC_COLOR = 0x0301;
  9954. RenderState.BLENDPARAM_DST_COLOR = 0x0306;
  9955. RenderState.BLENDPARAM_ONE_MINUS_DST_COLOR = 0x0307;
  9956. RenderState.BLENDPARAM_SRC_ALPHA = 0x0302;
  9957. RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA = 0x0303;
  9958. RenderState.BLENDPARAM_DST_ALPHA = 0x0304;
  9959. RenderState.BLENDPARAM_ONE_MINUS_DST_ALPHA = 0x0305;
  9960. RenderState.BLENDPARAM_SRC_ALPHA_SATURATE = 0x0308;
  9961. RenderState.BLENDEQUATION_ADD = 0x8006;
  9962. RenderState.BLENDEQUATION_SUBTRACT = 0x800A;
  9963. RenderState.BLENDEQUATION_REVERSE_SUBTRACT = 0x800B;
  9964. RenderState.DEPTHTEST_OFF = 0;
  9965. RenderState.DEPTHTEST_NEVER = 0x0200;
  9966. RenderState.DEPTHTEST_LESS = 0x0201;
  9967. RenderState.DEPTHTEST_EQUAL = 0x0202;
  9968. RenderState.DEPTHTEST_LEQUAL = 0x0203;
  9969. RenderState.DEPTHTEST_GREATER = 0x0204;
  9970. RenderState.DEPTHTEST_NOTEQUAL = 0x0205;
  9971. RenderState.DEPTHTEST_GEQUAL = 0x0206;
  9972. RenderState.DEPTHTEST_ALWAYS = 0x0207;
  9973. class BlinnPhongMaterial extends Material {
  9974. constructor() {
  9975. super();
  9976. this._enableVertexColor = false;
  9977. this.setShaderName("BLINNPHONG");
  9978. this._albedoIntensity = 1.0;
  9979. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  9980. var sv = this._shaderValues;
  9981. sv.setVector(BlinnPhongMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  9982. sv.setVector(BlinnPhongMaterial.MATERIALSPECULAR, new Vector4(1.0, 1.0, 1.0, 1.0));
  9983. sv.setNumber(BlinnPhongMaterial.SHININESS, 0.078125);
  9984. sv.setNumber(Material.ALPHATESTVALUE, 0.5);
  9985. sv.setVector(BlinnPhongMaterial.TILINGOFFSET, new Vector4(1.0, 1.0, 0.0, 0.0));
  9986. this._enableLighting = true;
  9987. this.renderMode = BlinnPhongMaterial.RENDERMODE_OPAQUE;
  9988. }
  9989. static __initDefine__() {
  9990. BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP = Shader3D.getDefineByName("DIFFUSEMAP");
  9991. BlinnPhongMaterial.SHADERDEFINE_NORMALMAP = Shader3D.getDefineByName("NORMALMAP");
  9992. BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP = Shader3D.getDefineByName("SPECULARMAP");
  9993. BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  9994. BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR = Shader3D.getDefineByName("ENABLEVERTEXCOLOR");
  9995. }
  9996. get _ColorR() {
  9997. return this._albedoColor.x;
  9998. }
  9999. set _ColorR(value) {
  10000. this._albedoColor.x = value;
  10001. this.albedoColor = this._albedoColor;
  10002. }
  10003. get _ColorG() {
  10004. return this._albedoColor.y;
  10005. }
  10006. set _ColorG(value) {
  10007. this._albedoColor.y = value;
  10008. this.albedoColor = this._albedoColor;
  10009. }
  10010. get _ColorB() {
  10011. return this._albedoColor.z;
  10012. }
  10013. set _ColorB(value) {
  10014. this._albedoColor.z = value;
  10015. this.albedoColor = this._albedoColor;
  10016. }
  10017. get _ColorA() {
  10018. return this._albedoColor.w;
  10019. }
  10020. set _ColorA(value) {
  10021. this._albedoColor.w = value;
  10022. this.albedoColor = this._albedoColor;
  10023. }
  10024. get _Color() {
  10025. return this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  10026. }
  10027. set _Color(value) {
  10028. this.albedoColor = value;
  10029. }
  10030. get _SpecColorR() {
  10031. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).x;
  10032. }
  10033. set _SpecColorR(value) {
  10034. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).x = value;
  10035. }
  10036. get _SpecColorG() {
  10037. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).y;
  10038. }
  10039. set _SpecColorG(value) {
  10040. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).y = value;
  10041. }
  10042. get _SpecColorB() {
  10043. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).z;
  10044. }
  10045. set _SpecColorB(value) {
  10046. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).z = value;
  10047. }
  10048. get _SpecColorA() {
  10049. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).w;
  10050. }
  10051. set _SpecColorA(value) {
  10052. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).w = value;
  10053. }
  10054. get _SpecColor() {
  10055. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR);
  10056. }
  10057. set _SpecColor(value) {
  10058. this.specularColor = value;
  10059. }
  10060. get _AlbedoIntensity() {
  10061. return this._albedoIntensity;
  10062. }
  10063. set _AlbedoIntensity(value) {
  10064. if (this._albedoIntensity !== value) {
  10065. var finalAlbedo = this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  10066. Vector4.scale(this._albedoColor, value, finalAlbedo);
  10067. this._albedoIntensity = value;
  10068. this._shaderValues.setVector(BlinnPhongMaterial.ALBEDOCOLOR, finalAlbedo);
  10069. }
  10070. }
  10071. get _Shininess() {
  10072. return this._shaderValues.getNumber(BlinnPhongMaterial.SHININESS);
  10073. }
  10074. set _Shininess(value) {
  10075. value = Math.max(0.0, Math.min(1.0, value));
  10076. this._shaderValues.setNumber(BlinnPhongMaterial.SHININESS, value);
  10077. }
  10078. get _MainTex_STX() {
  10079. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).x;
  10080. }
  10081. set _MainTex_STX(x) {
  10082. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  10083. tilOff.x = x;
  10084. this.tilingOffset = tilOff;
  10085. }
  10086. get _MainTex_STY() {
  10087. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).y;
  10088. }
  10089. set _MainTex_STY(y) {
  10090. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  10091. tilOff.y = y;
  10092. this.tilingOffset = tilOff;
  10093. }
  10094. get _MainTex_STZ() {
  10095. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).z;
  10096. }
  10097. set _MainTex_STZ(z) {
  10098. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  10099. tilOff.z = z;
  10100. this.tilingOffset = tilOff;
  10101. }
  10102. get _MainTex_STW() {
  10103. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).w;
  10104. }
  10105. set _MainTex_STW(w) {
  10106. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  10107. tilOff.w = w;
  10108. this.tilingOffset = tilOff;
  10109. }
  10110. get _MainTex_ST() {
  10111. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  10112. }
  10113. set _MainTex_ST(value) {
  10114. this.tilingOffset = value;
  10115. }
  10116. get _Cutoff() {
  10117. return this.alphaTestValue;
  10118. }
  10119. set _Cutoff(value) {
  10120. this.alphaTestValue = value;
  10121. }
  10122. set renderMode(value) {
  10123. switch (value) {
  10124. case BlinnPhongMaterial.RENDERMODE_OPAQUE:
  10125. this.alphaTest = false;
  10126. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  10127. this.depthWrite = true;
  10128. this.cull = RenderState.CULL_BACK;
  10129. this.blend = RenderState.BLEND_DISABLE;
  10130. this.depthTest = RenderState.DEPTHTEST_LESS;
  10131. break;
  10132. case BlinnPhongMaterial.RENDERMODE_CUTOUT:
  10133. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  10134. this.alphaTest = true;
  10135. this.depthWrite = true;
  10136. this.cull = RenderState.CULL_BACK;
  10137. this.blend = RenderState.BLEND_DISABLE;
  10138. this.depthTest = RenderState.DEPTHTEST_LESS;
  10139. break;
  10140. case BlinnPhongMaterial.RENDERMODE_TRANSPARENT:
  10141. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  10142. this.alphaTest = false;
  10143. this.depthWrite = false;
  10144. this.cull = RenderState.CULL_BACK;
  10145. this.blend = RenderState.BLEND_ENABLE_ALL;
  10146. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  10147. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  10148. this.depthTest = RenderState.DEPTHTEST_LESS;
  10149. break;
  10150. default:
  10151. throw new Error("Material:renderMode value error.");
  10152. }
  10153. }
  10154. get enableVertexColor() {
  10155. return this._enableVertexColor;
  10156. }
  10157. set enableVertexColor(value) {
  10158. this._enableVertexColor = value;
  10159. if (value)
  10160. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  10161. else
  10162. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  10163. }
  10164. get tilingOffsetX() {
  10165. return this._MainTex_STX;
  10166. }
  10167. set tilingOffsetX(x) {
  10168. this._MainTex_STX = x;
  10169. }
  10170. get tilingOffsetY() {
  10171. return this._MainTex_STY;
  10172. }
  10173. set tilingOffsetY(y) {
  10174. this._MainTex_STY = y;
  10175. }
  10176. get tilingOffsetZ() {
  10177. return this._MainTex_STZ;
  10178. }
  10179. set tilingOffsetZ(z) {
  10180. this._MainTex_STZ = z;
  10181. }
  10182. get tilingOffsetW() {
  10183. return this._MainTex_STW;
  10184. }
  10185. set tilingOffsetW(w) {
  10186. this._MainTex_STW = w;
  10187. }
  10188. get tilingOffset() {
  10189. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  10190. }
  10191. set tilingOffset(value) {
  10192. if (value) {
  10193. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  10194. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  10195. else
  10196. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  10197. }
  10198. else {
  10199. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  10200. }
  10201. this._shaderValues.setVector(BlinnPhongMaterial.TILINGOFFSET, value);
  10202. }
  10203. get albedoColorR() {
  10204. return this._ColorR;
  10205. }
  10206. set albedoColorR(value) {
  10207. this._ColorR = value;
  10208. }
  10209. get albedoColorG() {
  10210. return this._ColorG;
  10211. }
  10212. set albedoColorG(value) {
  10213. this._ColorG = value;
  10214. }
  10215. get albedoColorB() {
  10216. return this._ColorB;
  10217. }
  10218. set albedoColorB(value) {
  10219. this._ColorB = value;
  10220. }
  10221. get albedoColorA() {
  10222. return this._ColorA;
  10223. }
  10224. set albedoColorA(value) {
  10225. this._ColorA = value;
  10226. }
  10227. get albedoColor() {
  10228. return this._albedoColor;
  10229. }
  10230. set albedoColor(value) {
  10231. var finalAlbedo = this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  10232. Vector4.scale(value, this._albedoIntensity, finalAlbedo);
  10233. this._albedoColor = value;
  10234. this._shaderValues.setVector(BlinnPhongMaterial.ALBEDOCOLOR, finalAlbedo);
  10235. }
  10236. get albedoIntensity() {
  10237. return this._albedoIntensity;
  10238. }
  10239. set albedoIntensity(value) {
  10240. this._AlbedoIntensity = value;
  10241. }
  10242. get specularColorR() {
  10243. return this._SpecColorR;
  10244. }
  10245. set specularColorR(value) {
  10246. this._SpecColorR = value;
  10247. }
  10248. get specularColorG() {
  10249. return this._SpecColorG;
  10250. }
  10251. set specularColorG(value) {
  10252. this._SpecColorG = value;
  10253. }
  10254. get specularColorB() {
  10255. return this._SpecColorB;
  10256. }
  10257. set specularColorB(value) {
  10258. this._SpecColorB = value;
  10259. }
  10260. get specularColorA() {
  10261. return this._SpecColorA;
  10262. }
  10263. set specularColorA(value) {
  10264. this._SpecColorA = value;
  10265. }
  10266. get specularColor() {
  10267. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR);
  10268. }
  10269. set specularColor(value) {
  10270. this._shaderValues.setVector(BlinnPhongMaterial.MATERIALSPECULAR, value);
  10271. }
  10272. get shininess() {
  10273. return this._Shininess;
  10274. }
  10275. set shininess(value) {
  10276. this._Shininess = value;
  10277. }
  10278. get albedoTexture() {
  10279. return this._shaderValues.getTexture(BlinnPhongMaterial.ALBEDOTEXTURE);
  10280. }
  10281. set albedoTexture(value) {
  10282. if (value)
  10283. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP);
  10284. else
  10285. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP);
  10286. this._shaderValues.setTexture(BlinnPhongMaterial.ALBEDOTEXTURE, value);
  10287. }
  10288. get normalTexture() {
  10289. return this._shaderValues.getTexture(BlinnPhongMaterial.NORMALTEXTURE);
  10290. }
  10291. set normalTexture(value) {
  10292. if (value)
  10293. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_NORMALMAP);
  10294. else
  10295. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_NORMALMAP);
  10296. this._shaderValues.setTexture(BlinnPhongMaterial.NORMALTEXTURE, value);
  10297. }
  10298. get specularTexture() {
  10299. return this._shaderValues.getTexture(BlinnPhongMaterial.SPECULARTEXTURE);
  10300. }
  10301. set specularTexture(value) {
  10302. if (value)
  10303. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP);
  10304. else
  10305. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP);
  10306. this._shaderValues.setTexture(BlinnPhongMaterial.SPECULARTEXTURE, value);
  10307. }
  10308. get depthWrite() {
  10309. return this._shaderValues.getBool(BlinnPhongMaterial.DEPTH_WRITE);
  10310. }
  10311. set depthWrite(value) {
  10312. this._shaderValues.setBool(BlinnPhongMaterial.DEPTH_WRITE, value);
  10313. }
  10314. get cull() {
  10315. return this._shaderValues.getInt(BlinnPhongMaterial.CULL);
  10316. }
  10317. set cull(value) {
  10318. this._shaderValues.setInt(BlinnPhongMaterial.CULL, value);
  10319. }
  10320. get blend() {
  10321. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND);
  10322. }
  10323. set blend(value) {
  10324. this._shaderValues.setInt(BlinnPhongMaterial.BLEND, value);
  10325. }
  10326. get blendSrc() {
  10327. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND_SRC);
  10328. }
  10329. set blendSrc(value) {
  10330. this._shaderValues.setInt(BlinnPhongMaterial.BLEND_SRC, value);
  10331. }
  10332. get blendDst() {
  10333. return this._shaderValues.getInt(BlinnPhongMaterial.BLEND_DST);
  10334. }
  10335. set blendDst(value) {
  10336. this._shaderValues.setInt(BlinnPhongMaterial.BLEND_DST, value);
  10337. }
  10338. get depthTest() {
  10339. return this._shaderValues.getInt(BlinnPhongMaterial.DEPTH_TEST);
  10340. }
  10341. set depthTest(value) {
  10342. this._shaderValues.setInt(BlinnPhongMaterial.DEPTH_TEST, value);
  10343. }
  10344. clone() {
  10345. var dest = new BlinnPhongMaterial();
  10346. this.cloneTo(dest);
  10347. return dest;
  10348. }
  10349. cloneTo(destObject) {
  10350. super.cloneTo(destObject);
  10351. var destMaterial = destObject;
  10352. destMaterial._enableLighting = this._enableLighting;
  10353. destMaterial._albedoIntensity = this._albedoIntensity;
  10354. destMaterial._enableVertexColor = this._enableVertexColor;
  10355. this._albedoColor.cloneTo(destMaterial._albedoColor);
  10356. }
  10357. }
  10358. BlinnPhongMaterial.RENDERMODE_OPAQUE = 0;
  10359. BlinnPhongMaterial.RENDERMODE_CUTOUT = 1;
  10360. BlinnPhongMaterial.RENDERMODE_TRANSPARENT = 2;
  10361. BlinnPhongMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_DiffuseTexture");
  10362. BlinnPhongMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  10363. BlinnPhongMaterial.SPECULARTEXTURE = Shader3D.propertyNameToID("u_SpecularTexture");
  10364. BlinnPhongMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_DiffuseColor");
  10365. BlinnPhongMaterial.MATERIALSPECULAR = Shader3D.propertyNameToID("u_MaterialSpecular");
  10366. BlinnPhongMaterial.SHININESS = Shader3D.propertyNameToID("u_Shininess");
  10367. BlinnPhongMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  10368. BlinnPhongMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  10369. BlinnPhongMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  10370. BlinnPhongMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  10371. BlinnPhongMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  10372. BlinnPhongMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  10373. BlinnPhongMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  10374. class EffectMaterial extends Material {
  10375. constructor() {
  10376. super();
  10377. this.setShaderName("Effect");
  10378. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  10379. this._shaderValues.setVector(EffectMaterial.TINTCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  10380. this.renderMode = EffectMaterial.RENDERMODE_ADDTIVE;
  10381. }
  10382. static __initDefine__() {
  10383. EffectMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  10384. EffectMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  10385. EffectMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  10386. }
  10387. get _TintColorR() {
  10388. return this._color.x;
  10389. }
  10390. set _TintColorR(value) {
  10391. this._color.x = value;
  10392. this.color = this._color;
  10393. }
  10394. get _TintColorG() {
  10395. return this._color.y;
  10396. }
  10397. set _TintColorG(value) {
  10398. this._color.y = value;
  10399. this.color = this._color;
  10400. }
  10401. get _TintColorB() {
  10402. return this._color.z;
  10403. }
  10404. set _TintColorB(value) {
  10405. this._color.z = value;
  10406. this.color = this._color;
  10407. }
  10408. get _TintColorA() {
  10409. return this._color.w;
  10410. }
  10411. set _TintColorA(value) {
  10412. this._color.w = value;
  10413. this.color = this._color;
  10414. }
  10415. get _MainTex_STX() {
  10416. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).x;
  10417. }
  10418. set _MainTex_STX(x) {
  10419. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  10420. tilOff.x = x;
  10421. this.tilingOffset = tilOff;
  10422. }
  10423. get _MainTex_STY() {
  10424. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).y;
  10425. }
  10426. set _MainTex_STY(y) {
  10427. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  10428. tilOff.y = y;
  10429. this.tilingOffset = tilOff;
  10430. }
  10431. get _MainTex_STZ() {
  10432. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).z;
  10433. }
  10434. set _MainTex_STZ(z) {
  10435. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  10436. tilOff.z = z;
  10437. this.tilingOffset = tilOff;
  10438. }
  10439. get _MainTex_STW() {
  10440. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).w;
  10441. }
  10442. set _MainTex_STW(w) {
  10443. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  10444. tilOff.w = w;
  10445. this.tilingOffset = tilOff;
  10446. }
  10447. set renderMode(value) {
  10448. switch (value) {
  10449. case EffectMaterial.RENDERMODE_ADDTIVE:
  10450. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  10451. this.alphaTest = false;
  10452. this.depthWrite = false;
  10453. this.cull = RenderState.CULL_NONE;
  10454. this.blend = RenderState.BLEND_ENABLE_ALL;
  10455. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  10456. this.blendDst = RenderState.BLENDPARAM_ONE;
  10457. this.depthTest = RenderState.DEPTHTEST_LESS;
  10458. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_ADDTIVEFOG);
  10459. break;
  10460. case EffectMaterial.RENDERMODE_ALPHABLENDED:
  10461. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  10462. this.alphaTest = false;
  10463. this.depthWrite = false;
  10464. this.cull = RenderState.CULL_NONE;
  10465. this.blend = RenderState.BLEND_ENABLE_ALL;
  10466. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  10467. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  10468. this.depthTest = RenderState.DEPTHTEST_LESS;
  10469. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_ADDTIVEFOG);
  10470. break;
  10471. default:
  10472. throw new Error("MeshEffectMaterial : renderMode value error.");
  10473. }
  10474. }
  10475. get colorR() {
  10476. return this._TintColorR;
  10477. }
  10478. set colorR(value) {
  10479. this._TintColorR = value;
  10480. }
  10481. get colorG() {
  10482. return this._TintColorG;
  10483. }
  10484. set colorG(value) {
  10485. this._TintColorG = value;
  10486. }
  10487. get colorB() {
  10488. return this._TintColorB;
  10489. }
  10490. set colorB(value) {
  10491. this._TintColorB = value;
  10492. }
  10493. get colorA() {
  10494. return this._TintColorA;
  10495. }
  10496. set colorA(value) {
  10497. this._TintColorA = value;
  10498. }
  10499. get color() {
  10500. return this._shaderValues.getVector(EffectMaterial.TINTCOLOR);
  10501. }
  10502. set color(value) {
  10503. this._shaderValues.setVector(EffectMaterial.TINTCOLOR, value);
  10504. }
  10505. get texture() {
  10506. return this._shaderValues.getTexture(EffectMaterial.MAINTEXTURE);
  10507. }
  10508. set texture(value) {
  10509. if (value)
  10510. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_MAINTEXTURE);
  10511. else
  10512. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_MAINTEXTURE);
  10513. this._shaderValues.setTexture(EffectMaterial.MAINTEXTURE, value);
  10514. }
  10515. get tilingOffsetX() {
  10516. return this._MainTex_STX;
  10517. }
  10518. set tilingOffsetX(x) {
  10519. this._MainTex_STX = x;
  10520. }
  10521. get tilingOffsetY() {
  10522. return this._MainTex_STY;
  10523. }
  10524. set tilingOffsetY(y) {
  10525. this._MainTex_STY = y;
  10526. }
  10527. get tilingOffsetZ() {
  10528. return this._MainTex_STZ;
  10529. }
  10530. set tilingOffsetZ(z) {
  10531. this._MainTex_STZ = z;
  10532. }
  10533. get tilingOffsetW() {
  10534. return this._MainTex_STW;
  10535. }
  10536. set tilingOffsetW(w) {
  10537. this._MainTex_STW = w;
  10538. }
  10539. get tilingOffset() {
  10540. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  10541. }
  10542. set tilingOffset(value) {
  10543. if (value) {
  10544. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  10545. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  10546. else
  10547. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  10548. }
  10549. else {
  10550. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  10551. }
  10552. this._shaderValues.setVector(EffectMaterial.TILINGOFFSET, value);
  10553. }
  10554. get depthWrite() {
  10555. return this._shaderValues.getBool(EffectMaterial.DEPTH_WRITE);
  10556. }
  10557. set depthWrite(value) {
  10558. this._shaderValues.setBool(EffectMaterial.DEPTH_WRITE, value);
  10559. }
  10560. get cull() {
  10561. return this._shaderValues.getInt(EffectMaterial.CULL);
  10562. }
  10563. set cull(value) {
  10564. this._shaderValues.setInt(EffectMaterial.CULL, value);
  10565. }
  10566. get blend() {
  10567. return this._shaderValues.getInt(EffectMaterial.BLEND);
  10568. }
  10569. set blend(value) {
  10570. this._shaderValues.setInt(EffectMaterial.BLEND, value);
  10571. }
  10572. get blendSrc() {
  10573. return this._shaderValues.getInt(EffectMaterial.BLEND_SRC);
  10574. }
  10575. set blendSrc(value) {
  10576. this._shaderValues.setInt(EffectMaterial.BLEND_SRC, value);
  10577. }
  10578. get blendDst() {
  10579. return this._shaderValues.getInt(EffectMaterial.BLEND_DST);
  10580. }
  10581. set blendDst(value) {
  10582. this._shaderValues.setInt(EffectMaterial.BLEND_DST, value);
  10583. }
  10584. get depthTest() {
  10585. return this._shaderValues.getInt(EffectMaterial.DEPTH_TEST);
  10586. }
  10587. set depthTest(value) {
  10588. this._shaderValues.setInt(EffectMaterial.DEPTH_TEST, value);
  10589. }
  10590. clone() {
  10591. var dest = new EffectMaterial();
  10592. this.cloneTo(dest);
  10593. return dest;
  10594. }
  10595. }
  10596. EffectMaterial.RENDERMODE_ADDTIVE = 0;
  10597. EffectMaterial.RENDERMODE_ALPHABLENDED = 1;
  10598. EffectMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  10599. EffectMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  10600. EffectMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  10601. EffectMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  10602. EffectMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  10603. EffectMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  10604. EffectMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  10605. EffectMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  10606. EffectMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  10607. class ExtendTerrainMaterial extends Material {
  10608. constructor() {
  10609. super();
  10610. this._enableLighting = true;
  10611. this.setShaderName("ExtendTerrain");
  10612. this.renderMode = ExtendTerrainMaterial.RENDERMODE_OPAQUE;
  10613. }
  10614. static __initDefine__() {
  10615. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM1");
  10616. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM2");
  10617. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM3");
  10618. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM4");
  10619. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM5");
  10620. }
  10621. get splatAlphaTexture() {
  10622. return this._shaderValues.getTexture(ExtendTerrainMaterial.SPLATALPHATEXTURE);
  10623. }
  10624. set splatAlphaTexture(value) {
  10625. this._shaderValues.setTexture(ExtendTerrainMaterial.SPLATALPHATEXTURE, value);
  10626. }
  10627. get diffuseTexture1() {
  10628. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE1);
  10629. }
  10630. set diffuseTexture1(value) {
  10631. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE1, value);
  10632. this._setDetailNum(1);
  10633. }
  10634. get diffuseTexture2() {
  10635. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE2);
  10636. }
  10637. set diffuseTexture2(value) {
  10638. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE2, value);
  10639. this._setDetailNum(2);
  10640. }
  10641. get diffuseTexture3() {
  10642. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE3);
  10643. }
  10644. set diffuseTexture3(value) {
  10645. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE3, value);
  10646. this._setDetailNum(3);
  10647. }
  10648. get diffuseTexture4() {
  10649. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE4);
  10650. }
  10651. set diffuseTexture4(value) {
  10652. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE4, value);
  10653. this._setDetailNum(4);
  10654. }
  10655. get diffuseTexture5() {
  10656. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE5);
  10657. }
  10658. set diffuseTexture5(value) {
  10659. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE5, value);
  10660. this._setDetailNum(5);
  10661. }
  10662. set diffuseScaleOffset1(scaleOffset1) {
  10663. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET1, scaleOffset1);
  10664. }
  10665. set diffuseScaleOffset2(scaleOffset2) {
  10666. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET2, scaleOffset2);
  10667. }
  10668. set diffuseScaleOffset3(scaleOffset3) {
  10669. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET3, scaleOffset3);
  10670. }
  10671. set diffuseScaleOffset4(scaleOffset4) {
  10672. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET4, scaleOffset4);
  10673. }
  10674. set diffuseScaleOffset5(scaleOffset5) {
  10675. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET5, scaleOffset5);
  10676. }
  10677. set renderMode(value) {
  10678. switch (value) {
  10679. case ExtendTerrainMaterial.RENDERMODE_OPAQUE:
  10680. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  10681. this.depthWrite = true;
  10682. this.cull = RenderState.CULL_BACK;
  10683. this.blend = RenderState.BLEND_DISABLE;
  10684. this.depthTest = RenderState.DEPTHTEST_LESS;
  10685. break;
  10686. case ExtendTerrainMaterial.RENDERMODE_TRANSPARENT:
  10687. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  10688. this.depthWrite = false;
  10689. this.cull = RenderState.CULL_BACK;
  10690. this.blend = RenderState.BLEND_ENABLE_ALL;
  10691. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  10692. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  10693. this.depthTest = RenderState.DEPTHTEST_LEQUAL;
  10694. break;
  10695. default:
  10696. throw new Error("ExtendTerrainMaterial:renderMode value error.");
  10697. }
  10698. }
  10699. get depthWrite() {
  10700. return this._shaderValues.getBool(ExtendTerrainMaterial.DEPTH_WRITE);
  10701. }
  10702. set depthWrite(value) {
  10703. this._shaderValues.setBool(ExtendTerrainMaterial.DEPTH_WRITE, value);
  10704. }
  10705. get cull() {
  10706. return this._shaderValues.getInt(ExtendTerrainMaterial.CULL);
  10707. }
  10708. set cull(value) {
  10709. this._shaderValues.setInt(ExtendTerrainMaterial.CULL, value);
  10710. }
  10711. get blend() {
  10712. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND);
  10713. }
  10714. set blend(value) {
  10715. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND, value);
  10716. }
  10717. get blendSrc() {
  10718. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND_SRC);
  10719. }
  10720. set blendSrc(value) {
  10721. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND_SRC, value);
  10722. }
  10723. get blendDst() {
  10724. return this._shaderValues.getInt(ExtendTerrainMaterial.BLEND_DST);
  10725. }
  10726. set blendDst(value) {
  10727. this._shaderValues.setInt(ExtendTerrainMaterial.BLEND_DST, value);
  10728. }
  10729. get depthTest() {
  10730. return this._shaderValues.getInt(ExtendTerrainMaterial.DEPTH_TEST);
  10731. }
  10732. set depthTest(value) {
  10733. this._shaderValues.setInt(ExtendTerrainMaterial.DEPTH_TEST, value);
  10734. }
  10735. _setDetailNum(value) {
  10736. switch (value) {
  10737. case 1:
  10738. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  10739. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  10740. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  10741. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  10742. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  10743. break;
  10744. case 2:
  10745. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  10746. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  10747. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  10748. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  10749. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  10750. break;
  10751. case 3:
  10752. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  10753. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  10754. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  10755. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  10756. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  10757. break;
  10758. case 4:
  10759. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  10760. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  10761. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  10762. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  10763. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  10764. break;
  10765. case 5:
  10766. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  10767. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  10768. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  10769. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  10770. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  10771. break;
  10772. }
  10773. }
  10774. clone() {
  10775. var dest = new ExtendTerrainMaterial();
  10776. this.cloneTo(dest);
  10777. return dest;
  10778. }
  10779. }
  10780. ExtendTerrainMaterial.RENDERMODE_OPAQUE = 1;
  10781. ExtendTerrainMaterial.RENDERMODE_TRANSPARENT = 2;
  10782. ExtendTerrainMaterial.SPLATALPHATEXTURE = Shader3D.propertyNameToID("u_SplatAlphaTexture");
  10783. ExtendTerrainMaterial.DIFFUSETEXTURE1 = Shader3D.propertyNameToID("u_DiffuseTexture1");
  10784. ExtendTerrainMaterial.DIFFUSETEXTURE2 = Shader3D.propertyNameToID("u_DiffuseTexture2");
  10785. ExtendTerrainMaterial.DIFFUSETEXTURE3 = Shader3D.propertyNameToID("u_DiffuseTexture3");
  10786. ExtendTerrainMaterial.DIFFUSETEXTURE4 = Shader3D.propertyNameToID("u_DiffuseTexture4");
  10787. ExtendTerrainMaterial.DIFFUSETEXTURE5 = Shader3D.propertyNameToID("u_DiffuseTexture5");
  10788. ExtendTerrainMaterial.DIFFUSESCALEOFFSET1 = Shader3D.propertyNameToID("u_DiffuseScaleOffset1");
  10789. ExtendTerrainMaterial.DIFFUSESCALEOFFSET2 = Shader3D.propertyNameToID("u_DiffuseScaleOffset2");
  10790. ExtendTerrainMaterial.DIFFUSESCALEOFFSET3 = Shader3D.propertyNameToID("u_DiffuseScaleOffset3");
  10791. ExtendTerrainMaterial.DIFFUSESCALEOFFSET4 = Shader3D.propertyNameToID("u_DiffuseScaleOffset4");
  10792. ExtendTerrainMaterial.DIFFUSESCALEOFFSET5 = Shader3D.propertyNameToID("u_DiffuseScaleOffset5");
  10793. ExtendTerrainMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  10794. ExtendTerrainMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  10795. ExtendTerrainMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  10796. ExtendTerrainMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  10797. ExtendTerrainMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  10798. ExtendTerrainMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  10799. (function (PBRRenderMode) {
  10800. PBRRenderMode[PBRRenderMode["Opaque"] = 0] = "Opaque";
  10801. PBRRenderMode[PBRRenderMode["Cutout"] = 1] = "Cutout";
  10802. PBRRenderMode[PBRRenderMode["Fade"] = 2] = "Fade";
  10803. PBRRenderMode[PBRRenderMode["Transparent"] = 3] = "Transparent";
  10804. })(exports.PBRRenderMode || (exports.PBRRenderMode = {}));
  10805. class PBRMaterial extends Material {
  10806. constructor() {
  10807. super();
  10808. this._enableEmission = false;
  10809. this._shaderValues.setVector(PBRMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  10810. this._shaderValues.setVector(PBRMaterial.EMISSIONCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  10811. this._shaderValues.setNumber(PBRMaterial.SMOOTHNESS, 0.5);
  10812. this._shaderValues.setNumber(PBRMaterial.SMOOTHNESSSCALE, 1.0);
  10813. this._shaderValues.setNumber(PBRMaterial.OCCLUSIONSTRENGTH, 1.0);
  10814. this._shaderValues.setNumber(PBRMaterial.NORMALSCALE, 1.0);
  10815. this._shaderValues.setNumber(PBRMaterial.PARALLAXSCALE, 0.001);
  10816. this._shaderValues.setNumber(Material.ALPHATESTVALUE, 0.5);
  10817. this.renderMode = exports.PBRRenderMode.Opaque;
  10818. }
  10819. static __init__() {
  10820. PBRMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  10821. PBRMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  10822. PBRMaterial.SHADERDEFINE_PARALLAXTEXTURE = Shader3D.getDefineByName("PARALLAXTEXTURE");
  10823. PBRMaterial.SHADERDEFINE_OCCLUSIONTEXTURE = Shader3D.getDefineByName("OCCLUSIONTEXTURE");
  10824. PBRMaterial.SHADERDEFINE_EMISSION = Shader3D.getDefineByName("EMISSION");
  10825. PBRMaterial.SHADERDEFINE_EMISSIONTEXTURE = Shader3D.getDefineByName("EMISSIONTEXTURE");
  10826. PBRMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  10827. PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND = Shader3D.getDefineByName("TRANSPARENTBLEND");
  10828. PBRMaterial.SHADERDEFINE_LAYA_PBR_BRDF_HIGH = Shader3D.getDefineByName("LAYA_PBR_BRDF_HIGH");
  10829. PBRMaterial.SHADERDEFINE_LAYA_PBR_BRDF_LOW = Shader3D.getDefineByName("LAYA_PBR_BRDF_LOW");
  10830. }
  10831. get albedoColor() {
  10832. return this._shaderValues.getVector(PBRMaterial.ALBEDOCOLOR);
  10833. }
  10834. set albedoColor(value) {
  10835. this._shaderValues.setVector(PBRMaterial.ALBEDOCOLOR, value);
  10836. }
  10837. get albedoTexture() {
  10838. return this._shaderValues.getTexture(PBRMaterial.ALBEDOTEXTURE);
  10839. }
  10840. set albedoTexture(value) {
  10841. if (value)
  10842. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  10843. else
  10844. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  10845. this._shaderValues.setTexture(PBRMaterial.ALBEDOTEXTURE, value);
  10846. }
  10847. get normalTexture() {
  10848. return this._shaderValues.getTexture(PBRMaterial.NORMALTEXTURE);
  10849. }
  10850. set normalTexture(value) {
  10851. if (value) {
  10852. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_NORMALTEXTURE);
  10853. }
  10854. else {
  10855. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_NORMALTEXTURE);
  10856. }
  10857. this._shaderValues.setTexture(PBRMaterial.NORMALTEXTURE, value);
  10858. }
  10859. get normalTextureScale() {
  10860. return this._shaderValues.getNumber(PBRMaterial.NORMALSCALE);
  10861. }
  10862. set normalTextureScale(value) {
  10863. this._shaderValues.setNumber(PBRMaterial.NORMALSCALE, value);
  10864. }
  10865. get parallaxTexture() {
  10866. return this._shaderValues.getTexture(PBRMaterial.PARALLAXTEXTURE);
  10867. }
  10868. set parallaxTexture(value) {
  10869. if (value)
  10870. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  10871. else
  10872. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  10873. this._shaderValues.setTexture(PBRMaterial.PARALLAXTEXTURE, value);
  10874. }
  10875. get parallaxTextureScale() {
  10876. return this._shaderValues.getNumber(PBRMaterial.PARALLAXSCALE);
  10877. }
  10878. set parallaxTextureScale(value) {
  10879. this._shaderValues.setNumber(PBRMaterial.PARALLAXSCALE, Math.max(0.005, Math.min(0.08, value)));
  10880. }
  10881. get occlusionTexture() {
  10882. return this._shaderValues.getTexture(PBRMaterial.OCCLUSIONTEXTURE);
  10883. }
  10884. set occlusionTexture(value) {
  10885. if (value)
  10886. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  10887. else
  10888. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  10889. this._shaderValues.setTexture(PBRMaterial.OCCLUSIONTEXTURE, value);
  10890. }
  10891. get occlusionTextureStrength() {
  10892. return this._shaderValues.getNumber(PBRMaterial.OCCLUSIONSTRENGTH);
  10893. }
  10894. set occlusionTextureStrength(value) {
  10895. this._shaderValues.setNumber(PBRMaterial.OCCLUSIONSTRENGTH, Math.max(0.0, Math.min(1.0, value)));
  10896. }
  10897. get smoothness() {
  10898. return this._shaderValues.getNumber(PBRMaterial.SMOOTHNESS);
  10899. }
  10900. set smoothness(value) {
  10901. this._shaderValues.setNumber(PBRMaterial.SMOOTHNESS, Math.max(0.0, Math.min(1.0, value)));
  10902. }
  10903. get smoothnessTextureScale() {
  10904. return this._shaderValues.getNumber(PBRMaterial.SMOOTHNESSSCALE);
  10905. }
  10906. set smoothnessTextureScale(value) {
  10907. this._shaderValues.setNumber(PBRMaterial.SMOOTHNESSSCALE, Math.max(0.0, Math.min(1.0, value)));
  10908. }
  10909. get enableEmission() {
  10910. return this._enableEmission;
  10911. }
  10912. set enableEmission(value) {
  10913. if (value)
  10914. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_EMISSION);
  10915. else
  10916. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_EMISSION);
  10917. this._enableEmission = value;
  10918. }
  10919. get emissionColor() {
  10920. return this._shaderValues.getVector(PBRMaterial.EMISSIONCOLOR);
  10921. }
  10922. set emissionColor(value) {
  10923. this._shaderValues.setVector(PBRMaterial.EMISSIONCOLOR, value);
  10924. }
  10925. get emissionTexture() {
  10926. return this._shaderValues.getTexture(PBRMaterial.EMISSIONTEXTURE);
  10927. }
  10928. set emissionTexture(value) {
  10929. if (value)
  10930. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  10931. else
  10932. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  10933. this._shaderValues.setTexture(PBRMaterial.EMISSIONTEXTURE, value);
  10934. }
  10935. get tilingOffset() {
  10936. return this._shaderValues.getVector(PBRMaterial.TILINGOFFSET);
  10937. }
  10938. set tilingOffset(value) {
  10939. if (value) {
  10940. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  10941. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_TILINGOFFSET);
  10942. else
  10943. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TILINGOFFSET);
  10944. }
  10945. else {
  10946. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TILINGOFFSET);
  10947. }
  10948. this._shaderValues.setVector(PBRMaterial.TILINGOFFSET, value);
  10949. }
  10950. get depthWrite() {
  10951. return this._shaderValues.getBool(PBRMaterial.DEPTH_WRITE);
  10952. }
  10953. set depthWrite(value) {
  10954. this._shaderValues.setBool(PBRMaterial.DEPTH_WRITE, value);
  10955. }
  10956. get cull() {
  10957. return this._shaderValues.getInt(PBRMaterial.CULL);
  10958. }
  10959. set cull(value) {
  10960. this._shaderValues.setInt(PBRMaterial.CULL, value);
  10961. }
  10962. get blend() {
  10963. return this._shaderValues.getInt(PBRMaterial.BLEND);
  10964. }
  10965. set blend(value) {
  10966. this._shaderValues.setInt(PBRMaterial.BLEND, value);
  10967. }
  10968. get blendSrc() {
  10969. return this._shaderValues.getInt(PBRMaterial.BLEND_SRC);
  10970. }
  10971. set blendSrc(value) {
  10972. this._shaderValues.setInt(PBRMaterial.BLEND_SRC, value);
  10973. }
  10974. get blendDst() {
  10975. return this._shaderValues.getInt(PBRMaterial.BLEND_DST);
  10976. }
  10977. set blendDst(value) {
  10978. this._shaderValues.setInt(PBRMaterial.BLEND_DST, value);
  10979. }
  10980. get depthTest() {
  10981. return this._shaderValues.getInt(PBRMaterial.DEPTH_TEST);
  10982. }
  10983. set depthTest(value) {
  10984. this._shaderValues.setInt(PBRMaterial.DEPTH_TEST, value);
  10985. }
  10986. set renderMode(value) {
  10987. switch (value) {
  10988. case exports.PBRRenderMode.Opaque:
  10989. this.alphaTest = false;
  10990. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  10991. this.depthWrite = true;
  10992. this.cull = RenderState.CULL_BACK;
  10993. this.blend = RenderState.BLEND_DISABLE;
  10994. this.depthTest = RenderState.DEPTHTEST_LESS;
  10995. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND);
  10996. break;
  10997. case exports.PBRRenderMode.Cutout:
  10998. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  10999. this.alphaTest = true;
  11000. this.depthWrite = true;
  11001. this.cull = RenderState.CULL_BACK;
  11002. this.blend = RenderState.BLEND_DISABLE;
  11003. this.depthTest = RenderState.DEPTHTEST_LESS;
  11004. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND);
  11005. break;
  11006. case exports.PBRRenderMode.Fade:
  11007. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  11008. this.alphaTest = false;
  11009. this.depthWrite = false;
  11010. this.cull = RenderState.CULL_BACK;
  11011. this.blend = RenderState.BLEND_ENABLE_ALL;
  11012. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  11013. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  11014. this.depthTest = RenderState.DEPTHTEST_LESS;
  11015. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND);
  11016. break;
  11017. case exports.PBRRenderMode.Transparent:
  11018. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  11019. this.alphaTest = false;
  11020. this.depthWrite = false;
  11021. this.cull = RenderState.CULL_BACK;
  11022. this.blend = RenderState.BLEND_ENABLE_ALL;
  11023. this.blendSrc = RenderState.BLENDPARAM_ONE;
  11024. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  11025. this.depthTest = RenderState.DEPTHTEST_LESS;
  11026. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND);
  11027. break;
  11028. default:
  11029. throw new Error("PBRMaterial:unknown renderMode value.");
  11030. }
  11031. }
  11032. get enableReflection() {
  11033. return true;
  11034. }
  11035. set enableReflection(value) {
  11036. }
  11037. }
  11038. PBRMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  11039. PBRMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  11040. PBRMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  11041. PBRMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  11042. PBRMaterial.NORMALSCALE = Shader3D.propertyNameToID("u_NormalScale");
  11043. PBRMaterial.SMOOTHNESS = Shader3D.propertyNameToID("u_Smoothness");
  11044. PBRMaterial.SMOOTHNESSSCALE = Shader3D.propertyNameToID("u_SmoothnessScale");
  11045. PBRMaterial.OCCLUSIONTEXTURE = Shader3D.propertyNameToID("u_OcclusionTexture");
  11046. PBRMaterial.OCCLUSIONSTRENGTH = Shader3D.propertyNameToID("u_occlusionStrength");
  11047. PBRMaterial.PARALLAXTEXTURE = Shader3D.propertyNameToID("u_ParallaxTexture");
  11048. PBRMaterial.PARALLAXSCALE = Shader3D.propertyNameToID("u_ParallaxScale");
  11049. PBRMaterial.EMISSIONTEXTURE = Shader3D.propertyNameToID("u_EmissionTexture");
  11050. PBRMaterial.EMISSIONCOLOR = Shader3D.propertyNameToID("u_EmissionColor");
  11051. PBRMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  11052. PBRMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  11053. PBRMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  11054. PBRMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  11055. PBRMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  11056. PBRMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  11057. PBRMaterial.renderQuality = exports.PBRRenderQuality.High;
  11058. var PBRPS = "#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#define SETUP_BRDF_INPUT specularSetup\r\n\r\n#include \"Lighting.glsl\";\r\n#include \"PBRFSInput.glsl\";\r\n#include \"LayaPBRBRDF.glsl\";\r\n#include \"GlobalIllumination.glsl\";\r\n#include \"Shadow.glsl\"\r\n#include \"PBRCore.glsl\";\r\n\r\nvoid main()\r\n{\r\n\tfragmentForward();\r\n}";
  11059. var PBRVS = "#include \"PBRVSInput.glsl\";\r\n#include \"Lighting.glsl\";\r\n#include \"PBRVertex.glsl\";\r\n\r\nvoid main()\r\n{\r\n\tvertexForward();\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  11060. var PBRShadowCasterPS = "#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 \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
  11061. var PBRShadowCasterVS = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS = shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
  11062. class ShaderVariable {
  11063. constructor() {
  11064. this.textureID = -1;
  11065. }
  11066. }
  11067. class ShaderInstance extends Laya.Resource {
  11068. constructor(vs, ps, attributeMap, uniformMap, shaderPass) {
  11069. super();
  11070. this._stateParamsMap = [];
  11071. this._uploadMark = -1;
  11072. this._uploadRenderType = -1;
  11073. this._vs = vs;
  11074. this._ps = ps;
  11075. this._attributeMap = attributeMap;
  11076. this._uniformMap = uniformMap;
  11077. this._shaderPass = shaderPass;
  11078. this._create();
  11079. this.lock = true;
  11080. }
  11081. _create() {
  11082. var gl = Laya.LayaGL.instance;
  11083. this._program = gl.createProgram();
  11084. this._vshader = this._createShader(gl, this._vs, gl.VERTEX_SHADER);
  11085. this._pshader = this._createShader(gl, this._ps, gl.FRAGMENT_SHADER);
  11086. gl.attachShader(this._program, this._vshader);
  11087. gl.attachShader(this._program, this._pshader);
  11088. for (var k in this._attributeMap)
  11089. gl.bindAttribLocation(this._program, this._attributeMap[k], k);
  11090. gl.linkProgram(this._program);
  11091. if (!Laya.Render.isConchApp && Shader3D.debugMode && !gl.getProgramParameter(this._program, gl.LINK_STATUS))
  11092. throw gl.getProgramInfoLog(this._program);
  11093. var sceneParms = [];
  11094. var cameraParms = [];
  11095. var spriteParms = [];
  11096. var materialParms = [];
  11097. var customParms = [];
  11098. this._customUniformParamsMap = [];
  11099. var nUniformNum = gl.getProgramParameter(this._program, gl.ACTIVE_UNIFORMS);
  11100. Laya.WebGLContext.useProgram(gl, this._program);
  11101. this._curActTexIndex = 0;
  11102. var one, i, n;
  11103. for (i = 0; i < nUniformNum; i++) {
  11104. var uniformData = gl.getActiveUniform(this._program, i);
  11105. var uniName = uniformData.name;
  11106. one = new ShaderVariable();
  11107. one.location = gl.getUniformLocation(this._program, uniName);
  11108. if (uniName.indexOf('[0]') > 0) {
  11109. one.name = uniName = uniName.substr(0, uniName.length - 3);
  11110. one.isArray = true;
  11111. }
  11112. else {
  11113. one.name = uniName;
  11114. one.isArray = false;
  11115. }
  11116. one.type = uniformData.type;
  11117. this._addShaderUnifiormFun(one);
  11118. var uniformPeriod = this._uniformMap[uniName];
  11119. if (uniformPeriod != null) {
  11120. one.dataOffset = Shader3D.propertyNameToID(uniName);
  11121. switch (uniformPeriod) {
  11122. case Shader3D.PERIOD_CUSTOM:
  11123. customParms.push(one);
  11124. break;
  11125. case Shader3D.PERIOD_MATERIAL:
  11126. materialParms.push(one);
  11127. break;
  11128. case Shader3D.PERIOD_SPRITE:
  11129. spriteParms.push(one);
  11130. break;
  11131. case Shader3D.PERIOD_CAMERA:
  11132. cameraParms.push(one);
  11133. break;
  11134. case Shader3D.PERIOD_SCENE:
  11135. sceneParms.push(one);
  11136. break;
  11137. default:
  11138. throw new Error("Shader3D: period is unkonw.");
  11139. }
  11140. }
  11141. }
  11142. this._sceneUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(sceneParms.length * 4 * 5 + 4, 64, true);
  11143. for (i = 0, n = sceneParms.length; i < n; i++)
  11144. this._sceneUniformParamsMap.addShaderUniform(sceneParms[i]);
  11145. this._cameraUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(cameraParms.length * 4 * 5 + 4, 64, true);
  11146. for (i = 0, n = cameraParms.length; i < n; i++)
  11147. this._cameraUniformParamsMap.addShaderUniform(cameraParms[i]);
  11148. this._spriteUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(spriteParms.length * 4 * 5 + 4, 64, true);
  11149. for (i = 0, n = spriteParms.length; i < n; i++)
  11150. this._spriteUniformParamsMap.addShaderUniform(spriteParms[i]);
  11151. this._materialUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(materialParms.length * 4 * 5 + 4, 64, true);
  11152. for (i = 0, n = materialParms.length; i < n; i++)
  11153. this._materialUniformParamsMap.addShaderUniform(materialParms[i]);
  11154. this._customUniformParamsMap.length = customParms.length;
  11155. for (i = 0, n = customParms.length; i < n; i++) {
  11156. var custom = customParms[i];
  11157. this._customUniformParamsMap[custom.dataOffset] = custom;
  11158. }
  11159. var stateMap = this._shaderPass._stateMap;
  11160. for (var s in stateMap)
  11161. this._stateParamsMap[stateMap[s]] = Shader3D.propertyNameToID(s);
  11162. }
  11163. _getRenderState(shaderDatas, stateIndex) {
  11164. var stateID = this._stateParamsMap[stateIndex];
  11165. if (stateID == null)
  11166. return null;
  11167. else
  11168. return shaderDatas[stateID];
  11169. }
  11170. _disposeResource() {
  11171. Laya.LayaGL.instance.deleteShader(this._vshader);
  11172. Laya.LayaGL.instance.deleteShader(this._pshader);
  11173. Laya.LayaGL.instance.deleteProgram(this._program);
  11174. this._vshader = this._pshader = this._program = null;
  11175. this._setGPUMemory(0);
  11176. this._curActTexIndex = 0;
  11177. }
  11178. _addShaderUnifiormFun(one) {
  11179. var gl = Laya.LayaGL.instance;
  11180. one.caller = this;
  11181. var isArray = one.isArray;
  11182. switch (one.type) {
  11183. case gl.BOOL:
  11184. one.fun = this._uniform1i;
  11185. one.uploadedValue = new Array(1);
  11186. break;
  11187. case gl.INT:
  11188. one.fun = isArray ? this._uniform1iv : this._uniform1i;
  11189. one.uploadedValue = new Array(1);
  11190. break;
  11191. case gl.FLOAT:
  11192. one.fun = isArray ? this._uniform1fv : this._uniform1f;
  11193. one.uploadedValue = new Array(1);
  11194. break;
  11195. case gl.FLOAT_VEC2:
  11196. one.fun = isArray ? this._uniform_vec2v : this._uniform_vec2;
  11197. one.uploadedValue = new Array(2);
  11198. break;
  11199. case gl.FLOAT_VEC3:
  11200. one.fun = isArray ? this._uniform_vec3v : this._uniform_vec3;
  11201. one.uploadedValue = new Array(3);
  11202. break;
  11203. case gl.FLOAT_VEC4:
  11204. one.fun = isArray ? this._uniform_vec4v : this._uniform_vec4;
  11205. one.uploadedValue = new Array(4);
  11206. break;
  11207. case gl.FLOAT_MAT2:
  11208. one.fun = this._uniformMatrix2fv;
  11209. break;
  11210. case gl.FLOAT_MAT3:
  11211. one.fun = this._uniformMatrix3fv;
  11212. break;
  11213. case gl.FLOAT_MAT4:
  11214. one.fun = isArray ? this._uniformMatrix4fv : this._uniformMatrix4f;
  11215. break;
  11216. case gl.SAMPLER_2D:
  11217. case gl.SAMPLER_2D_SHADOW:
  11218. gl.uniform1i(one.location, this._curActTexIndex);
  11219. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  11220. one.fun = this._uniform_sampler2D;
  11221. break;
  11222. case 0x8b5f:
  11223. gl.uniform1i(one.location, this._curActTexIndex);
  11224. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  11225. one.fun = this._uniform_sampler3D;
  11226. break;
  11227. case gl.SAMPLER_CUBE:
  11228. gl.uniform1i(one.location, this._curActTexIndex);
  11229. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  11230. one.fun = this._uniform_samplerCube;
  11231. break;
  11232. default:
  11233. throw new Error("compile shader err!");
  11234. break;
  11235. }
  11236. }
  11237. _createShader(gl, str, type) {
  11238. var shader = gl.createShader(type);
  11239. gl.shaderSource(shader, str);
  11240. gl.compileShader(shader);
  11241. if (Shader3D.debugMode && !gl.getShaderParameter(shader, gl.COMPILE_STATUS))
  11242. throw gl.getShaderInfoLog(shader);
  11243. return shader;
  11244. }
  11245. _uniform1f(one, value) {
  11246. var uploadedValue = one.uploadedValue;
  11247. if (uploadedValue[0] !== value) {
  11248. Laya.LayaGL.instance.uniform1f(one.location, uploadedValue[0] = value);
  11249. return 1;
  11250. }
  11251. return 0;
  11252. }
  11253. _uniform1fv(one, value) {
  11254. if (value.length < 4) {
  11255. var uploadedValue = one.uploadedValue;
  11256. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  11257. Laya.LayaGL.instance.uniform1fv(one.location, value);
  11258. uploadedValue[0] = value[0];
  11259. uploadedValue[1] = value[1];
  11260. uploadedValue[2] = value[2];
  11261. uploadedValue[3] = value[3];
  11262. return 1;
  11263. }
  11264. return 0;
  11265. }
  11266. else {
  11267. Laya.LayaGL.instance.uniform1fv(one.location, value);
  11268. return 1;
  11269. }
  11270. }
  11271. _uniform_vec2(one, v) {
  11272. var uploadedValue = one.uploadedValue;
  11273. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y) {
  11274. Laya.LayaGL.instance.uniform2f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y);
  11275. return 1;
  11276. }
  11277. return 0;
  11278. }
  11279. _uniform_vec2v(one, value) {
  11280. if (value.length < 2) {
  11281. var uploadedValue = one.uploadedValue;
  11282. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  11283. Laya.LayaGL.instance.uniform2fv(one.location, value);
  11284. uploadedValue[0] = value[0];
  11285. uploadedValue[1] = value[1];
  11286. uploadedValue[2] = value[2];
  11287. uploadedValue[3] = value[3];
  11288. return 1;
  11289. }
  11290. return 0;
  11291. }
  11292. else {
  11293. Laya.LayaGL.instance.uniform2fv(one.location, value);
  11294. return 1;
  11295. }
  11296. }
  11297. _uniform_vec3(one, v) {
  11298. var uploadedValue = one.uploadedValue;
  11299. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y || uploadedValue[2] !== v.z) {
  11300. Laya.LayaGL.instance.uniform3f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y, uploadedValue[2] = v.z);
  11301. return 1;
  11302. }
  11303. return 0;
  11304. }
  11305. _uniform_vec3v(one, v) {
  11306. Laya.LayaGL.instance.uniform3fv(one.location, v);
  11307. return 1;
  11308. }
  11309. _uniform_vec4(one, v) {
  11310. var uploadedValue = one.uploadedValue;
  11311. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y || uploadedValue[2] !== v.z || uploadedValue[3] !== v.w) {
  11312. Laya.LayaGL.instance.uniform4f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y, uploadedValue[2] = v.z, uploadedValue[3] = v.w);
  11313. return 1;
  11314. }
  11315. return 0;
  11316. }
  11317. _uniform_vec4v(one, v) {
  11318. Laya.LayaGL.instance.uniform4fv(one.location, v);
  11319. return 1;
  11320. }
  11321. _uniformMatrix2fv(one, value) {
  11322. Laya.LayaGL.instance.uniformMatrix2fv(one.location, false, value);
  11323. return 1;
  11324. }
  11325. _uniformMatrix3fv(one, value) {
  11326. Laya.LayaGL.instance.uniformMatrix3fv(one.location, false, value);
  11327. return 1;
  11328. }
  11329. _uniformMatrix4f(one, m) {
  11330. var value = m.elements;
  11331. Laya.LayaGL.instance.uniformMatrix4fv(one.location, false, value);
  11332. return 1;
  11333. }
  11334. _uniformMatrix4fv(one, m) {
  11335. Laya.LayaGL.instance.uniformMatrix4fv(one.location, false, m);
  11336. return 1;
  11337. }
  11338. _uniform1i(one, value) {
  11339. var uploadedValue = one.uploadedValue;
  11340. if (uploadedValue[0] !== value) {
  11341. Laya.LayaGL.instance.uniform1i(one.location, uploadedValue[0] = value);
  11342. return 1;
  11343. }
  11344. return 0;
  11345. }
  11346. _uniform1iv(one, value) {
  11347. Laya.LayaGL.instance.uniform1iv(one.location, value);
  11348. return 1;
  11349. }
  11350. _uniform_ivec2(one, value) {
  11351. var uploadedValue = one.uploadedValue;
  11352. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1]) {
  11353. Laya.LayaGL.instance.uniform2i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1]);
  11354. return 1;
  11355. }
  11356. return 0;
  11357. }
  11358. _uniform_ivec2v(one, value) {
  11359. Laya.LayaGL.instance.uniform2iv(one.location, value);
  11360. return 1;
  11361. }
  11362. _uniform_vec3i(one, value) {
  11363. var uploadedValue = one.uploadedValue;
  11364. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2]) {
  11365. Laya.LayaGL.instance.uniform3i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1], uploadedValue[2] = value[2]);
  11366. return 1;
  11367. }
  11368. return 0;
  11369. }
  11370. _uniform_vec3vi(one, value) {
  11371. Laya.LayaGL.instance.uniform3iv(one.location, value);
  11372. return 1;
  11373. }
  11374. _uniform_vec4i(one, value) {
  11375. var uploadedValue = one.uploadedValue;
  11376. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  11377. Laya.LayaGL.instance.uniform4i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1], uploadedValue[2] = value[2], uploadedValue[3] = value[3]);
  11378. return 1;
  11379. }
  11380. return 0;
  11381. }
  11382. _uniform_vec4vi(one, value) {
  11383. Laya.LayaGL.instance.uniform4iv(one.location, value);
  11384. return 1;
  11385. }
  11386. _uniform_sampler2D(one, texture) {
  11387. var value = texture._getSource() || texture.defaulteTexture._getSource();
  11388. var gl = Laya.LayaGL.instance;
  11389. Laya.WebGLContext.activeTexture(gl, one.textureID);
  11390. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, value);
  11391. return 0;
  11392. }
  11393. _uniform_sampler3D(one, texture) {
  11394. var value = texture._getSource() || texture.defaulteTexture._getSource();
  11395. var gl = Laya.LayaGL.instance;
  11396. Laya.WebGLContext.activeTexture(gl, one.textureID);
  11397. Laya.WebGLContext.bindTexture(gl, WebGL2RenderingContext.TEXTURE_3D, value);
  11398. return 0;
  11399. }
  11400. _uniform_samplerCube(one, texture) {
  11401. var value = texture._getSource() || texture.defaulteTexture._getSource();
  11402. var gl = Laya.LayaGL.instance;
  11403. Laya.WebGLContext.activeTexture(gl, one.textureID);
  11404. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_CUBE_MAP, value);
  11405. return 0;
  11406. }
  11407. bind() {
  11408. return Laya.WebGLContext.useProgram(Laya.LayaGL.instance, this._program);
  11409. }
  11410. uploadUniforms(shaderUniform, shaderDatas, uploadUnTexture) {
  11411. Laya.Stat.shaderCall += Laya.LayaGLRunner.uploadShaderUniforms(Laya.LayaGL.instance, shaderUniform, shaderDatas, uploadUnTexture);
  11412. }
  11413. uploadRenderStateBlendDepth(shaderDatas) {
  11414. var gl = Laya.LayaGL.instance;
  11415. var renderState = this._shaderPass.renderState;
  11416. var datas = shaderDatas.getData();
  11417. var depthWrite = this._getRenderState(datas, Shader3D.RENDER_STATE_DEPTH_WRITE);
  11418. var depthTest = this._getRenderState(datas, Shader3D.RENDER_STATE_DEPTH_TEST);
  11419. var blend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND);
  11420. depthWrite == null && (depthWrite = renderState.depthWrite);
  11421. depthTest == null && (depthTest = renderState.depthTest);
  11422. blend == null && (blend = renderState.blend);
  11423. Laya.WebGLContext.setDepthMask(gl, depthWrite);
  11424. if (depthTest === RenderState.DEPTHTEST_OFF)
  11425. Laya.WebGLContext.setDepthTest(gl, false);
  11426. else {
  11427. Laya.WebGLContext.setDepthTest(gl, true);
  11428. Laya.WebGLContext.setDepthFunc(gl, depthTest);
  11429. }
  11430. switch (blend) {
  11431. case RenderState.BLEND_DISABLE:
  11432. Laya.WebGLContext.setBlend(gl, false);
  11433. break;
  11434. case RenderState.BLEND_ENABLE_ALL:
  11435. var blendEquation = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION);
  11436. var srcBlend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC);
  11437. var dstBlend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST);
  11438. blendEquation == null && (blendEquation = renderState.blendEquation);
  11439. srcBlend == null && (srcBlend = renderState.srcBlend);
  11440. dstBlend == null && (dstBlend = renderState.dstBlend);
  11441. Laya.WebGLContext.setBlend(gl, true);
  11442. Laya.WebGLContext.setBlendEquation(gl, blendEquation);
  11443. Laya.WebGLContext.setBlendFunc(gl, srcBlend, dstBlend);
  11444. break;
  11445. case RenderState.BLEND_ENABLE_SEPERATE:
  11446. var blendEquationRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION_RGB);
  11447. var blendEquationAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION_ALPHA);
  11448. var srcRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC_RGB);
  11449. var dstRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST_RGB);
  11450. var srcAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC_ALPHA);
  11451. var dstAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST_ALPHA);
  11452. blendEquationRGB == null && (blendEquationRGB = renderState.blendEquationRGB);
  11453. blendEquationAlpha == null && (blendEquationAlpha = renderState.blendEquationAlpha);
  11454. srcRGB == null && (srcRGB = renderState.srcBlendRGB);
  11455. dstRGB == null && (dstRGB = renderState.dstBlendRGB);
  11456. srcAlpha == null && (srcAlpha = renderState.srcBlendAlpha);
  11457. dstAlpha == null && (dstAlpha = renderState.dstBlendAlpha);
  11458. Laya.WebGLContext.setBlend(gl, true);
  11459. Laya.WebGLContext.setBlendEquationSeparate(gl, blendEquationRGB, blendEquationAlpha);
  11460. Laya.WebGLContext.setBlendFuncSeperate(gl, srcRGB, dstRGB, srcAlpha, dstAlpha);
  11461. break;
  11462. }
  11463. }
  11464. uploadRenderStateFrontFace(shaderDatas, isTarget, invertFront) {
  11465. var gl = Laya.LayaGL.instance;
  11466. var renderState = this._shaderPass.renderState;
  11467. var datas = shaderDatas.getData();
  11468. var cull = this._getRenderState(datas, Shader3D.RENDER_STATE_CULL);
  11469. cull == null && (cull = renderState.cull);
  11470. var forntFace;
  11471. switch (cull) {
  11472. case RenderState.CULL_NONE:
  11473. Laya.WebGLContext.setCullFace(gl, false);
  11474. break;
  11475. case RenderState.CULL_FRONT:
  11476. Laya.WebGLContext.setCullFace(gl, true);
  11477. if (isTarget) {
  11478. if (invertFront)
  11479. forntFace = gl.CCW;
  11480. else
  11481. forntFace = gl.CW;
  11482. }
  11483. else {
  11484. if (invertFront)
  11485. forntFace = gl.CW;
  11486. else
  11487. forntFace = gl.CCW;
  11488. }
  11489. Laya.WebGLContext.setFrontFace(gl, forntFace);
  11490. break;
  11491. case RenderState.CULL_BACK:
  11492. Laya.WebGLContext.setCullFace(gl, true);
  11493. if (isTarget) {
  11494. if (invertFront)
  11495. forntFace = gl.CW;
  11496. else
  11497. forntFace = gl.CCW;
  11498. }
  11499. else {
  11500. if (invertFront)
  11501. forntFace = gl.CCW;
  11502. else
  11503. forntFace = gl.CW;
  11504. }
  11505. Laya.WebGLContext.setFrontFace(gl, forntFace);
  11506. break;
  11507. }
  11508. }
  11509. uploadCustomUniform(index, data) {
  11510. Laya.Stat.shaderCall += Laya.LayaGLRunner.uploadCustomUniform(Laya.LayaGL.instance, this._customUniformParamsMap, index, data);
  11511. }
  11512. _uniformMatrix2fvForNative(one, value) {
  11513. Laya.LayaGL.instance.uniformMatrix2fvEx(one.location, false, value);
  11514. return 1;
  11515. }
  11516. _uniformMatrix3fvForNative(one, value) {
  11517. Laya.LayaGL.instance.uniformMatrix3fvEx(one.location, false, value);
  11518. return 1;
  11519. }
  11520. _uniformMatrix4fvForNative(one, m) {
  11521. Laya.LayaGL.instance.uniformMatrix4fvEx(one.location, false, m);
  11522. return 1;
  11523. }
  11524. }
  11525. class SimpleSingletonList extends SingletonList {
  11526. constructor() {
  11527. super();
  11528. }
  11529. add(element) {
  11530. var index = element._getIndexInList();
  11531. if (index !== -1)
  11532. throw "SimpleSingletonList:" + element + " has in SingletonList.";
  11533. this._add(element);
  11534. element._setIndexInList(this.length++);
  11535. }
  11536. remove(element) {
  11537. var index = element._getIndexInList();
  11538. this.length--;
  11539. if (index !== this.length) {
  11540. var end = this.elements[this.length];
  11541. this.elements[index] = end;
  11542. end._setIndexInList(index);
  11543. }
  11544. element._setIndexInList(-1);
  11545. }
  11546. clear() {
  11547. var elements = this.elements;
  11548. for (var i = 0, n = this.length; i < n; i++)
  11549. elements[i]._setIndexInList(-1);
  11550. this.length = 0;
  11551. }
  11552. }
  11553. class Color {
  11554. constructor(r = 1, g = 1, b = 1, a = 1) {
  11555. this.r = r;
  11556. this.g = g;
  11557. this.b = b;
  11558. this.a = a;
  11559. }
  11560. static gammaToLinearSpace(value) {
  11561. if (value <= 0.04045)
  11562. return value / 12.92;
  11563. else if (value < 1.0)
  11564. return Math.pow((value + 0.055) / 1.055, 2.4);
  11565. else
  11566. return Math.pow(value, 2.4);
  11567. }
  11568. static linearToGammaSpace(value) {
  11569. if (value <= 0.0)
  11570. return 0.0;
  11571. else if (value <= 0.0031308)
  11572. return 12.92 * value;
  11573. else if (value <= 1.0)
  11574. return 1.055 * Math.pow(value, 0.41666) - 0.055;
  11575. else
  11576. return Math.pow(value, 0.41666);
  11577. }
  11578. toLinear(out) {
  11579. out.r = Color.gammaToLinearSpace(this.r);
  11580. out.g = Color.gammaToLinearSpace(this.g);
  11581. out.b = Color.gammaToLinearSpace(this.b);
  11582. }
  11583. toGamma(out) {
  11584. out.r = Color.linearToGammaSpace(this.r);
  11585. out.g = Color.linearToGammaSpace(this.g);
  11586. out.b = Color.linearToGammaSpace(this.b);
  11587. }
  11588. cloneTo(destObject) {
  11589. var destColor = destObject;
  11590. destColor.r = this.r;
  11591. destColor.g = this.g;
  11592. destColor.b = this.b;
  11593. destColor.a = this.a;
  11594. }
  11595. clone() {
  11596. var dest = new Color();
  11597. this.cloneTo(dest);
  11598. return dest;
  11599. }
  11600. forNativeElement() {
  11601. }
  11602. }
  11603. Color.RED = new Color(1, 0, 0, 1);
  11604. Color.GREEN = new Color(0, 1, 0, 1);
  11605. Color.BLUE = new Color(0, 0, 1, 1);
  11606. Color.CYAN = new Color(0, 1, 1, 1);
  11607. Color.YELLOW = new Color(1, 0.92, 0.016, 1);
  11608. Color.MAGENTA = new Color(1, 0, 1, 1);
  11609. Color.GRAY = new Color(0.5, 0.5, 0.5, 1);
  11610. Color.WHITE = new Color(1, 1, 1, 1);
  11611. Color.BLACK = new Color(0, 0, 0, 1);
  11612. class CameraCullInfo {
  11613. }
  11614. class ShadowCullInfo {
  11615. }
  11616. class FrustumCulling {
  11617. static __init__() {
  11618. if (Laya.Render.supportWebGLPlusCulling) {
  11619. FrustumCulling._cullingBufferLength = 0;
  11620. FrustumCulling._cullingBuffer = new Float32Array(4096);
  11621. }
  11622. }
  11623. static _drawTraversalCullingBound(renderList, debugTool) {
  11624. var renders = renderList.elements;
  11625. for (var i = 0, n = renderList.length; i < n; i++) {
  11626. var color = FrustumCulling._tempColor0;
  11627. color.r = 0;
  11628. color.g = 1;
  11629. color.b = 0;
  11630. color.a = 1;
  11631. Utils3D._drawBound(debugTool, renders[i].bounds._getBoundBox(), color);
  11632. }
  11633. }
  11634. static _traversalCulling(cameraCullInfo, scene, context, renderList, customShader, replacementTag, isShadowCasterCull) {
  11635. var renders = renderList.elements;
  11636. var boundFrustum = cameraCullInfo.boundFrustum;
  11637. var camPos = cameraCullInfo.position;
  11638. var cullMask = cameraCullInfo.cullingMask;
  11639. var loopCount = Laya.Stat.loopCount;
  11640. for (var i = 0, n = renderList.length; i < n; i++) {
  11641. var render = renders[i];
  11642. var canPass;
  11643. if (isShadowCasterCull)
  11644. canPass = render._castShadow && render._enable;
  11645. else
  11646. canPass = ((Math.pow(2, render._owner._layer) & cullMask) != 0) && render._enable;
  11647. if (canPass) {
  11648. Laya.Stat.frustumCulling++;
  11649. if (!cameraCullInfo.useOcclusionCulling || render._needRender(boundFrustum, context)) {
  11650. render._renderMark = loopCount;
  11651. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  11652. var elements = render._renderElements;
  11653. for (var j = 0, m = elements.length; j < m; j++)
  11654. elements[j]._update(scene, context, customShader, replacementTag);
  11655. }
  11656. }
  11657. }
  11658. }
  11659. static renderObjectCulling(cameraCullInfo, scene, context, customShader, replacementTag, isShadowCasterCull) {
  11660. var opaqueQueue = scene._opaqueQueue;
  11661. var transparentQueue = scene._transparentQueue;
  11662. var renderList = scene._renders;
  11663. scene._clearRenderQueue();
  11664. var octree = scene._octree;
  11665. if (octree) {
  11666. octree.updateMotionObjects();
  11667. octree.shrinkRootIfPossible();
  11668. octree.getCollidingWithFrustum(cameraCullInfo, context, customShader, replacementTag, isShadowCasterCull);
  11669. }
  11670. FrustumCulling._traversalCulling(cameraCullInfo, scene, context, renderList, customShader, replacementTag, isShadowCasterCull);
  11671. if (FrustumCulling.debugFrustumCulling) {
  11672. var debugTool = scene._debugTool;
  11673. debugTool.clear();
  11674. if (octree) {
  11675. octree.drawAllBounds(debugTool);
  11676. octree.drawAllObjects(debugTool);
  11677. }
  11678. FrustumCulling._drawTraversalCullingBound(renderList, debugTool);
  11679. }
  11680. var count = opaqueQueue.elements.length;
  11681. (count > 0) && (opaqueQueue._quickSort(0, count - 1));
  11682. count = transparentQueue.elements.length;
  11683. (count > 0) && (transparentQueue._quickSort(0, count - 1));
  11684. }
  11685. static cullingShadow(cullInfo, scene, context) {
  11686. var renderList = scene._renders;
  11687. scene._clearRenderQueue();
  11688. var opaqueQueue = scene._opaqueQueue;
  11689. var position = cullInfo.position;
  11690. var cullPlaneCount = cullInfo.cullPlaneCount;
  11691. var cullPlanes = cullInfo.cullPlanes;
  11692. var cullSphere = cullInfo.cullSphere;
  11693. var direction = cullInfo.direction;
  11694. var renders = renderList.elements;
  11695. var loopCount = Laya.Stat.loopCount;
  11696. for (var i = 0, n = renderList.length; i < n; i++) {
  11697. var render = renders[i];
  11698. var canPass = render._castShadow && render._enable;
  11699. if (canPass) {
  11700. Laya.Stat.frustumCulling++;
  11701. var bounds = render.bounds;
  11702. var min = bounds.getMin();
  11703. var max = bounds.getMax();
  11704. var minX = min.x;
  11705. var minY = min.y;
  11706. var minZ = min.z;
  11707. var maxX = max.x;
  11708. var maxY = max.y;
  11709. var maxZ = max.z;
  11710. var pass = true;
  11711. for (var j = 0; j < cullPlaneCount; j++) {
  11712. var plane = cullPlanes[j];
  11713. var normal = plane.normal;
  11714. if (plane.distance + (normal.x * (normal.x < 0.0 ? minX : maxX)) + (normal.y * (normal.y < 0.0 ? minY : maxY)) + (normal.z * (normal.z < 0.0 ? minZ : maxZ)) < 0.0) {
  11715. pass = false;
  11716. break;
  11717. }
  11718. }
  11719. if (pass) {
  11720. render._renderMark = loopCount;
  11721. render._distanceForSort = Vector3.distance(bounds.getCenter(), position);
  11722. var elements = render._renderElements;
  11723. for (var j = 0, m = elements.length; j < m; j++)
  11724. elements[j]._update(scene, context, null, null);
  11725. }
  11726. }
  11727. }
  11728. return opaqueQueue.elements.length > 0 ? true : false;
  11729. }
  11730. static cullingSpotShadow(cameraCullInfo, scene, context) {
  11731. var renderList = scene._renders;
  11732. scene._clearRenderQueue();
  11733. var opaqueQueue = scene._opaqueQueue;
  11734. var renders = renderList.elements;
  11735. var loopCount = Laya.Stat.loopCount;
  11736. for (var i = 0, n = renderList.length; i < n; i++) {
  11737. var render = renders[i];
  11738. var canPass = render._castShadow && render._enable;
  11739. if (canPass) {
  11740. if (render._needRender(cameraCullInfo.boundFrustum, context)) {
  11741. var bounds = render.bounds;
  11742. render._renderMark = loopCount;
  11743. render._distanceForSort = Vector3.distance(bounds.getCenter(), cameraCullInfo.position);
  11744. var elements = render._renderElements;
  11745. for (var j = 0, m = elements.length; j < m; j++)
  11746. elements[j]._update(scene, context, null, null);
  11747. }
  11748. }
  11749. }
  11750. return opaqueQueue.elements.length > 0 ? true : false;
  11751. }
  11752. static renderObjectCullingNative(camera, scene, context, renderList, customShader, replacementTag) {
  11753. var i, j, m;
  11754. var opaqueQueue = scene._opaqueQueue;
  11755. var transparentQueue = scene._transparentQueue;
  11756. scene._clearRenderQueue();
  11757. var validCount = renderList.length;
  11758. var renders = renderList.elements;
  11759. for (i = 0; i < validCount; i++) {
  11760. renders[i].bounds;
  11761. renders[i]._updateForNative && renders[i]._updateForNative(context);
  11762. }
  11763. var boundFrustum = camera.boundFrustum;
  11764. FrustumCulling.cullingNative(camera._boundFrustumBuffer, FrustumCulling._cullingBuffer, scene._cullingBufferIndices, validCount, scene._cullingBufferResult);
  11765. var loopCount = Laya.Stat.loopCount;
  11766. var camPos = context.camera._transform.position;
  11767. for (i = 0; i < validCount; i++) {
  11768. var render = renders[i];
  11769. if (!camera.useOcclusionCulling || (camera._isLayerVisible(render._owner._layer) && render._enable && scene._cullingBufferResult[i])) {
  11770. render._renderMark = loopCount;
  11771. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  11772. var elements = render._renderElements;
  11773. for (j = 0, m = elements.length; j < m; j++) {
  11774. var element = elements[j];
  11775. element._update(scene, context, customShader, replacementTag);
  11776. }
  11777. }
  11778. }
  11779. var count = opaqueQueue.elements.length;
  11780. (count > 0) && (opaqueQueue._quickSort(0, count - 1));
  11781. count = transparentQueue.elements.length;
  11782. (count > 0) && (transparentQueue._quickSort(0, count - 1));
  11783. }
  11784. static cullingNative(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult) {
  11785. return Laya.LayaGL.instance.culling(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult);
  11786. }
  11787. }
  11788. FrustumCulling._tempColor0 = new Color();
  11789. FrustumCulling._tempVector0 = new Vector3();
  11790. FrustumCulling._cameraCullInfo = new CameraCullInfo();
  11791. FrustumCulling._shadowCullInfo = new ShadowCullInfo();
  11792. FrustumCulling.debugFrustumCulling = false;
  11793. class LightBound {
  11794. }
  11795. class ClusterData {
  11796. constructor() {
  11797. this.updateMark = -1;
  11798. this.pointLightCount = 0;
  11799. this.spotLightCount = 0;
  11800. this.indices = [];
  11801. }
  11802. }
  11803. class Cluster {
  11804. constructor(xSlices, ySlices, zSlices, maxLightsPerClusterAverage) {
  11805. this._updateMark = 0;
  11806. this._depthSliceParam = new Vector2();
  11807. this._xSlices = xSlices;
  11808. this._ySlices = ySlices;
  11809. this._zSlices = zSlices;
  11810. var clusterTexWidth = xSlices * ySlices;
  11811. var clisterTexHeight = zSlices * (1 + Math.ceil(maxLightsPerClusterAverage / 4));
  11812. this._clusterTexture = Utils3D._createFloatTextureBuffer(clusterTexWidth, clisterTexHeight);
  11813. this._clusterTexture.lock = true;
  11814. this._clusterPixels = new Float32Array(clusterTexWidth * clisterTexHeight * 4);
  11815. var clusterDatas = new Array(this._zSlices);
  11816. for (var z = 0; z < this._zSlices; z++) {
  11817. clusterDatas[z] = new Array(this._ySlices);
  11818. for (var y = 0; y < this._ySlices; y++) {
  11819. clusterDatas[z][y] = new Array(this._xSlices);
  11820. for (var x = 0; x < this._xSlices; x++)
  11821. clusterDatas[z][y][x] = new ClusterData();
  11822. }
  11823. }
  11824. this._clusterDatas = clusterDatas;
  11825. }
  11826. _insertSpotLightSphere(origin, forward, size, angle, testSphere) {
  11827. var V = Cluster._tempVector35;
  11828. V.x = testSphere.x - origin.x;
  11829. V.y = testSphere.y - origin.y;
  11830. V.z = testSphere.z - origin.z;
  11831. var VlenSq = Vector3.dot(V, V);
  11832. var sphereRadius = testSphere.w;
  11833. var rangeCull = VlenSq > sphereRadius * sphereRadius;
  11834. if (!rangeCull)
  11835. return false;
  11836. var V1len = Vector3.dot(V, forward);
  11837. var distanceClosestPoint = Math.cos(angle) * Math.sqrt(VlenSq - V1len * V1len) - V1len * Math.sin(angle);
  11838. var angleCull = distanceClosestPoint > sphereRadius;
  11839. var frontCull = V1len > sphereRadius + size;
  11840. var backCull = V1len < -sphereRadius;
  11841. return !(angleCull || frontCull || backCull);
  11842. }
  11843. _placePointLightToClusters(lightIndex, lightBound) {
  11844. var clusterDatas = this._clusterDatas;
  11845. var updateMark = this._updateMark;
  11846. for (var z = lightBound.zMin, zEnd = lightBound.zMax; z < zEnd; z++) {
  11847. for (var y = lightBound.yMin, yEnd = lightBound.yMax; y < yEnd; y++) {
  11848. for (var x = lightBound.xMin, xEnd = lightBound.xMax; x < xEnd; x++) {
  11849. var data = clusterDatas[z][y][x];
  11850. if (data.updateMark != updateMark) {
  11851. data.pointLightCount = 0;
  11852. data.spotLightCount = 0;
  11853. data.updateMark = updateMark;
  11854. }
  11855. var indices = data.indices;
  11856. var lightCount = data.pointLightCount++;
  11857. if (lightCount < indices.length)
  11858. indices[lightCount] = lightIndex;
  11859. else
  11860. indices.push(lightIndex);
  11861. }
  11862. }
  11863. }
  11864. }
  11865. _placeSpotLightToClusters(lightIndex, lightBound) {
  11866. var clusterDatas = this._clusterDatas;
  11867. var updateMark = this._updateMark;
  11868. for (var z = lightBound.zMin, zEnd = lightBound.zMax; z < zEnd; z++) {
  11869. for (var y = lightBound.yMin, yEnd = lightBound.yMax; y < yEnd; y++) {
  11870. for (var x = lightBound.xMin, xEnd = lightBound.xMax; x < xEnd; x++) {
  11871. var data = clusterDatas[z][y][x];
  11872. if (data.updateMark != updateMark) {
  11873. data.pointLightCount = 0;
  11874. data.spotLightCount = 0;
  11875. data.updateMark = updateMark;
  11876. }
  11877. var indices = data.indices;
  11878. var lightCount = data.pointLightCount + data.spotLightCount++;
  11879. if (lightCount < indices.length)
  11880. indices[lightCount] = lightIndex;
  11881. else
  11882. indices.push(lightIndex);
  11883. }
  11884. }
  11885. }
  11886. }
  11887. _insertConePlane(origin, forward, radius, halfAngle, pNor) {
  11888. var V1 = Cluster._tempVector36;
  11889. var V2 = Cluster._tempVector37;
  11890. Vector3.cross(pNor, forward, V1);
  11891. Vector3.cross(V1, forward, V2);
  11892. Vector3.normalize(V2, V2);
  11893. var tanR = radius * Math.tan(halfAngle);
  11894. var capRimX = origin.x + radius * forward.x + tanR * V2.x;
  11895. var capRimY = origin.y + radius * forward.y + tanR * V2.y;
  11896. var capRimZ = origin.z + radius * forward.z + tanR * V2.z;
  11897. return capRimX * pNor.x + capRimY * pNor.y + capRimZ * pNor.z <= 0 || origin.x * pNor.x + origin.y * pNor.y + origin.z * pNor.z <= 0;
  11898. }
  11899. _shrinkSphereLightZPerspective(near, far, lightviewPos, radius, lightBound) {
  11900. var lvZ = lightviewPos.z;
  11901. var minZ = lvZ - radius;
  11902. var maxZ = lvZ + radius;
  11903. if ((minZ > far) || (maxZ <= near))
  11904. return false;
  11905. var depthSliceParam = this._depthSliceParam;
  11906. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  11907. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  11908. return true;
  11909. }
  11910. _shrinkSpotLightZPerspective(near, far, viewLightPos, viewConeCap, radius, halfAngle, lightBound) {
  11911. var pbX = viewConeCap.x, pbY = viewConeCap.y, pbZ = viewConeCap.z;
  11912. var rb = Math.tan(halfAngle) * radius;
  11913. var paX = viewLightPos.x, paY = viewLightPos.y, paZ = viewLightPos.z;
  11914. var aX = pbX - paX, aY = pbY - paY, aZ = pbZ - paZ;
  11915. var dotA = aX * aX + aY * aY + aZ * aZ;
  11916. var eZ = Math.sqrt(1.0 - aZ * aZ / dotA);
  11917. var minZ = Math.max(Math.min(paZ, pbZ - eZ * rb), viewLightPos.z - radius);
  11918. var maxZ = Math.min(Math.max(paZ, pbZ + eZ * rb), viewLightPos.z + radius);
  11919. if ((minZ > far) || (maxZ <= near))
  11920. return false;
  11921. var depthSliceParam = this._depthSliceParam;
  11922. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  11923. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  11924. return true;
  11925. }
  11926. _shrinkSphereLightByBoundOrth(halfX, halfY, near, far, lightviewPos, radius, lightBound) {
  11927. var lvZ = lightviewPos.z;
  11928. var minZ = lvZ - radius, maxZ = lvZ + radius;
  11929. if ((minZ > far) || (maxZ <= near))
  11930. return false;
  11931. var lvX = lightviewPos.x;
  11932. var minX = lvX - radius, maxX = lvX + radius;
  11933. if ((minX > halfX) || (maxX <= -halfX))
  11934. return false;
  11935. var lvY = lightviewPos.y;
  11936. var minY = lvY - radius, maxY = lvY + radius;
  11937. if ((minY > halfY) || (maxY <= -halfY))
  11938. return false;
  11939. var xSlices = this._xSlices, ySlices = this._ySlices;
  11940. var depthSliceParam = this._depthSliceParam;
  11941. var xStride = halfX * 2 / xSlices, yStride = halfY * 2 / ySlices;
  11942. lightBound.xMin = Math.max(Math.floor((minX + halfX) / xStride), 0);
  11943. lightBound.xMax = Math.min(Math.ceil((maxX + halfX) / xStride), xSlices);
  11944. lightBound.yMin = Math.max(Math.floor((halfY - maxY) / yStride), 0);
  11945. lightBound.yMax = Math.min(Math.ceil((halfY - minY) / yStride), ySlices);
  11946. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  11947. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  11948. return true;
  11949. }
  11950. _shrinkSpotLightByBoundOrth(halfX, halfY, near, far, viewLightPos, viewConeCap, radius, halfAngle, lightBound) {
  11951. var pbX = viewConeCap.x, pbY = viewConeCap.y, pbZ = viewConeCap.z;
  11952. var rb = Math.tan(halfAngle) * radius;
  11953. var paX = viewLightPos.x, paY = viewLightPos.y, paZ = viewLightPos.z;
  11954. var aX = pbX - paX, aY = pbY - paY, aZ = pbZ - paZ;
  11955. var dotA = aX * aX + aY * aY + aZ * aZ;
  11956. var eZ = Math.sqrt(1.0 - aZ * aZ / dotA);
  11957. var minZ = Math.max(Math.min(paZ, pbZ - eZ * rb), viewLightPos.z - radius);
  11958. var maxZ = Math.min(Math.max(paZ, pbZ + eZ * rb), viewLightPos.z + radius);
  11959. if ((minZ > far) || (maxZ <= near))
  11960. return false;
  11961. var eX = Math.sqrt(1.0 - aX * aX / dotA);
  11962. var minX = Math.max(Math.min(paX, pbX - eX * rb), viewLightPos.x - radius);
  11963. var maxX = Math.min(Math.max(paX, pbX + eX * rb), viewLightPos.x + radius);
  11964. if ((minX > halfX) || (maxX <= -halfX))
  11965. return false;
  11966. var eY = Math.sqrt(1.0 - aY * aY / dotA);
  11967. var minY = Math.max(Math.min(paY, pbY - eY * rb), viewLightPos.y - radius);
  11968. var maxY = Math.min(Math.max(paY, pbY + eY * rb), viewLightPos.y + radius);
  11969. if ((minY > halfY) || (maxY <= -halfY))
  11970. return false;
  11971. var xSlices = this._xSlices, ySlices = this._ySlices;
  11972. var depthSliceParam = this._depthSliceParam;
  11973. var xStride = halfX * 2 / xSlices, yStride = halfY * 2 / ySlices;
  11974. lightBound.xMin = Math.max(Math.floor((minX + halfX) / xStride), 0);
  11975. lightBound.xMax = Math.min(Math.ceil((maxX + halfX) / xStride), xSlices);
  11976. lightBound.yMin = Math.max(Math.floor((halfY - maxY) / yStride), 0);
  11977. lightBound.yMax = Math.min(Math.ceil((halfY - minY) / yStride), ySlices);
  11978. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  11979. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  11980. return true;
  11981. }
  11982. _shrinkXYByRadiusPerspective(lightviewPos, radius, lightBound, xPlanes, yPlanes) {
  11983. var xMin, yMin;
  11984. var xMax, yMax;
  11985. var lvX = lightviewPos.x, lvY = lightviewPos.y, lvZ = lightviewPos.z;
  11986. var i;
  11987. var n = this._ySlices + 1;
  11988. for (i = 0; i < n; i++) {
  11989. var plane = yPlanes[i];
  11990. if (lvY * plane.y + lvZ * plane.z < radius) {
  11991. yMin = Math.max(0, i - 1);
  11992. break;
  11993. }
  11994. }
  11995. if (i == n)
  11996. return false;
  11997. yMax = this._ySlices;
  11998. for (i = yMin + 1; i < n; i++) {
  11999. var plane = yPlanes[i];
  12000. if (lvY * plane.y + lvZ * plane.z <= -radius) {
  12001. yMax = Math.max(0, i);
  12002. break;
  12003. }
  12004. }
  12005. n = this._xSlices + 1;
  12006. for (i = 0; i < n; i++) {
  12007. var plane = xPlanes[i];
  12008. if (lvX * plane.x + lvZ * plane.z < radius) {
  12009. xMin = Math.max(0, i - 1);
  12010. break;
  12011. }
  12012. }
  12013. xMax = this._xSlices;
  12014. for (i = xMin + 1; i < n; i++) {
  12015. var plane = xPlanes[i];
  12016. if (lvX * plane.x + lvZ * plane.z <= -radius) {
  12017. xMax = Math.max(0, i);
  12018. break;
  12019. }
  12020. }
  12021. lightBound.xMin = xMin;
  12022. lightBound.xMax = xMax;
  12023. lightBound.yMin = yMin;
  12024. lightBound.yMax = yMax;
  12025. return true;
  12026. }
  12027. _shrinkSpotXYByConePerspective(lightviewPos, viewForward, radius, halfAngle, lightBound, xPlanes, yPlanes) {
  12028. var xMin, yMin;
  12029. var xMax, yMax;
  12030. var normal = Cluster._tempVector32;
  12031. var n = lightBound.yMax + 1;
  12032. for (var i = lightBound.yMin + 1; i < n; i++) {
  12033. if (this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, yPlanes[i])) {
  12034. yMin = Math.max(0, i - 1);
  12035. break;
  12036. }
  12037. }
  12038. yMax = lightBound.yMax;
  12039. for (var i = yMin + 1; i < n; i++) {
  12040. var plane = yPlanes[i];
  12041. normal.setValue(0, -plane.y, -plane.z);
  12042. if (!this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, normal)) {
  12043. yMax = Math.max(0, i);
  12044. break;
  12045. }
  12046. }
  12047. n = lightBound.xMax + 1;
  12048. for (var i = lightBound.xMin + 1; i < n; i++) {
  12049. if (this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, xPlanes[i])) {
  12050. xMin = Math.max(0, i - 1);
  12051. break;
  12052. }
  12053. }
  12054. xMax = lightBound.xMax;
  12055. for (var i = xMin + 1; i < n; i++) {
  12056. var plane = xPlanes[i];
  12057. normal.setValue(-plane.x, 0, -plane.z);
  12058. if (!this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, normal)) {
  12059. xMax = Math.max(0, i);
  12060. break;
  12061. }
  12062. }
  12063. lightBound.xMin = xMin;
  12064. lightBound.xMax = xMax;
  12065. lightBound.yMin = yMin;
  12066. lightBound.yMax = yMax;
  12067. }
  12068. _updatePointLightPerspective(near, far, viewMat, pointLight, lightIndex, xPlanes, yPlanes) {
  12069. var lightBound = Cluster._tempLightBound;
  12070. var lightviewPos = Cluster._tempVector30;
  12071. Vector3.transformV3ToV3(pointLight._transform.position, viewMat, lightviewPos);
  12072. lightviewPos.z *= -1;
  12073. if (!this._shrinkSphereLightZPerspective(near, far, lightviewPos, pointLight.range, lightBound))
  12074. return;
  12075. if (!this._shrinkXYByRadiusPerspective(lightviewPos, pointLight.range, lightBound, xPlanes, yPlanes))
  12076. return;
  12077. this._placePointLightToClusters(lightIndex, lightBound);
  12078. }
  12079. _updateSpotLightPerspective(near, far, viewMat, spotLight, lightIndex, xPlanes, yPlanes) {
  12080. var lightBound = Cluster._tempLightBound;
  12081. var viewPos = Cluster._tempVector30;
  12082. var forward = Cluster._tempVector31;
  12083. var viewConeCap = Cluster._tempVector34;
  12084. var position = spotLight._transform.position;
  12085. var range = spotLight.range;
  12086. spotLight._transform.worldMatrix.getForward(forward);
  12087. Vector3.normalize(forward, forward);
  12088. Vector3.scale(forward, range, viewConeCap);
  12089. Vector3.add(position, viewConeCap, viewConeCap);
  12090. Vector3.transformV3ToV3(position, viewMat, viewPos);
  12091. Vector3.transformV3ToV3(viewConeCap, viewMat, viewConeCap);
  12092. viewPos.z *= -1;
  12093. viewConeCap.z *= -1;
  12094. var halfAngle = (spotLight.spotAngle / 2) * Math.PI / 180;
  12095. if (!this._shrinkSpotLightZPerspective(near, far, viewPos, viewConeCap, range, halfAngle, lightBound))
  12096. return;
  12097. if (!this._shrinkXYByRadiusPerspective(viewPos, range, lightBound, xPlanes, yPlanes))
  12098. return;
  12099. var viewFor = Cluster._tempVector33;
  12100. viewFor.x = viewConeCap.x - viewPos.x, viewFor.y = viewConeCap.y - viewPos.y, viewFor.z = viewConeCap.z - viewPos.z;
  12101. Vector3.normalize(viewFor, viewFor);
  12102. this._shrinkSpotXYByConePerspective(viewPos, viewFor, range, halfAngle, lightBound, xPlanes, yPlanes);
  12103. this._placeSpotLightToClusters(lightIndex, lightBound);
  12104. }
  12105. _updatePointLightOrth(halfX, halfY, near, far, viewMat, pointLight, lightIndex) {
  12106. var lightBound = Cluster._tempLightBound;
  12107. var lightviewPos = Cluster._tempVector30;
  12108. Vector3.transformV3ToV3(pointLight._transform.position, viewMat, lightviewPos);
  12109. lightviewPos.z *= -1;
  12110. if (!this._shrinkSphereLightByBoundOrth(halfX, halfY, near, far, lightviewPos, pointLight.range, lightBound))
  12111. return;
  12112. this._placePointLightToClusters(lightIndex, lightBound);
  12113. }
  12114. _updateSpotLightOrth(halfX, halfY, near, far, viewMat, spotLight, lightIndex) {
  12115. var lightBound = Cluster._tempLightBound;
  12116. var viewPos = Cluster._tempVector30;
  12117. var forward = Cluster._tempVector31;
  12118. var viewConeCap = Cluster._tempVector34;
  12119. var position = spotLight._transform.position;
  12120. var range = spotLight.range;
  12121. spotLight._transform.worldMatrix.getForward(forward);
  12122. Vector3.normalize(forward, forward);
  12123. Vector3.scale(forward, range, viewConeCap);
  12124. Vector3.add(position, viewConeCap, viewConeCap);
  12125. Vector3.transformV3ToV3(position, viewMat, viewPos);
  12126. Vector3.transformV3ToV3(viewConeCap, viewMat, viewConeCap);
  12127. viewPos.z *= -1;
  12128. viewConeCap.z *= -1;
  12129. var halfAngle = (spotLight.spotAngle / 2) * Math.PI / 180;
  12130. if (!this._shrinkSpotLightByBoundOrth(halfX, halfY, near, far, viewPos, viewConeCap, range, halfAngle, lightBound))
  12131. return;
  12132. this._placeSpotLightToClusters(lightIndex, lightBound);
  12133. }
  12134. update(camera, scene) {
  12135. this._updateMark++;
  12136. var camNear = camera.nearPlane;
  12137. this._depthSliceParam.x = Config3D._config.lightClusterCount.z / Math.log2(camera.farPlane / camNear);
  12138. this._depthSliceParam.y = Math.log2(camNear) * this._depthSliceParam.x;
  12139. var near = camera.nearPlane;
  12140. var far = camera.farPlane;
  12141. var viewMat = camera.viewMatrix;
  12142. var curCount = scene._directionLights._length;
  12143. var pointLights = scene._pointLights;
  12144. var poiCount = pointLights._length;
  12145. var poiElements = pointLights._elements;
  12146. var spotLights = scene._spotLights;
  12147. var spoCount = spotLights._length;
  12148. var spoElements = spotLights._elements;
  12149. if (camera.orthographic) {
  12150. var halfY = camera.orthographicVerticalSize / 2.0;
  12151. var halfX = halfY * camera.aspectRatio;
  12152. for (var i = 0; i < poiCount; i++, curCount++)
  12153. this._updatePointLightOrth(halfX, halfY, near, far, viewMat, poiElements[i], curCount);
  12154. for (var i = 0; i < spoCount; i++, curCount++)
  12155. this._updateSpotLightOrth(halfX, halfY, near, far, viewMat, spoElements[i], curCount);
  12156. }
  12157. else {
  12158. camera._updateClusterPlaneXY();
  12159. var xPlanes = camera._clusterXPlanes;
  12160. var yPlanes = camera._clusterYPlanes;
  12161. for (var i = 0; i < poiCount; i++, curCount++)
  12162. this._updatePointLightPerspective(near, far, viewMat, poiElements[i], curCount, xPlanes, yPlanes);
  12163. for (var i = 0; i < spoCount; i++, curCount++)
  12164. this._updateSpotLightPerspective(near, far, viewMat, spoElements[i], curCount, xPlanes, yPlanes);
  12165. }
  12166. if (poiCount + spoCount > 0) {
  12167. var xSlices = this._xSlices, ySlices = this._ySlices, zSlices = this._zSlices;
  12168. var widthFloat = xSlices * ySlices * 4;
  12169. var lightOff = widthFloat * zSlices;
  12170. var clusterPixels = this._clusterPixels;
  12171. var clusterPixelsCount = clusterPixels.length;
  12172. var clusterDatas = this._clusterDatas;
  12173. var updateMark = this._updateMark;
  12174. var freeSpace = true;
  12175. for (var z = 0; z < zSlices; z++) {
  12176. for (var y = 0; y < ySlices; y++) {
  12177. for (var x = 0; x < xSlices; x++) {
  12178. var data = clusterDatas[z][y][x];
  12179. var clusterOff = (x + y * xSlices + z * xSlices * ySlices) * 4;
  12180. if (data.updateMark !== updateMark) {
  12181. clusterPixels[clusterOff] = 0;
  12182. clusterPixels[clusterOff + 1] = 0;
  12183. }
  12184. else {
  12185. if (freeSpace) {
  12186. var indices = data.indices;
  12187. var pCount = data.pointLightCount;
  12188. var sCount = data.spotLightCount;
  12189. var count = pCount + sCount;
  12190. if (lightOff + count < clusterPixelsCount) {
  12191. clusterPixels[clusterOff] = pCount;
  12192. clusterPixels[clusterOff + 1] = sCount;
  12193. clusterPixels[clusterOff + 2] = Math.floor(lightOff / widthFloat);
  12194. clusterPixels[clusterOff + 3] = lightOff % widthFloat;
  12195. for (var i = 0; i < count; i++)
  12196. clusterPixels[lightOff++] = indices[i];
  12197. }
  12198. else {
  12199. count = clusterPixelsCount - (lightOff + count);
  12200. pCount = Math.min(pCount, count);
  12201. clusterPixels[clusterOff] = pCount;
  12202. clusterPixels[clusterOff + 1] = Math.min(sCount, count - pCount);
  12203. clusterPixels[clusterOff + 2] = Math.floor(lightOff / widthFloat);
  12204. clusterPixels[clusterOff + 3] = lightOff % widthFloat;
  12205. for (var i = 0; i < count; i++)
  12206. clusterPixels[lightOff++] = indices[i];
  12207. freeSpace = false;
  12208. }
  12209. }
  12210. }
  12211. }
  12212. }
  12213. }
  12214. var width = this._clusterTexture.width;
  12215. this._clusterTexture.setSubPixels(0, 0, width, Math.ceil(lightOff / (4 * width)), clusterPixels);
  12216. }
  12217. }
  12218. }
  12219. Cluster._tempVector30 = new Vector3();
  12220. Cluster._tempVector31 = new Vector3();
  12221. Cluster._tempVector32 = new Vector3();
  12222. Cluster._tempVector33 = new Vector3();
  12223. Cluster._tempVector34 = new Vector3();
  12224. Cluster._tempVector35 = new Vector3();
  12225. Cluster._tempVector36 = new Vector3();
  12226. Cluster._tempVector37 = new Vector3();
  12227. Cluster._tempLightBound = new LightBound();
  12228. class SphericalHarmonicsL2 {
  12229. constructor() {
  12230. this._coefficients = new Float32Array(27);
  12231. }
  12232. getCoefficient(i, j) {
  12233. return this._coefficients[i * 9 + j];
  12234. }
  12235. setCoefficient(i, j, coefficient) {
  12236. this._coefficients[i * 9 + j] = coefficient;
  12237. }
  12238. setCoefficients(i, coefficient0, coefficient1, coefficient2, coefficient3, coefficient4, coefficient5, coefficient6, coefficient7, coefficient8) {
  12239. var offset = i * 9;
  12240. this._coefficients[offset] = coefficient0;
  12241. this._coefficients[++offset] = coefficient1;
  12242. this._coefficients[++offset] = coefficient2;
  12243. this._coefficients[++offset] = coefficient3;
  12244. this._coefficients[++offset] = coefficient4;
  12245. this._coefficients[++offset] = coefficient5;
  12246. this._coefficients[++offset] = coefficient6;
  12247. this._coefficients[++offset] = coefficient7;
  12248. this._coefficients[++offset] = coefficient8;
  12249. }
  12250. cloneTo(dest) {
  12251. if (this === dest)
  12252. return;
  12253. var coes = this._coefficients;
  12254. var destCoes = dest._coefficients;
  12255. for (var i = 0; i < 27; i++)
  12256. destCoes[i] = coes[i];
  12257. }
  12258. }
  12259. SphericalHarmonicsL2._default = new SphericalHarmonicsL2();
  12260. class MouseTouch {
  12261. constructor() {
  12262. this._pressedSprite = null;
  12263. this._pressedLoopCount = -1;
  12264. this.sprite = null;
  12265. this.mousePositionX = 0;
  12266. this.mousePositionY = 0;
  12267. }
  12268. }
  12269. class Touch {
  12270. constructor() {
  12271. this._indexInList = -1;
  12272. this._identifier = -1;
  12273. this._position = new Vector2();
  12274. }
  12275. get identifier() {
  12276. return this._identifier;
  12277. }
  12278. get position() {
  12279. return this._position;
  12280. }
  12281. _getIndexInList() {
  12282. return this._indexInList;
  12283. }
  12284. _setIndexInList(index) {
  12285. this._indexInList = index;
  12286. }
  12287. }
  12288. class Plane {
  12289. constructor(normal, d = 0) {
  12290. this.normal = normal;
  12291. this.distance = d;
  12292. }
  12293. static createPlaneBy3P(point0, point1, point2, out) {
  12294. var x1 = point1.x - point0.x;
  12295. var y1 = point1.y - point0.y;
  12296. var z1 = point1.z - point0.z;
  12297. var x2 = point2.x - point0.x;
  12298. var y2 = point2.y - point0.y;
  12299. var z2 = point2.z - point0.z;
  12300. var yz = (y1 * z2) - (z1 * y2);
  12301. var xz = (z1 * x2) - (x1 * z2);
  12302. var xy = (x1 * y2) - (y1 * x2);
  12303. var invPyth = 1.0 / (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  12304. var x = yz * invPyth;
  12305. var y = xz * invPyth;
  12306. var z = xy * invPyth;
  12307. var normal = out.normal;
  12308. normal.x = x;
  12309. normal.y = y;
  12310. normal.z = z;
  12311. out.distance = -((x * point0.x) + (y * point0.y) + (z * point0.z));
  12312. }
  12313. normalize() {
  12314. var normalEX = this.normal.x;
  12315. var normalEY = this.normal.y;
  12316. var normalEZ = this.normal.z;
  12317. var magnitude = 1.0 / Math.sqrt(normalEX * normalEX + normalEY * normalEY + normalEZ * normalEZ);
  12318. this.normal.x = normalEX * magnitude;
  12319. this.normal.y = normalEY * magnitude;
  12320. this.normal.z = normalEZ * magnitude;
  12321. this.distance *= magnitude;
  12322. }
  12323. cloneTo(destObject) {
  12324. var dest = destObject;
  12325. this.normal.cloneTo(dest.normal);
  12326. dest.distance = this.distance;
  12327. }
  12328. clone() {
  12329. var dest = new Plane(new Vector3());
  12330. this.cloneTo(dest);
  12331. return dest;
  12332. }
  12333. }
  12334. Plane.PlaneIntersectionType_Back = 0;
  12335. Plane.PlaneIntersectionType_Front = 1;
  12336. Plane.PlaneIntersectionType_Intersecting = 2;
  12337. class Ray {
  12338. constructor(origin, direction) {
  12339. this.origin = origin;
  12340. this.direction = direction;
  12341. }
  12342. }
  12343. class ContainmentType {
  12344. }
  12345. ContainmentType.Disjoint = 0;
  12346. ContainmentType.Contains = 1;
  12347. ContainmentType.Intersects = 2;
  12348. class CollisionUtils {
  12349. constructor() {
  12350. }
  12351. static distancePlaneToPoint(plane, point) {
  12352. var dot = Vector3.dot(plane.normal, point);
  12353. return dot - plane.distance;
  12354. }
  12355. static distanceBoxToPoint(box, point) {
  12356. var boxMin = box.min;
  12357. var boxMineX = boxMin.x;
  12358. var boxMineY = boxMin.y;
  12359. var boxMineZ = boxMin.z;
  12360. var boxMax = box.max;
  12361. var boxMaxeX = boxMax.x;
  12362. var boxMaxeY = boxMax.y;
  12363. var boxMaxeZ = boxMax.z;
  12364. var pointeX = point.x;
  12365. var pointeY = point.y;
  12366. var pointeZ = point.z;
  12367. var distance = 0;
  12368. if (pointeX < boxMineX)
  12369. distance += (boxMineX - pointeX) * (boxMineX - pointeX);
  12370. if (pointeX > boxMaxeX)
  12371. distance += (boxMaxeX - pointeX) * (boxMaxeX - pointeX);
  12372. if (pointeY < boxMineY)
  12373. distance += (boxMineY - pointeY) * (boxMineY - pointeY);
  12374. if (pointeY > boxMaxeY)
  12375. distance += (boxMaxeY - pointeY) * (boxMaxeY - pointeY);
  12376. if (pointeZ < boxMineZ)
  12377. distance += (boxMineZ - pointeZ) * (boxMineZ - pointeZ);
  12378. if (pointeZ > boxMaxeZ)
  12379. distance += (boxMaxeZ - pointeZ) * (boxMaxeZ - pointeZ);
  12380. return Math.sqrt(distance);
  12381. }
  12382. static distanceBoxToBox(box1, box2) {
  12383. var box1Mine = box1.min;
  12384. var box1MineX = box1Mine.x;
  12385. var box1MineY = box1Mine.y;
  12386. var box1MineZ = box1Mine.z;
  12387. var box1Maxe = box1.max;
  12388. var box1MaxeX = box1Maxe.x;
  12389. var box1MaxeY = box1Maxe.y;
  12390. var box1MaxeZ = box1Maxe.z;
  12391. var box2Mine = box2.min;
  12392. var box2MineX = box2Mine.x;
  12393. var box2MineY = box2Mine.y;
  12394. var box2MineZ = box2Mine.z;
  12395. var box2Maxe = box2.max;
  12396. var box2MaxeX = box2Maxe.x;
  12397. var box2MaxeY = box2Maxe.y;
  12398. var box2MaxeZ = box2Maxe.z;
  12399. var distance = 0;
  12400. var delta;
  12401. if (box1MineX > box2MaxeX) {
  12402. delta = box1MineX - box2MaxeX;
  12403. distance += delta * delta;
  12404. }
  12405. else if (box2MineX > box1MaxeX) {
  12406. delta = box2MineX - box1MaxeX;
  12407. distance += delta * delta;
  12408. }
  12409. if (box1MineY > box2MaxeY) {
  12410. delta = box1MineY - box2MaxeY;
  12411. distance += delta * delta;
  12412. }
  12413. else if (box2MineY > box1MaxeY) {
  12414. delta = box2MineY - box1MaxeY;
  12415. distance += delta * delta;
  12416. }
  12417. if (box1MineZ > box2MaxeZ) {
  12418. delta = box1MineZ - box2MaxeZ;
  12419. distance += delta * delta;
  12420. }
  12421. else if (box2MineZ > box1MaxeZ) {
  12422. delta = box2MineZ - box1MaxeZ;
  12423. distance += delta * delta;
  12424. }
  12425. return Math.sqrt(distance);
  12426. }
  12427. static distanceSphereToPoint(sphere, point) {
  12428. var distance = Math.sqrt(Vector3.distanceSquared(sphere.center, point));
  12429. distance -= sphere.radius;
  12430. return Math.max(distance, 0);
  12431. }
  12432. static distanceSphereToSphere(sphere1, sphere2) {
  12433. var distance = Math.sqrt(Vector3.distanceSquared(sphere1.center, sphere2.center));
  12434. distance -= sphere1.radius + sphere2.radius;
  12435. return Math.max(distance, 0);
  12436. }
  12437. static intersectsRayAndTriangleRD(ray, vertex1, vertex2, vertex3, out) {
  12438. var rayO = ray.origin;
  12439. var rayOeX = rayO.x;
  12440. var rayOeY = rayO.y;
  12441. var rayOeZ = rayO.z;
  12442. var rayD = ray.direction;
  12443. var rayDeX = rayD.x;
  12444. var rayDeY = rayD.y;
  12445. var rayDeZ = rayD.z;
  12446. var v1eX = vertex1.x;
  12447. var v1eY = vertex1.y;
  12448. var v1eZ = vertex1.z;
  12449. var v2eX = vertex2.x;
  12450. var v2eY = vertex2.y;
  12451. var v2eZ = vertex2.z;
  12452. var v3eX = vertex3.x;
  12453. var v3eY = vertex3.y;
  12454. var v3eZ = vertex3.z;
  12455. var _tempV30eX = CollisionUtils._tempV30.x;
  12456. var _tempV30eY = CollisionUtils._tempV30.y;
  12457. var _tempV30eZ = CollisionUtils._tempV30.z;
  12458. _tempV30eX = v2eX - v1eX;
  12459. _tempV30eY = v2eY - v1eY;
  12460. _tempV30eZ = v2eZ - v1eZ;
  12461. var _tempV31eX = CollisionUtils._tempV31.x;
  12462. var _tempV31eY = CollisionUtils._tempV31.y;
  12463. var _tempV31eZ = CollisionUtils._tempV31.z;
  12464. _tempV31eX = v3eX - v1eX;
  12465. _tempV31eY = v3eY - v1eY;
  12466. _tempV31eZ = v3eZ - v1eZ;
  12467. var _tempV32eX = CollisionUtils._tempV32.x;
  12468. var _tempV32eY = CollisionUtils._tempV32.y;
  12469. var _tempV32eZ = CollisionUtils._tempV32.z;
  12470. _tempV32eX = (rayDeY * _tempV31eZ) - (rayDeZ * _tempV31eY);
  12471. _tempV32eY = (rayDeZ * _tempV31eX) - (rayDeX * _tempV31eZ);
  12472. _tempV32eZ = (rayDeX * _tempV31eY) - (rayDeY * _tempV31eX);
  12473. var determinant = (_tempV30eX * _tempV32eX) + (_tempV30eY * _tempV32eY) + (_tempV30eZ * _tempV32eZ);
  12474. if (MathUtils3D.isZero(determinant)) {
  12475. return false;
  12476. }
  12477. var inversedeterminant = 1 / determinant;
  12478. var _tempV33eX = CollisionUtils._tempV33.x;
  12479. var _tempV33eY = CollisionUtils._tempV33.y;
  12480. var _tempV33eZ = CollisionUtils._tempV33.z;
  12481. _tempV33eX = rayOeX - v1eX;
  12482. _tempV33eY = rayOeY - v1eY;
  12483. _tempV33eZ = rayOeZ - v1eZ;
  12484. var triangleU = (_tempV33eX * _tempV32eX) + (_tempV33eY * _tempV32eY) + (_tempV33eZ * _tempV32eZ);
  12485. triangleU *= inversedeterminant;
  12486. if (triangleU < 0 || triangleU > 1) {
  12487. return false;
  12488. }
  12489. var _tempV34eX = CollisionUtils._tempV34.x;
  12490. var _tempV34eY = CollisionUtils._tempV34.y;
  12491. var _tempV34eZ = CollisionUtils._tempV34.z;
  12492. _tempV34eX = (_tempV33eY * _tempV30eZ) - (_tempV33eZ * _tempV30eY);
  12493. _tempV34eY = (_tempV33eZ * _tempV30eX) - (_tempV33eX * _tempV30eZ);
  12494. _tempV34eZ = (_tempV33eX * _tempV30eY) - (_tempV33eY * _tempV30eX);
  12495. var triangleV = ((rayDeX * _tempV34eX) + (rayDeY * _tempV34eY)) + (rayDeZ * _tempV34eZ);
  12496. triangleV *= inversedeterminant;
  12497. if (triangleV < 0 || triangleU + triangleV > 1) {
  12498. return false;
  12499. }
  12500. var raydistance = (_tempV31eX * _tempV34eX) + (_tempV31eY * _tempV34eY) + (_tempV31eZ * _tempV34eZ);
  12501. raydistance *= inversedeterminant;
  12502. if (raydistance < 0) {
  12503. return false;
  12504. }
  12505. return true;
  12506. }
  12507. static intersectsRayAndTriangleRP(ray, vertex1, vertex2, vertex3, out) {
  12508. var distance;
  12509. if (!CollisionUtils.intersectsRayAndTriangleRD(ray, vertex1, vertex2, vertex3, distance)) {
  12510. out = Vector3._ZERO;
  12511. return false;
  12512. }
  12513. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  12514. Vector3.add(ray.origin, CollisionUtils._tempV30, out);
  12515. return true;
  12516. }
  12517. static intersectsRayAndPoint(ray, point) {
  12518. Vector3.subtract(ray.origin, point, CollisionUtils._tempV30);
  12519. var b = Vector3.dot(CollisionUtils._tempV30, ray.direction);
  12520. var c = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30) - MathUtils3D.zeroTolerance;
  12521. if (c > 0 && b > 0)
  12522. return false;
  12523. var discriminant = b * b - c;
  12524. if (discriminant < 0)
  12525. return false;
  12526. return true;
  12527. }
  12528. static intersectsRayAndRay(ray1, ray2, out) {
  12529. var ray1o = ray1.origin;
  12530. var ray1oeX = ray1o.x;
  12531. var ray1oeY = ray1o.y;
  12532. var ray1oeZ = ray1o.z;
  12533. var ray1d = ray1.direction;
  12534. var ray1deX = ray1d.x;
  12535. var ray1deY = ray1d.y;
  12536. var ray1deZ = ray1d.z;
  12537. var ray2o = ray2.origin;
  12538. var ray2oeX = ray2o.x;
  12539. var ray2oeY = ray2o.y;
  12540. var ray2oeZ = ray2o.z;
  12541. var ray2d = ray2.direction;
  12542. var ray2deX = ray2d.x;
  12543. var ray2deY = ray2d.y;
  12544. var ray2deZ = ray2d.z;
  12545. Vector3.cross(ray1d, ray2d, CollisionUtils._tempV30);
  12546. var tempV3 = CollisionUtils._tempV30;
  12547. var denominator = Vector3.scalarLength(CollisionUtils._tempV30);
  12548. if (MathUtils3D.isZero(denominator)) {
  12549. if (MathUtils3D.nearEqual(ray2oeX, ray1oeX) && MathUtils3D.nearEqual(ray2oeY, ray1oeY) && MathUtils3D.nearEqual(ray2oeZ, ray1oeZ)) {
  12550. return true;
  12551. }
  12552. }
  12553. denominator = denominator * denominator;
  12554. var m11 = ray2oeX - ray1oeX;
  12555. var m12 = ray2oeY - ray1oeY;
  12556. var m13 = ray2oeZ - ray1oeZ;
  12557. var m21 = ray2deX;
  12558. var m22 = ray2deY;
  12559. var m23 = ray2deZ;
  12560. var m31 = tempV3.x;
  12561. var m32 = tempV3.y;
  12562. var m33 = tempV3.z;
  12563. var dets = m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m11 * m23 * m32 - m12 * m21 * m33 - m13 * m22 * m31;
  12564. m21 = ray1deX;
  12565. m22 = ray1deY;
  12566. m23 = ray1deZ;
  12567. var s = dets / denominator;
  12568. Vector3.scale(ray1d, s, CollisionUtils._tempV30);
  12569. Vector3.scale(ray2d, s, CollisionUtils._tempV31);
  12570. Vector3.add(ray1o, CollisionUtils._tempV30, CollisionUtils._tempV32);
  12571. Vector3.add(ray2o, CollisionUtils._tempV31, CollisionUtils._tempV33);
  12572. var point1e = CollisionUtils._tempV32;
  12573. var point2e = CollisionUtils._tempV33;
  12574. if (!MathUtils3D.nearEqual(point2e.x, point1e.x) || !MathUtils3D.nearEqual(point2e.y, point1e.y) || !MathUtils3D.nearEqual(point2e.z, point1e.z)) {
  12575. return false;
  12576. }
  12577. return true;
  12578. }
  12579. static intersectsPlaneAndTriangle(plane, vertex1, vertex2, vertex3) {
  12580. var test1 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex1);
  12581. var test2 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex2);
  12582. var test3 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex3);
  12583. if (test1 == Plane.PlaneIntersectionType_Front && test2 == Plane.PlaneIntersectionType_Front && test3 == Plane.PlaneIntersectionType_Front)
  12584. return Plane.PlaneIntersectionType_Front;
  12585. if (test1 == Plane.PlaneIntersectionType_Back && test2 == Plane.PlaneIntersectionType_Back && test3 == Plane.PlaneIntersectionType_Back)
  12586. return Plane.PlaneIntersectionType_Back;
  12587. return Plane.PlaneIntersectionType_Intersecting;
  12588. }
  12589. static intersectsRayAndPlaneRD(ray, plane) {
  12590. var planeNor = plane.normal;
  12591. var direction = Vector3.dot(planeNor, ray.direction);
  12592. if (Math.abs(direction) < MathUtils3D.zeroTolerance)
  12593. return -1;
  12594. var position = Vector3.dot(planeNor, ray.origin);
  12595. var distance = (-plane.distance - position) / direction;
  12596. if (distance < 0) {
  12597. if (distance < -MathUtils3D.zeroTolerance)
  12598. return -1;
  12599. distance = 0;
  12600. }
  12601. return distance;
  12602. }
  12603. static intersectsRayAndPlaneRP(ray, plane, out) {
  12604. var distance = CollisionUtils.intersectsRayAndPlaneRD(ray, plane);
  12605. if (distance == -1) {
  12606. out.setValue(0, 0, 0);
  12607. return false;
  12608. }
  12609. var scaDis = CollisionUtils._tempV30;
  12610. Vector3.scale(ray.direction, distance, scaDis);
  12611. Vector3.add(ray.origin, scaDis, out);
  12612. return true;
  12613. }
  12614. static intersectsRayAndBoxRD(ray, box) {
  12615. var rayoe = ray.origin;
  12616. var rayoeX = rayoe.x;
  12617. var rayoeY = rayoe.y;
  12618. var rayoeZ = rayoe.z;
  12619. var rayde = ray.direction;
  12620. var raydeX = rayde.x;
  12621. var raydeY = rayde.y;
  12622. var raydeZ = rayde.z;
  12623. var boxMine = box.min;
  12624. var boxMineX = boxMine.x;
  12625. var boxMineY = boxMine.y;
  12626. var boxMineZ = boxMine.z;
  12627. var boxMaxe = box.max;
  12628. var boxMaxeX = boxMaxe.x;
  12629. var boxMaxeY = boxMaxe.y;
  12630. var boxMaxeZ = boxMaxe.z;
  12631. var out = 0;
  12632. var tmax = MathUtils3D.MaxValue;
  12633. if (MathUtils3D.isZero(raydeX)) {
  12634. if (rayoeX < boxMineX || rayoeX > boxMaxeX) {
  12635. return -1;
  12636. }
  12637. }
  12638. else {
  12639. var inverse = 1 / raydeX;
  12640. var t1 = (boxMineX - rayoeX) * inverse;
  12641. var t2 = (boxMaxeX - rayoeX) * inverse;
  12642. if (t1 > t2) {
  12643. var temp = t1;
  12644. t1 = t2;
  12645. t2 = temp;
  12646. }
  12647. out = Math.max(t1, out);
  12648. tmax = Math.min(t2, tmax);
  12649. if (out > tmax) {
  12650. return -1;
  12651. }
  12652. }
  12653. if (MathUtils3D.isZero(raydeY)) {
  12654. if (rayoeY < boxMineY || rayoeY > boxMaxeY) {
  12655. return -1;
  12656. }
  12657. }
  12658. else {
  12659. var inverse1 = 1 / raydeY;
  12660. var t3 = (boxMineY - rayoeY) * inverse1;
  12661. var t4 = (boxMaxeY - rayoeY) * inverse1;
  12662. if (t3 > t4) {
  12663. var temp1 = t3;
  12664. t3 = t4;
  12665. t4 = temp1;
  12666. }
  12667. out = Math.max(t3, out);
  12668. tmax = Math.min(t4, tmax);
  12669. if (out > tmax) {
  12670. return -1;
  12671. }
  12672. }
  12673. if (MathUtils3D.isZero(raydeZ)) {
  12674. if (rayoeZ < boxMineZ || rayoeZ > boxMaxeZ) {
  12675. return -1;
  12676. }
  12677. }
  12678. else {
  12679. var inverse2 = 1 / raydeZ;
  12680. var t5 = (boxMineZ - rayoeZ) * inverse2;
  12681. var t6 = (boxMaxeZ - rayoeZ) * inverse2;
  12682. if (t5 > t6) {
  12683. var temp2 = t5;
  12684. t5 = t6;
  12685. t6 = temp2;
  12686. }
  12687. out = Math.max(t5, out);
  12688. tmax = Math.min(t6, tmax);
  12689. if (out > tmax) {
  12690. return -1;
  12691. }
  12692. }
  12693. return out;
  12694. }
  12695. static intersectsRayAndBoxRP(ray, box, out) {
  12696. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, box);
  12697. if (distance === -1) {
  12698. Vector3._ZERO.cloneTo(out);
  12699. return distance;
  12700. }
  12701. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  12702. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  12703. CollisionUtils._tempV31.cloneTo(out);
  12704. return distance;
  12705. }
  12706. static intersectsRayAndSphereRD(ray, sphere) {
  12707. var sphereR = sphere.radius;
  12708. Vector3.subtract(ray.origin, sphere.center, CollisionUtils._tempV30);
  12709. var b = Vector3.dot(CollisionUtils._tempV30, ray.direction);
  12710. var c = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30) - (sphereR * sphereR);
  12711. if (c > 0 && b > 0) {
  12712. return -1;
  12713. }
  12714. var discriminant = b * b - c;
  12715. if (discriminant < 0) {
  12716. return -1;
  12717. }
  12718. var distance = -b - Math.sqrt(discriminant);
  12719. if (distance < 0)
  12720. distance = 0;
  12721. return distance;
  12722. }
  12723. static intersectsRayAndSphereRP(ray, sphere, out) {
  12724. var distance = CollisionUtils.intersectsRayAndSphereRD(ray, sphere);
  12725. if (distance === -1) {
  12726. Vector3._ZERO.cloneTo(out);
  12727. return distance;
  12728. }
  12729. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  12730. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  12731. CollisionUtils._tempV31.cloneTo(out);
  12732. return distance;
  12733. }
  12734. static intersectsSphereAndTriangle(sphere, vertex1, vertex2, vertex3) {
  12735. var sphereC = sphere.center;
  12736. var sphereR = sphere.radius;
  12737. CollisionUtils.closestPointPointTriangle(sphereC, vertex1, vertex2, vertex3, CollisionUtils._tempV30);
  12738. Vector3.subtract(CollisionUtils._tempV30, sphereC, CollisionUtils._tempV31);
  12739. var dot = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV31);
  12740. return dot <= sphereR * sphereR;
  12741. }
  12742. static intersectsPlaneAndPoint(plane, point) {
  12743. var distance = Vector3.dot(plane.normal, point) + plane.distance;
  12744. if (distance > 0)
  12745. return Plane.PlaneIntersectionType_Front;
  12746. if (distance < 0)
  12747. return Plane.PlaneIntersectionType_Back;
  12748. return Plane.PlaneIntersectionType_Intersecting;
  12749. }
  12750. static intersectsPlaneAndPlane(plane1, plane2) {
  12751. Vector3.cross(plane1.normal, plane2.normal, CollisionUtils._tempV30);
  12752. var denominator = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30);
  12753. if (MathUtils3D.isZero(denominator))
  12754. return false;
  12755. return true;
  12756. }
  12757. static intersectsPlaneAndPlaneRL(plane1, plane2, line) {
  12758. var plane1nor = plane1.normal;
  12759. var plane2nor = plane2.normal;
  12760. Vector3.cross(plane1nor, plane2nor, CollisionUtils._tempV34);
  12761. var denominator = Vector3.dot(CollisionUtils._tempV34, CollisionUtils._tempV34);
  12762. if (MathUtils3D.isZero(denominator))
  12763. return false;
  12764. Vector3.scale(plane2nor, plane1.distance, CollisionUtils._tempV30);
  12765. Vector3.scale(plane1nor, plane2.distance, CollisionUtils._tempV31);
  12766. Vector3.subtract(CollisionUtils._tempV30, CollisionUtils._tempV31, CollisionUtils._tempV32);
  12767. Vector3.cross(CollisionUtils._tempV32, CollisionUtils._tempV34, CollisionUtils._tempV33);
  12768. Vector3.normalize(CollisionUtils._tempV34, CollisionUtils._tempV34);
  12769. return true;
  12770. }
  12771. static intersectsPlaneAndBox(plane, box) {
  12772. var planeD = plane.distance;
  12773. var planeNor = plane.normal;
  12774. var planeNoreX = planeNor.x;
  12775. var planeNoreY = planeNor.y;
  12776. var planeNoreZ = planeNor.z;
  12777. var boxMine = box.min;
  12778. var boxMineX = boxMine.x;
  12779. var boxMineY = boxMine.y;
  12780. var boxMineZ = boxMine.z;
  12781. var boxMaxe = box.max;
  12782. var boxMaxeX = boxMaxe.x;
  12783. var boxMaxeY = boxMaxe.y;
  12784. var boxMaxeZ = boxMaxe.z;
  12785. CollisionUtils._tempV30.x = (planeNoreX > 0) ? boxMineX : boxMaxeX;
  12786. CollisionUtils._tempV30.y = (planeNoreY > 0) ? boxMineY : boxMaxeY;
  12787. CollisionUtils._tempV30.z = (planeNoreZ > 0) ? boxMineZ : boxMaxeZ;
  12788. CollisionUtils._tempV31.x = (planeNoreX > 0) ? boxMaxeX : boxMineX;
  12789. CollisionUtils._tempV31.y = (planeNoreY > 0) ? boxMaxeY : boxMineY;
  12790. CollisionUtils._tempV31.z = (planeNoreZ > 0) ? boxMaxeZ : boxMineZ;
  12791. var distance = Vector3.dot(planeNor, CollisionUtils._tempV30);
  12792. if (distance + planeD > 0)
  12793. return Plane.PlaneIntersectionType_Front;
  12794. distance = Vector3.dot(planeNor, CollisionUtils._tempV31);
  12795. if (distance + planeD < 0)
  12796. return Plane.PlaneIntersectionType_Back;
  12797. return Plane.PlaneIntersectionType_Intersecting;
  12798. }
  12799. static intersectsPlaneAndSphere(plane, sphere) {
  12800. var sphereR = sphere.radius;
  12801. var distance = Vector3.dot(plane.normal, sphere.center) + plane.distance;
  12802. if (distance > sphereR)
  12803. return Plane.PlaneIntersectionType_Front;
  12804. if (distance < -sphereR)
  12805. return Plane.PlaneIntersectionType_Back;
  12806. return Plane.PlaneIntersectionType_Intersecting;
  12807. }
  12808. static intersectsBoxAndBox(box1, box2) {
  12809. var box1Mine = box1.min;
  12810. var box1Maxe = box1.max;
  12811. var box2Mine = box2.min;
  12812. var box2Maxe = box2.max;
  12813. if (box1Mine.x > box2Maxe.x || box2Mine.x > box1Maxe.x)
  12814. return false;
  12815. if (box1Mine.y > box2Maxe.y || box2Mine.y > box1Maxe.y)
  12816. return false;
  12817. if (box1Mine.z > box2Maxe.z || box2Mine.z > box1Maxe.z)
  12818. return false;
  12819. return true;
  12820. }
  12821. static intersectsBoxAndSphere(box, sphere) {
  12822. var center = sphere.center;
  12823. var radius = sphere.radius;
  12824. var nearest = CollisionUtils._tempV30;
  12825. Vector3.Clamp(center, box.min, box.max, nearest);
  12826. var distance = Vector3.distanceSquared(center, nearest);
  12827. return distance <= radius * radius;
  12828. }
  12829. static intersectsSphereAndSphere(sphere1, sphere2) {
  12830. var radiisum = sphere1.radius + sphere2.radius;
  12831. return Vector3.distanceSquared(sphere1.center, sphere2.center) <= radiisum * radiisum;
  12832. }
  12833. static boxContainsPoint(box, point) {
  12834. var boxMine = box.min;
  12835. var boxMaxe = box.max;
  12836. 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)
  12837. return ContainmentType.Contains;
  12838. return ContainmentType.Disjoint;
  12839. }
  12840. static boxContainsBox(box1, box2) {
  12841. var box1Mine = box1.min;
  12842. var box1MineX = box1Mine.x;
  12843. var box1MineY = box1Mine.y;
  12844. var box1MineZ = box1Mine.z;
  12845. var box1Maxe = box1.max;
  12846. var box1MaxeX = box1Maxe.x;
  12847. var box1MaxeY = box1Maxe.y;
  12848. var box1MaxeZ = box1Maxe.z;
  12849. var box2Mine = box2.min;
  12850. var box2MineX = box2Mine.x;
  12851. var box2MineY = box2Mine.y;
  12852. var box2MineZ = box2Mine.z;
  12853. var box2Maxe = box2.max;
  12854. var box2MaxeX = box2Maxe.x;
  12855. var box2MaxeY = box2Maxe.y;
  12856. var box2MaxeZ = box2Maxe.z;
  12857. if (box1MaxeX < box2MineX || box1MineX > box2MaxeX)
  12858. return ContainmentType.Disjoint;
  12859. if (box1MaxeY < box2MineY || box1MineY > box2MaxeY)
  12860. return ContainmentType.Disjoint;
  12861. if (box1MaxeZ < box2MineZ || box1MineZ > box2MaxeZ)
  12862. return ContainmentType.Disjoint;
  12863. if (box1MineX <= box2MineX && box2MaxeX <= box1MaxeX && box1MineY <= box2MineY && box2MaxeY <= box1MaxeY && box1MineZ <= box2MineZ && box2MaxeZ <= box1MaxeZ) {
  12864. return ContainmentType.Contains;
  12865. }
  12866. return ContainmentType.Intersects;
  12867. }
  12868. static boxContainsSphere(box, sphere) {
  12869. var boxMin = box.min;
  12870. var boxMineX = boxMin.x;
  12871. var boxMineY = boxMin.y;
  12872. var boxMineZ = boxMin.z;
  12873. var boxMax = box.max;
  12874. var boxMaxeX = boxMax.x;
  12875. var boxMaxeY = boxMax.y;
  12876. var boxMaxeZ = boxMax.z;
  12877. var sphereC = sphere.center;
  12878. var sphereCeX = sphereC.x;
  12879. var sphereCeY = sphereC.y;
  12880. var sphereCeZ = sphereC.z;
  12881. var sphereR = sphere.radius;
  12882. Vector3.Clamp(sphereC, boxMin, boxMax, CollisionUtils._tempV30);
  12883. var distance = Vector3.distanceSquared(sphereC, CollisionUtils._tempV30);
  12884. if (distance > sphereR * sphereR)
  12885. return ContainmentType.Disjoint;
  12886. if ((((boxMineX + sphereR <= sphereCeX) && (sphereCeX <= boxMaxeX - sphereR)) && ((boxMaxeX - boxMineX > sphereR) &&
  12887. (boxMineY + sphereR <= sphereCeY))) && (((sphereCeY <= boxMaxeY - sphereR) && (boxMaxeY - boxMineY > sphereR)) &&
  12888. (((boxMineZ + sphereR <= sphereCeZ) && (sphereCeZ <= boxMaxeZ - sphereR)) && (boxMaxeZ - boxMineZ > sphereR))))
  12889. return ContainmentType.Contains;
  12890. return ContainmentType.Intersects;
  12891. }
  12892. static sphereContainsPoint(sphere, point) {
  12893. if (Vector3.distanceSquared(point, sphere.center) <= sphere.radius * sphere.radius)
  12894. return ContainmentType.Contains;
  12895. return ContainmentType.Disjoint;
  12896. }
  12897. static sphereContainsTriangle(sphere, vertex1, vertex2, vertex3) {
  12898. var test1 = CollisionUtils.sphereContainsPoint(sphere, vertex1);
  12899. var test2 = CollisionUtils.sphereContainsPoint(sphere, vertex2);
  12900. var test3 = CollisionUtils.sphereContainsPoint(sphere, vertex3);
  12901. if (test1 == ContainmentType.Contains && test2 == ContainmentType.Contains && test3 == ContainmentType.Contains)
  12902. return ContainmentType.Contains;
  12903. if (CollisionUtils.intersectsSphereAndTriangle(sphere, vertex1, vertex2, vertex3))
  12904. return ContainmentType.Intersects;
  12905. return ContainmentType.Disjoint;
  12906. }
  12907. static sphereContainsBox(sphere, box) {
  12908. var sphereC = sphere.center;
  12909. var sphereCeX = sphereC.x;
  12910. var sphereCeY = sphereC.y;
  12911. var sphereCeZ = sphereC.z;
  12912. var sphereR = sphere.radius;
  12913. var boxMin = box.min;
  12914. var boxMineX = boxMin.x;
  12915. var boxMineY = boxMin.y;
  12916. var boxMineZ = boxMin.z;
  12917. var boxMax = box.max;
  12918. var boxMaxeX = boxMax.x;
  12919. var boxMaxeY = boxMax.y;
  12920. var boxMaxeZ = boxMax.z;
  12921. var _tempV30e = CollisionUtils._tempV30;
  12922. var _tempV30eX = _tempV30e.x;
  12923. var _tempV30eY = _tempV30e.y;
  12924. var _tempV30eZ = _tempV30e.z;
  12925. if (!CollisionUtils.intersectsBoxAndSphere(box, sphere))
  12926. return ContainmentType.Disjoint;
  12927. var radiusSquared = sphereR * sphereR;
  12928. _tempV30eX = sphereCeX - boxMineX;
  12929. _tempV30eY = sphereCeY - boxMaxeY;
  12930. _tempV30eZ = sphereCeZ - boxMaxeZ;
  12931. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12932. return ContainmentType.Intersects;
  12933. _tempV30eX = sphereCeX - boxMaxeX;
  12934. _tempV30eY = sphereCeY - boxMaxeY;
  12935. _tempV30eZ = sphereCeZ - boxMaxeZ;
  12936. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12937. return ContainmentType.Intersects;
  12938. _tempV30eX = sphereCeX - boxMaxeX;
  12939. _tempV30eY = sphereCeY - boxMineY;
  12940. _tempV30eZ = sphereCeZ - boxMaxeZ;
  12941. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12942. return ContainmentType.Intersects;
  12943. _tempV30eX = sphereCeX - boxMineX;
  12944. _tempV30eY = sphereCeY - boxMineY;
  12945. _tempV30eZ = sphereCeZ - boxMaxeZ;
  12946. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12947. return ContainmentType.Intersects;
  12948. _tempV30eX = sphereCeX - boxMineX;
  12949. _tempV30eY = sphereCeY - boxMaxeY;
  12950. _tempV30eZ = sphereCeZ - boxMineZ;
  12951. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12952. return ContainmentType.Intersects;
  12953. _tempV30eX = sphereCeX - boxMaxeX;
  12954. _tempV30eY = sphereCeY - boxMaxeY;
  12955. _tempV30eZ = sphereCeZ - boxMineZ;
  12956. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12957. return ContainmentType.Intersects;
  12958. _tempV30eX = sphereCeX - boxMaxeX;
  12959. _tempV30eY = sphereCeY - boxMineY;
  12960. _tempV30eZ = sphereCeZ - boxMineZ;
  12961. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12962. return ContainmentType.Intersects;
  12963. _tempV30eX = sphereCeX - boxMineX;
  12964. _tempV30eY = sphereCeY - boxMineY;
  12965. _tempV30eZ = sphereCeZ - boxMineZ;
  12966. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  12967. return ContainmentType.Intersects;
  12968. return ContainmentType.Contains;
  12969. }
  12970. static sphereContainsSphere(sphere1, sphere2) {
  12971. var sphere1R = sphere1.radius;
  12972. var sphere2R = sphere2.radius;
  12973. var distance = Vector3.distance(sphere1.center, sphere2.center);
  12974. if (sphere1R + sphere2R < distance)
  12975. return ContainmentType.Disjoint;
  12976. if (sphere1R - sphere2R < distance)
  12977. return ContainmentType.Intersects;
  12978. return ContainmentType.Contains;
  12979. }
  12980. static closestPointPointTriangle(point, vertex1, vertex2, vertex3, out) {
  12981. Vector3.subtract(vertex2, vertex1, CollisionUtils._tempV30);
  12982. Vector3.subtract(vertex3, vertex1, CollisionUtils._tempV31);
  12983. Vector3.subtract(point, vertex1, CollisionUtils._tempV32);
  12984. Vector3.subtract(point, vertex2, CollisionUtils._tempV33);
  12985. Vector3.subtract(point, vertex3, CollisionUtils._tempV34);
  12986. var d1 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV32);
  12987. var d2 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV32);
  12988. var d3 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV33);
  12989. var d4 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV33);
  12990. var d5 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV34);
  12991. var d6 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV34);
  12992. if (d1 <= 0 && d2 <= 0) {
  12993. vertex1.cloneTo(out);
  12994. return;
  12995. }
  12996. if (d3 >= 0 && d4 <= d3) {
  12997. vertex2.cloneTo(out);
  12998. return;
  12999. }
  13000. var vc = d1 * d4 - d3 * d2;
  13001. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  13002. var v = d1 / (d1 - d3);
  13003. Vector3.scale(CollisionUtils._tempV30, v, out);
  13004. Vector3.add(vertex1, out, out);
  13005. return;
  13006. }
  13007. if (d6 >= 0 && d5 <= d6) {
  13008. vertex3.cloneTo(out);
  13009. return;
  13010. }
  13011. var vb = d5 * d2 - d1 * d6;
  13012. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  13013. var w = d2 / (d2 - d6);
  13014. Vector3.scale(CollisionUtils._tempV31, w, out);
  13015. Vector3.add(vertex1, out, out);
  13016. return;
  13017. }
  13018. var va = d3 * d6 - d5 * d4;
  13019. if (va <= 0 && (d4 - d3) >= 0 && (d5 - d6) >= 0) {
  13020. var w3 = (d4 - d3) / ((d4 - d3) + (d5 - d6));
  13021. Vector3.subtract(vertex3, vertex2, out);
  13022. Vector3.scale(out, w3, out);
  13023. Vector3.add(vertex2, out, out);
  13024. return;
  13025. }
  13026. var denom = 1 / (va + vb + vc);
  13027. var v2 = vb * denom;
  13028. var w2 = vc * denom;
  13029. Vector3.scale(CollisionUtils._tempV30, v2, CollisionUtils._tempV35);
  13030. Vector3.scale(CollisionUtils._tempV31, w2, CollisionUtils._tempV36);
  13031. Vector3.add(CollisionUtils._tempV35, CollisionUtils._tempV36, out);
  13032. Vector3.add(vertex1, out, out);
  13033. }
  13034. static closestPointPlanePoint(plane, point, out) {
  13035. var planeN = plane.normal;
  13036. var t = Vector3.dot(planeN, point) - plane.distance;
  13037. Vector3.scale(planeN, t, CollisionUtils._tempV30);
  13038. Vector3.subtract(point, CollisionUtils._tempV30, out);
  13039. }
  13040. static closestPointBoxPoint(box, point, out) {
  13041. Vector3.max(point, box.min, CollisionUtils._tempV30);
  13042. Vector3.min(CollisionUtils._tempV30, box.max, out);
  13043. }
  13044. static closestPointSpherePoint(sphere, point, out) {
  13045. var sphereC = sphere.center;
  13046. Vector3.subtract(point, sphereC, out);
  13047. Vector3.normalize(out, out);
  13048. Vector3.scale(out, sphere.radius, out);
  13049. Vector3.add(out, sphereC, out);
  13050. }
  13051. static closestPointSphereSphere(sphere1, sphere2, out) {
  13052. var sphere1C = sphere1.center;
  13053. Vector3.subtract(sphere2.center, sphere1C, out);
  13054. Vector3.normalize(out, out);
  13055. Vector3.scale(out, sphere1.radius, out);
  13056. Vector3.add(out, sphere1C, out);
  13057. }
  13058. }
  13059. CollisionUtils._tempV30 = new Vector3();
  13060. CollisionUtils._tempV31 = new Vector3();
  13061. CollisionUtils._tempV32 = new Vector3();
  13062. CollisionUtils._tempV33 = new Vector3();
  13063. CollisionUtils._tempV34 = new Vector3();
  13064. CollisionUtils._tempV35 = new Vector3();
  13065. CollisionUtils._tempV36 = new Vector3();
  13066. (function (FrustumCorner) {
  13067. FrustumCorner[FrustumCorner["FarBottomLeft"] = 0] = "FarBottomLeft";
  13068. FrustumCorner[FrustumCorner["FarTopLeft"] = 1] = "FarTopLeft";
  13069. FrustumCorner[FrustumCorner["FarTopRight"] = 2] = "FarTopRight";
  13070. FrustumCorner[FrustumCorner["FarBottomRight"] = 3] = "FarBottomRight";
  13071. FrustumCorner[FrustumCorner["nearBottomLeft"] = 4] = "nearBottomLeft";
  13072. FrustumCorner[FrustumCorner["nearTopLeft"] = 5] = "nearTopLeft";
  13073. FrustumCorner[FrustumCorner["nearTopRight"] = 6] = "nearTopRight";
  13074. FrustumCorner[FrustumCorner["nearBottomRight"] = 7] = "nearBottomRight";
  13075. FrustumCorner[FrustumCorner["unknown"] = 8] = "unknown";
  13076. })(exports.FrustumCorner || (exports.FrustumCorner = {}));
  13077. class BoundFrustum {
  13078. constructor(matrix) {
  13079. this._matrix = matrix;
  13080. this._near = new Plane(new Vector3());
  13081. this._far = new Plane(new Vector3());
  13082. this._left = new Plane(new Vector3());
  13083. this._right = new Plane(new Vector3());
  13084. this._top = new Plane(new Vector3());
  13085. this._bottom = new Plane(new Vector3());
  13086. BoundFrustum.getPlanesFromMatrix(this._matrix, this._near, this._far, this._left, this._right, this._top, this._bottom);
  13087. }
  13088. static getPlanesFromMatrix(m, np, fp, lp, rp, tp, bp) {
  13089. var matrixE = m.elements;
  13090. var m11 = matrixE[0];
  13091. var m12 = matrixE[1];
  13092. var m13 = matrixE[2];
  13093. var m14 = matrixE[3];
  13094. var m21 = matrixE[4];
  13095. var m22 = matrixE[5];
  13096. var m23 = matrixE[6];
  13097. var m24 = matrixE[7];
  13098. var m31 = matrixE[8];
  13099. var m32 = matrixE[9];
  13100. var m33 = matrixE[10];
  13101. var m34 = matrixE[11];
  13102. var m41 = matrixE[12];
  13103. var m42 = matrixE[13];
  13104. var m43 = matrixE[14];
  13105. var m44 = matrixE[15];
  13106. var nearNorE = np.normal;
  13107. nearNorE.x = m13;
  13108. nearNorE.y = m23;
  13109. nearNorE.z = m33;
  13110. np.distance = m43;
  13111. np.normalize();
  13112. var farNorE = fp.normal;
  13113. farNorE.x = m14 - m13;
  13114. farNorE.y = m24 - m23;
  13115. farNorE.z = m34 - m33;
  13116. fp.distance = m44 - m43;
  13117. fp.normalize();
  13118. var leftNorE = lp.normal;
  13119. leftNorE.x = m14 + m11;
  13120. leftNorE.y = m24 + m21;
  13121. leftNorE.z = m34 + m31;
  13122. lp.distance = m44 + m41;
  13123. lp.normalize();
  13124. var rightNorE = rp.normal;
  13125. rightNorE.x = m14 - m11;
  13126. rightNorE.y = m24 - m21;
  13127. rightNorE.z = m34 - m31;
  13128. rp.distance = m44 - m41;
  13129. rp.normalize();
  13130. var topNorE = tp.normal;
  13131. topNorE.x = m14 - m12;
  13132. topNorE.y = m24 - m22;
  13133. topNorE.z = m34 - m32;
  13134. tp.distance = m44 - m42;
  13135. tp.normalize();
  13136. var bottomNorE = bp.normal;
  13137. bottomNorE.x = m14 + m12;
  13138. bottomNorE.y = m24 + m22;
  13139. bottomNorE.z = m34 + m32;
  13140. bp.distance = m44 + m42;
  13141. bp.normalize();
  13142. }
  13143. get matrix() {
  13144. return this._matrix;
  13145. }
  13146. set matrix(matrix) {
  13147. matrix.cloneTo(this._matrix);
  13148. BoundFrustum.getPlanesFromMatrix(this._matrix, this._near, this._far, this._left, this._right, this._top, this._bottom);
  13149. }
  13150. get near() {
  13151. return this._near;
  13152. }
  13153. get far() {
  13154. return this._far;
  13155. }
  13156. get left() {
  13157. return this._left;
  13158. }
  13159. get right() {
  13160. return this._right;
  13161. }
  13162. get top() {
  13163. return this._top;
  13164. }
  13165. get bottom() {
  13166. return this._bottom;
  13167. }
  13168. equalsBoundFrustum(other) {
  13169. return this._matrix.equalsOtherMatrix(other.matrix);
  13170. }
  13171. equalsObj(obj) {
  13172. if (obj instanceof BoundFrustum) {
  13173. var bf = obj;
  13174. return this.equalsBoundFrustum(bf);
  13175. }
  13176. return false;
  13177. }
  13178. getPlane(index) {
  13179. switch (index) {
  13180. case 0:
  13181. return this._near;
  13182. case 1:
  13183. return this._far;
  13184. case 2:
  13185. return this._left;
  13186. case 3:
  13187. return this._right;
  13188. case 4:
  13189. return this._top;
  13190. case 5:
  13191. return this._bottom;
  13192. default:
  13193. return null;
  13194. }
  13195. }
  13196. static get3PlaneInterPoint(p1, p2, p3, out) {
  13197. var p1Nor = p1.normal;
  13198. var p2Nor = p2.normal;
  13199. var p3Nor = p3.normal;
  13200. Vector3.cross(p2Nor, p3Nor, BoundFrustum._tempV30);
  13201. Vector3.cross(p3Nor, p1Nor, BoundFrustum._tempV31);
  13202. Vector3.cross(p1Nor, p2Nor, BoundFrustum._tempV32);
  13203. var a = Vector3.dot(p1Nor, BoundFrustum._tempV30);
  13204. var b = Vector3.dot(p2Nor, BoundFrustum._tempV31);
  13205. var c = Vector3.dot(p3Nor, BoundFrustum._tempV32);
  13206. Vector3.scale(BoundFrustum._tempV30, -p1.distance / a, BoundFrustum._tempV33);
  13207. Vector3.scale(BoundFrustum._tempV31, -p2.distance / b, BoundFrustum._tempV34);
  13208. Vector3.scale(BoundFrustum._tempV32, -p3.distance / c, BoundFrustum._tempV35);
  13209. Vector3.add(BoundFrustum._tempV33, BoundFrustum._tempV34, BoundFrustum._tempV36);
  13210. Vector3.add(BoundFrustum._tempV35, BoundFrustum._tempV36, out);
  13211. }
  13212. getCorners(corners) {
  13213. BoundFrustum.get3PlaneInterPoint(this._near, this._bottom, this._right, corners[exports.FrustumCorner.nearBottomRight]);
  13214. BoundFrustum.get3PlaneInterPoint(this._near, this._top, this._right, corners[exports.FrustumCorner.nearTopRight]);
  13215. BoundFrustum.get3PlaneInterPoint(this._near, this._top, this._left, corners[exports.FrustumCorner.nearTopLeft]);
  13216. BoundFrustum.get3PlaneInterPoint(this._near, this._bottom, this._left, corners[exports.FrustumCorner.nearBottomLeft]);
  13217. BoundFrustum.get3PlaneInterPoint(this._far, this._bottom, this._right, corners[exports.FrustumCorner.FarBottomRight]);
  13218. BoundFrustum.get3PlaneInterPoint(this._far, this._top, this._right, corners[exports.FrustumCorner.FarTopRight]);
  13219. BoundFrustum.get3PlaneInterPoint(this._far, this._top, this._left, corners[exports.FrustumCorner.FarTopLeft]);
  13220. BoundFrustum.get3PlaneInterPoint(this._far, this._bottom, this._left, corners[exports.FrustumCorner.FarBottomLeft]);
  13221. }
  13222. containsPoint(point) {
  13223. var result = Plane.PlaneIntersectionType_Front;
  13224. var planeResult = Plane.PlaneIntersectionType_Front;
  13225. for (var i = 0; i < 6; i++) {
  13226. switch (i) {
  13227. case 0:
  13228. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._near, point);
  13229. break;
  13230. case 1:
  13231. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._far, point);
  13232. break;
  13233. case 2:
  13234. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._left, point);
  13235. break;
  13236. case 3:
  13237. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._right, point);
  13238. break;
  13239. case 4:
  13240. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._top, point);
  13241. break;
  13242. case 5:
  13243. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._bottom, point);
  13244. break;
  13245. }
  13246. switch (planeResult) {
  13247. case Plane.PlaneIntersectionType_Back:
  13248. return ContainmentType.Disjoint;
  13249. case Plane.PlaneIntersectionType_Intersecting:
  13250. result = Plane.PlaneIntersectionType_Intersecting;
  13251. break;
  13252. }
  13253. }
  13254. switch (result) {
  13255. case Plane.PlaneIntersectionType_Intersecting:
  13256. return ContainmentType.Intersects;
  13257. default:
  13258. return ContainmentType.Contains;
  13259. }
  13260. }
  13261. intersects(box) {
  13262. var min = box.min;
  13263. var max = box.max;
  13264. var minX = min.x;
  13265. var minY = min.y;
  13266. var minZ = min.z;
  13267. var maxX = max.x;
  13268. var maxY = max.y;
  13269. var maxZ = max.z;
  13270. var nearNormal = this._near.normal;
  13271. 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)
  13272. return false;
  13273. var leftNormal = this._left.normal;
  13274. 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)
  13275. return false;
  13276. var rightNormal = this._right.normal;
  13277. 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)
  13278. return false;
  13279. var bottomNormal = this._bottom.normal;
  13280. 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)
  13281. return false;
  13282. var topNormal = this._top.normal;
  13283. 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)
  13284. return false;
  13285. var farNormal = this._far.normal;
  13286. 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)
  13287. return false;
  13288. return true;
  13289. }
  13290. containsBoundBox(box) {
  13291. var p = BoundFrustum._tempV30, n = BoundFrustum._tempV31;
  13292. var boxMin = box.min;
  13293. var boxMax = box.max;
  13294. var result = ContainmentType.Contains;
  13295. for (var i = 0; i < 6; i++) {
  13296. var plane = this.getPlane(i);
  13297. var planeNor = plane.normal;
  13298. if (planeNor.x >= 0) {
  13299. p.x = boxMax.x;
  13300. n.x = boxMin.x;
  13301. }
  13302. else {
  13303. p.x = boxMin.x;
  13304. n.x = boxMax.x;
  13305. }
  13306. if (planeNor.y >= 0) {
  13307. p.y = boxMax.y;
  13308. n.y = boxMin.y;
  13309. }
  13310. else {
  13311. p.y = boxMin.y;
  13312. n.y = boxMax.y;
  13313. }
  13314. if (planeNor.z >= 0) {
  13315. p.z = boxMax.z;
  13316. n.z = boxMin.z;
  13317. }
  13318. else {
  13319. p.z = boxMin.z;
  13320. n.z = boxMax.z;
  13321. }
  13322. if (CollisionUtils.intersectsPlaneAndPoint(plane, p) === Plane.PlaneIntersectionType_Back)
  13323. return ContainmentType.Disjoint;
  13324. if (CollisionUtils.intersectsPlaneAndPoint(plane, n) === Plane.PlaneIntersectionType_Back)
  13325. result = ContainmentType.Intersects;
  13326. }
  13327. return result;
  13328. }
  13329. containsBoundSphere(sphere) {
  13330. var result = Plane.PlaneIntersectionType_Front;
  13331. var planeResult = Plane.PlaneIntersectionType_Front;
  13332. for (var i = 0; i < 6; i++) {
  13333. switch (i) {
  13334. case 0:
  13335. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._near, sphere);
  13336. break;
  13337. case 1:
  13338. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._far, sphere);
  13339. break;
  13340. case 2:
  13341. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._left, sphere);
  13342. break;
  13343. case 3:
  13344. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._right, sphere);
  13345. break;
  13346. case 4:
  13347. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._top, sphere);
  13348. break;
  13349. case 5:
  13350. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._bottom, sphere);
  13351. break;
  13352. }
  13353. switch (planeResult) {
  13354. case Plane.PlaneIntersectionType_Back:
  13355. return ContainmentType.Disjoint;
  13356. case Plane.PlaneIntersectionType_Intersecting:
  13357. result = Plane.PlaneIntersectionType_Intersecting;
  13358. break;
  13359. }
  13360. }
  13361. switch (result) {
  13362. case Plane.PlaneIntersectionType_Intersecting:
  13363. return ContainmentType.Intersects;
  13364. default:
  13365. return ContainmentType.Contains;
  13366. }
  13367. }
  13368. }
  13369. BoundFrustum._tempV30 = new Vector3();
  13370. BoundFrustum._tempV31 = new Vector3();
  13371. BoundFrustum._tempV32 = new Vector3();
  13372. BoundFrustum._tempV33 = new Vector3();
  13373. BoundFrustum._tempV34 = new Vector3();
  13374. BoundFrustum._tempV35 = new Vector3();
  13375. BoundFrustum._tempV36 = new Vector3();
  13376. class Viewport {
  13377. constructor(x, y, width, height) {
  13378. this.minDepth = 0.0;
  13379. this.maxDepth = 1.0;
  13380. this.x = x;
  13381. this.y = y;
  13382. this.width = width;
  13383. this.height = height;
  13384. }
  13385. project(source, matrix, out) {
  13386. Vector3.transformV3ToV4(source, matrix, out);
  13387. var x = out.x, y = out.y, z = out.z;
  13388. var w = out.w;
  13389. if (w !== 1.0) {
  13390. x = x / w;
  13391. y = y / w;
  13392. z = z / w;
  13393. }
  13394. out.x = (x + 1.0) * 0.5 * this.width + this.x;
  13395. out.y = (-y + 1.0) * 0.5 * this.height + this.y;
  13396. out.z = z * (this.maxDepth - this.minDepth) + this.minDepth;
  13397. }
  13398. unprojectFromMat(source, matrix, out) {
  13399. var matrixEleme = matrix.elements;
  13400. out.x = (((source.x - this.x) / this.width) * 2.0) - 1.0;
  13401. out.y = -((((source.y - this.y) / this.height) * 2.0) - 1.0);
  13402. out.z = (source.z - this.minDepth) / (this.maxDepth - this.minDepth);
  13403. var a = (((out.x * matrixEleme[3]) + (out.y * matrixEleme[7])) + (out.z * matrixEleme[11])) + matrixEleme[15];
  13404. Vector3.transformV3ToV3(out, matrix, out);
  13405. if (a !== 1.0) {
  13406. out.x = out.x / a;
  13407. out.y = out.y / a;
  13408. out.z = out.z / a;
  13409. }
  13410. }
  13411. unprojectFromWVP(source, projection, view, world, out) {
  13412. Matrix4x4.multiply(projection, view, Viewport._tempMatrix4x4);
  13413. (world) && (Matrix4x4.multiply(Viewport._tempMatrix4x4, world, Viewport._tempMatrix4x4));
  13414. Viewport._tempMatrix4x4.invert(Viewport._tempMatrix4x4);
  13415. this.unprojectFromMat(source, Viewport._tempMatrix4x4, out);
  13416. }
  13417. cloneTo(out) {
  13418. out.x = this.x;
  13419. out.y = this.y;
  13420. out.width = this.width;
  13421. out.height = this.height;
  13422. out.minDepth = this.minDepth;
  13423. out.maxDepth = this.maxDepth;
  13424. }
  13425. }
  13426. Viewport._tempMatrix4x4 = new Matrix4x4();
  13427. class Picker {
  13428. constructor() {
  13429. }
  13430. static calculateCursorRay(point, viewPort, projectionMatrix, viewMatrix, world, out) {
  13431. var x = point.x;
  13432. var y = point.y;
  13433. var nearSource = Picker._tempVector30;
  13434. var nerSourceE = nearSource;
  13435. nerSourceE.x = x;
  13436. nerSourceE.y = y;
  13437. nerSourceE.z = viewPort.minDepth;
  13438. var farSource = Picker._tempVector31;
  13439. var farSourceE = farSource;
  13440. farSourceE.x = x;
  13441. farSourceE.y = y;
  13442. farSourceE.z = viewPort.maxDepth;
  13443. var nearPoint = out.origin;
  13444. var farPoint = Picker._tempVector32;
  13445. viewPort.unprojectFromWVP(nearSource, projectionMatrix, viewMatrix, world, nearPoint);
  13446. viewPort.unprojectFromWVP(farSource, projectionMatrix, viewMatrix, world, farPoint);
  13447. var outDire = out.direction;
  13448. outDire.x = farPoint.x - nearPoint.x;
  13449. outDire.y = farPoint.y - nearPoint.y;
  13450. outDire.z = farPoint.z - nearPoint.z;
  13451. Vector3.normalize(out.direction, out.direction);
  13452. }
  13453. static rayIntersectsTriangle(ray, vertex1, vertex2, vertex3) {
  13454. var result;
  13455. var edge1 = Picker._tempVector30, edge2 = Picker._tempVector31;
  13456. Vector3.subtract(vertex2, vertex1, edge1);
  13457. Vector3.subtract(vertex3, vertex1, edge2);
  13458. var directionCrossEdge2 = Picker._tempVector32;
  13459. Vector3.cross(ray.direction, edge2, directionCrossEdge2);
  13460. var determinant;
  13461. determinant = Vector3.dot(edge1, directionCrossEdge2);
  13462. if (determinant > -Number.MIN_VALUE && determinant < Number.MIN_VALUE) {
  13463. result = Number.NaN;
  13464. return result;
  13465. }
  13466. var inverseDeterminant = 1.0 / determinant;
  13467. var distanceVector = Picker._tempVector33;
  13468. Vector3.subtract(ray.origin, vertex1, distanceVector);
  13469. var triangleU;
  13470. triangleU = Vector3.dot(distanceVector, directionCrossEdge2);
  13471. triangleU *= inverseDeterminant;
  13472. if (triangleU < 0 || triangleU > 1) {
  13473. result = Number.NaN;
  13474. return result;
  13475. }
  13476. var distanceCrossEdge1 = Picker._tempVector34;
  13477. Vector3.cross(distanceVector, edge1, distanceCrossEdge1);
  13478. var triangleV;
  13479. triangleV = Vector3.dot(ray.direction, distanceCrossEdge1);
  13480. triangleV *= inverseDeterminant;
  13481. if (triangleV < 0 || triangleU + triangleV > 1) {
  13482. result = Number.NaN;
  13483. return result;
  13484. }
  13485. var rayDistance;
  13486. rayDistance = Vector3.dot(edge2, distanceCrossEdge1);
  13487. rayDistance *= inverseDeterminant;
  13488. if (rayDistance < 0) {
  13489. result = Number.NaN;
  13490. return result;
  13491. }
  13492. result = rayDistance;
  13493. return result;
  13494. }
  13495. }
  13496. Picker._tempVector30 = new Vector3();
  13497. Picker._tempVector31 = new Vector3();
  13498. Picker._tempVector32 = new Vector3();
  13499. Picker._tempVector33 = new Vector3();
  13500. Picker._tempVector34 = new Vector3();
  13501. class BufferState extends Laya.BufferStateBase {
  13502. constructor() {
  13503. super();
  13504. }
  13505. applyVertexBuffer(vertexBuffer) {
  13506. if (Laya.BufferStateBase._curBindedBufferState === this) {
  13507. var gl = Laya.LayaGL.instance;
  13508. var verDec = vertexBuffer.vertexDeclaration;
  13509. var valueData = verDec._shaderValues.getData();
  13510. this.vertexDeclaration = verDec;
  13511. vertexBuffer.bind();
  13512. for (var k in valueData) {
  13513. var loc = parseInt(k);
  13514. var attribute = valueData[k];
  13515. gl.enableVertexAttribArray(loc);
  13516. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  13517. }
  13518. }
  13519. else {
  13520. throw "BufferState: must call bind() function first.";
  13521. }
  13522. }
  13523. applyVertexBuffers(vertexBuffers) {
  13524. if (Laya.BufferStateBase._curBindedBufferState === this) {
  13525. var gl = Laya.LayaGL.instance;
  13526. for (var i = 0, n = vertexBuffers.length; i < n; i++) {
  13527. var verBuf = vertexBuffers[i];
  13528. var verDec = verBuf.vertexDeclaration;
  13529. var valueData = verDec._shaderValues.getData();
  13530. verBuf.bind();
  13531. for (var k in valueData) {
  13532. var loc = parseInt(k);
  13533. var attribute = valueData[k];
  13534. gl.enableVertexAttribArray(loc);
  13535. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  13536. }
  13537. }
  13538. }
  13539. else {
  13540. throw "BufferState: must call bind() function first.";
  13541. }
  13542. }
  13543. applyInstanceVertexBuffer(vertexBuffer) {
  13544. if (Laya.LayaGL.layaGPUInstance.supportInstance()) {
  13545. if (Laya.BufferStateBase._curBindedBufferState === this) {
  13546. var gl = Laya.LayaGL.instance;
  13547. var verDec = vertexBuffer.vertexDeclaration;
  13548. var valueData = verDec._shaderValues.getData();
  13549. vertexBuffer.bind();
  13550. for (var k in valueData) {
  13551. var loc = parseInt(k);
  13552. var attribute = valueData[k];
  13553. gl.enableVertexAttribArray(loc);
  13554. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  13555. Laya.LayaGL.layaGPUInstance.vertexAttribDivisor(loc, 1);
  13556. }
  13557. }
  13558. else {
  13559. throw "BufferState: must call bind() function first.";
  13560. }
  13561. }
  13562. }
  13563. applyIndexBuffer(indexBuffer) {
  13564. if (Laya.BufferStateBase._curBindedBufferState === this) {
  13565. if (this._bindedIndexBuffer !== indexBuffer) {
  13566. indexBuffer._bindForVAO();
  13567. this._bindedIndexBuffer = indexBuffer;
  13568. }
  13569. }
  13570. else {
  13571. throw "BufferState: must call bind() function first.";
  13572. }
  13573. }
  13574. }
  13575. (function (IndexFormat) {
  13576. IndexFormat[IndexFormat["UInt8"] = 0] = "UInt8";
  13577. IndexFormat[IndexFormat["UInt16"] = 1] = "UInt16";
  13578. IndexFormat[IndexFormat["UInt32"] = 2] = "UInt32";
  13579. })(exports.IndexFormat || (exports.IndexFormat = {}));
  13580. class IndexBuffer3D extends Laya.Buffer {
  13581. constructor(indexType, indexCount, bufferUsage = 0x88E4, canRead = false) {
  13582. super();
  13583. this._indexType = indexType;
  13584. this._indexCount = indexCount;
  13585. this._bufferUsage = bufferUsage;
  13586. this._bufferType = Laya.LayaGL.instance.ELEMENT_ARRAY_BUFFER;
  13587. this._canRead = canRead;
  13588. switch (indexType) {
  13589. case exports.IndexFormat.UInt32:
  13590. this._indexTypeByteCount = 4;
  13591. break;
  13592. case exports.IndexFormat.UInt16:
  13593. this._indexTypeByteCount = 2;
  13594. break;
  13595. case exports.IndexFormat.UInt8:
  13596. this._indexTypeByteCount = 1;
  13597. break;
  13598. default:
  13599. throw new Error("unidentification index type.");
  13600. }
  13601. var byteLength = this._indexTypeByteCount * indexCount;
  13602. var curBufSta = Laya.BufferStateBase._curBindedBufferState;
  13603. this._byteLength = byteLength;
  13604. if (curBufSta) {
  13605. if (curBufSta._bindedIndexBuffer === this) {
  13606. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  13607. }
  13608. else {
  13609. curBufSta.unBind();
  13610. this.bind();
  13611. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  13612. curBufSta.bind();
  13613. }
  13614. }
  13615. else {
  13616. this.bind();
  13617. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  13618. }
  13619. if (canRead) {
  13620. switch (indexType) {
  13621. case exports.IndexFormat.UInt32:
  13622. this._buffer = new Uint32Array(indexCount);
  13623. break;
  13624. case exports.IndexFormat.UInt16:
  13625. this._buffer = new Uint16Array(indexCount);
  13626. break;
  13627. case exports.IndexFormat.UInt8:
  13628. this._buffer = new Uint8Array(indexCount);
  13629. break;
  13630. }
  13631. }
  13632. }
  13633. get indexType() {
  13634. return this._indexType;
  13635. }
  13636. get indexTypeByteCount() {
  13637. return this._indexTypeByteCount;
  13638. }
  13639. get indexCount() {
  13640. return this._indexCount;
  13641. }
  13642. get canRead() {
  13643. return this._canRead;
  13644. }
  13645. _bindForVAO() {
  13646. if (Laya.BufferStateBase._curBindedBufferState) {
  13647. var gl = Laya.LayaGL.instance;
  13648. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
  13649. }
  13650. else {
  13651. throw "IndexBuffer3D: must bind current BufferState.";
  13652. }
  13653. }
  13654. bind() {
  13655. if (Laya.BufferStateBase._curBindedBufferState) {
  13656. throw "IndexBuffer3D: must unbind current BufferState.";
  13657. }
  13658. else {
  13659. if (Laya.Buffer._bindedIndexBuffer !== this._glBuffer) {
  13660. var gl = Laya.LayaGL.instance;
  13661. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
  13662. Laya.Buffer._bindedIndexBuffer = this._glBuffer;
  13663. return true;
  13664. }
  13665. else {
  13666. return false;
  13667. }
  13668. }
  13669. }
  13670. setData(data, bufferOffset = 0, dataStartIndex = 0, dataCount = 4294967295) {
  13671. var byteCount = this._indexTypeByteCount;
  13672. if (dataStartIndex !== 0 || dataCount !== 4294967295) {
  13673. switch (this._indexType) {
  13674. case exports.IndexFormat.UInt32:
  13675. data = new Uint32Array(data.buffer, dataStartIndex * byteCount, dataCount);
  13676. break;
  13677. case exports.IndexFormat.UInt16:
  13678. data = new Uint16Array(data.buffer, dataStartIndex * byteCount, dataCount);
  13679. break;
  13680. case exports.IndexFormat.UInt8:
  13681. data = new Uint8Array(data.buffer, dataStartIndex * byteCount, dataCount);
  13682. break;
  13683. }
  13684. }
  13685. var curBufSta = Laya.BufferStateBase._curBindedBufferState;
  13686. if (curBufSta) {
  13687. if (curBufSta._bindedIndexBuffer === this) {
  13688. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  13689. }
  13690. else {
  13691. curBufSta.unBind();
  13692. this.bind();
  13693. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  13694. curBufSta.bind();
  13695. }
  13696. }
  13697. else {
  13698. this.bind();
  13699. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  13700. }
  13701. if (this._canRead) {
  13702. if (bufferOffset !== 0 || dataStartIndex !== 0 || dataCount !== 4294967295) {
  13703. var maxLength = this._buffer.length - bufferOffset;
  13704. if (dataCount > maxLength)
  13705. dataCount = maxLength;
  13706. for (var i = 0; i < dataCount; i++)
  13707. this._buffer[bufferOffset + i] = data[i];
  13708. }
  13709. else {
  13710. this._buffer = data;
  13711. }
  13712. }
  13713. }
  13714. getData() {
  13715. if (this._canRead)
  13716. return this._buffer;
  13717. else
  13718. throw new Error("Can't read data from VertexBuffer with only write flag!");
  13719. }
  13720. destroy() {
  13721. super.destroy();
  13722. this._buffer = null;
  13723. }
  13724. }
  13725. class VertexElementFormat {
  13726. static __init__() {
  13727. var gl = Laya.LayaGL.instance;
  13728. VertexElementFormat._elementInfos = {
  13729. "single": [1, gl.FLOAT, 0],
  13730. "vector2": [2, gl.FLOAT, 0],
  13731. "vector3": [3, gl.FLOAT, 0],
  13732. "vector4": [4, gl.FLOAT, 0],
  13733. "color": [4, gl.FLOAT, 0],
  13734. "byte4": [4, gl.UNSIGNED_BYTE, 0],
  13735. "short2": [2, gl.FLOAT, 0],
  13736. "short4": [4, gl.FLOAT, 0],
  13737. "normalizedshort2": [2, gl.FLOAT, 0],
  13738. "normalizedshort4": [4, gl.FLOAT, 0],
  13739. "halfvector2": [2, gl.FLOAT, 0],
  13740. "halfvector4": [4, gl.FLOAT, 0]
  13741. };
  13742. }
  13743. static getElementInfos(element) {
  13744. var info = VertexElementFormat._elementInfos[element];
  13745. if (info)
  13746. return info;
  13747. else
  13748. throw "VertexElementFormat: this vertexElementFormat is not implement.";
  13749. }
  13750. }
  13751. VertexElementFormat.Single = "single";
  13752. VertexElementFormat.Vector2 = "vector2";
  13753. VertexElementFormat.Vector3 = "vector3";
  13754. VertexElementFormat.Vector4 = "vector4";
  13755. VertexElementFormat.Color = "color";
  13756. VertexElementFormat.Byte4 = "byte4";
  13757. VertexElementFormat.Short2 = "short2";
  13758. VertexElementFormat.Short4 = "short4";
  13759. VertexElementFormat.NormalizedShort2 = "normalizedshort2";
  13760. VertexElementFormat.NormalizedShort4 = "normalizedshort4";
  13761. VertexElementFormat.HalfVector2 = "halfvector2";
  13762. VertexElementFormat.HalfVector4 = "halfvector4";
  13763. class VertexDeclaration {
  13764. constructor(vertexStride, vertexElements) {
  13765. this._id = ++VertexDeclaration._uniqueIDCounter;
  13766. this._vertexElementsDic = {};
  13767. this._vertexStride = vertexStride;
  13768. this._vertexElements = vertexElements;
  13769. var count = vertexElements.length;
  13770. this._shaderValues = new ShaderData(null);
  13771. for (var j = 0; j < count; j++) {
  13772. var vertexElement = vertexElements[j];
  13773. var name = vertexElement._elementUsage;
  13774. this._vertexElementsDic[name] = vertexElement;
  13775. var value = new Int32Array(5);
  13776. var elmentInfo = VertexElementFormat.getElementInfos(vertexElement._elementFormat);
  13777. value[0] = elmentInfo[0];
  13778. value[1] = elmentInfo[1];
  13779. value[2] = elmentInfo[2];
  13780. value[3] = this._vertexStride;
  13781. value[4] = vertexElement._offset;
  13782. this._shaderValues.setAttribute(name, value);
  13783. }
  13784. }
  13785. get id() {
  13786. return this._id;
  13787. }
  13788. get vertexStride() {
  13789. return this._vertexStride;
  13790. }
  13791. get vertexElementCount() {
  13792. return this._vertexElements.length;
  13793. }
  13794. getVertexElementByIndex(index) {
  13795. return this._vertexElements[index];
  13796. }
  13797. getVertexElementByUsage(usage) {
  13798. return this._vertexElementsDic[usage];
  13799. }
  13800. }
  13801. VertexDeclaration._uniqueIDCounter = 1;
  13802. class VertexElement {
  13803. constructor(offset, elementFormat, elementUsage) {
  13804. this._offset = offset;
  13805. this._elementFormat = elementFormat;
  13806. this._elementUsage = elementUsage;
  13807. }
  13808. get offset() {
  13809. return this._offset;
  13810. }
  13811. get elementFormat() {
  13812. return this._elementFormat;
  13813. }
  13814. get elementUsage() {
  13815. return this._elementUsage;
  13816. }
  13817. }
  13818. class VertexMesh {
  13819. static __init__() {
  13820. VertexMesh.instanceWorldMatrixDeclaration = new VertexDeclaration(64, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW0),
  13821. new VertexElement(16, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW1),
  13822. new VertexElement(32, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW2),
  13823. new VertexElement(48, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW3)]);
  13824. VertexMesh.instanceMVPMatrixDeclaration = new VertexDeclaration(64, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW0),
  13825. new VertexElement(16, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW1),
  13826. new VertexElement(32, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW2),
  13827. new VertexElement(48, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW3)]);
  13828. }
  13829. static getVertexDeclaration(vertexFlag, compatible = true) {
  13830. var verDec = VertexMesh._vertexDeclarationMap[vertexFlag + (compatible ? "_0" : "_1")];
  13831. if (!verDec) {
  13832. var subFlags = vertexFlag.split(",");
  13833. var offset = 0;
  13834. var elements = [];
  13835. for (var i = 0, n = subFlags.length; i < n; i++) {
  13836. var element;
  13837. switch (subFlags[i]) {
  13838. case "POSITION":
  13839. element = new VertexElement(offset, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0);
  13840. offset += 12;
  13841. break;
  13842. case "NORMAL":
  13843. element = new VertexElement(offset, VertexElementFormat.Vector3, VertexMesh.MESH_NORMAL0);
  13844. offset += 12;
  13845. break;
  13846. case "COLOR":
  13847. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_COLOR0);
  13848. offset += 16;
  13849. break;
  13850. case "UV":
  13851. element = new VertexElement(offset, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE0);
  13852. offset += 8;
  13853. break;
  13854. case "UV1":
  13855. element = new VertexElement(offset, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE1);
  13856. offset += 8;
  13857. break;
  13858. case "BLENDWEIGHT":
  13859. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_BLENDWEIGHT0);
  13860. offset += 16;
  13861. break;
  13862. case "BLENDINDICES":
  13863. if (compatible) {
  13864. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_BLENDINDICES0);
  13865. offset += 16;
  13866. }
  13867. else {
  13868. element = new VertexElement(offset, VertexElementFormat.Byte4, VertexMesh.MESH_BLENDINDICES0);
  13869. offset += 4;
  13870. }
  13871. break;
  13872. case "TANGENT":
  13873. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_TANGENT0);
  13874. offset += 16;
  13875. break;
  13876. default:
  13877. throw "VertexMesh: unknown vertex flag.";
  13878. }
  13879. elements.push(element);
  13880. }
  13881. verDec = new VertexDeclaration(offset, elements);
  13882. VertexMesh._vertexDeclarationMap[vertexFlag + (compatible ? "_0" : "_1")] = verDec;
  13883. }
  13884. return verDec;
  13885. }
  13886. }
  13887. VertexMesh.MESH_POSITION0 = 0;
  13888. VertexMesh.MESH_COLOR0 = 1;
  13889. VertexMesh.MESH_TEXTURECOORDINATE0 = 2;
  13890. VertexMesh.MESH_NORMAL0 = 3;
  13891. VertexMesh.MESH_TANGENT0 = 4;
  13892. VertexMesh.MESH_BLENDINDICES0 = 5;
  13893. VertexMesh.MESH_BLENDWEIGHT0 = 6;
  13894. VertexMesh.MESH_TEXTURECOORDINATE1 = 7;
  13895. VertexMesh.MESH_WORLDMATRIX_ROW0 = 8;
  13896. VertexMesh.MESH_WORLDMATRIX_ROW1 = 9;
  13897. VertexMesh.MESH_WORLDMATRIX_ROW2 = 10;
  13898. VertexMesh.MESH_WORLDMATRIX_ROW3 = 11;
  13899. VertexMesh.MESH_MVPMATRIX_ROW0 = 12;
  13900. VertexMesh.MESH_MVPMATRIX_ROW1 = 13;
  13901. VertexMesh.MESH_MVPMATRIX_ROW2 = 14;
  13902. VertexMesh.MESH_MVPMATRIX_ROW3 = 15;
  13903. VertexMesh._vertexDeclarationMap = {};
  13904. class VertexBuffer3D extends Laya.Buffer {
  13905. constructor(byteLength, bufferUsage, canRead = false) {
  13906. super();
  13907. this._vertexDeclaration = null;
  13908. this._float32Reader = null;
  13909. var gl = Laya.LayaGL.instance;
  13910. this._bufferUsage = bufferUsage;
  13911. this._bufferType = gl.ARRAY_BUFFER;
  13912. this._canRead = canRead;
  13913. this._byteLength = byteLength;
  13914. this.bind();
  13915. gl.bufferData(this._bufferType, this._byteLength, this._bufferUsage);
  13916. if (canRead) {
  13917. this._buffer = new Uint8Array(byteLength);
  13918. this._float32Reader = new Float32Array(this._buffer.buffer);
  13919. }
  13920. }
  13921. get vertexDeclaration() {
  13922. return this._vertexDeclaration;
  13923. }
  13924. set vertexDeclaration(value) {
  13925. this._vertexDeclaration = value;
  13926. }
  13927. get canRead() {
  13928. return this._canRead;
  13929. }
  13930. bind() {
  13931. if (Laya.Buffer._bindedVertexBuffer !== this._glBuffer) {
  13932. var gl = Laya.LayaGL.instance;
  13933. gl.bindBuffer(gl.ARRAY_BUFFER, this._glBuffer);
  13934. Laya.Buffer._bindedVertexBuffer = this._glBuffer;
  13935. return true;
  13936. }
  13937. else {
  13938. return false;
  13939. }
  13940. }
  13941. orphanStorage() {
  13942. this.bind();
  13943. Laya.LayaGL.instance.bufferData(this._bufferType, this._byteLength, this._bufferUsage);
  13944. }
  13945. setData(buffer, bufferOffset = 0, dataStartIndex = 0, dataCount = Number.MAX_SAFE_INTEGER) {
  13946. this.bind();
  13947. var needSubData = dataStartIndex !== 0 || dataCount !== Number.MAX_SAFE_INTEGER;
  13948. if (needSubData) {
  13949. var subData = new Uint8Array(buffer, dataStartIndex, dataCount);
  13950. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset, subData);
  13951. if (this._canRead)
  13952. this._buffer.set(subData, bufferOffset);
  13953. }
  13954. else {
  13955. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset, buffer);
  13956. if (this._canRead)
  13957. this._buffer.set(new Uint8Array(buffer), bufferOffset);
  13958. }
  13959. }
  13960. getUint8Data() {
  13961. if (this._canRead)
  13962. return this._buffer;
  13963. else
  13964. throw new Error("Can't read data from VertexBuffer with only write flag!");
  13965. }
  13966. getFloat32Data() {
  13967. if (this._canRead)
  13968. return this._float32Reader;
  13969. else
  13970. throw new Error("Can't read data from VertexBuffer with only write flag!");
  13971. }
  13972. markAsUnreadbale() {
  13973. this._canRead = false;
  13974. this._buffer = null;
  13975. this._float32Reader = null;
  13976. }
  13977. destroy() {
  13978. super.destroy();
  13979. this._buffer = null;
  13980. this._float32Reader = null;
  13981. this._vertexDeclaration = null;
  13982. }
  13983. }
  13984. VertexBuffer3D.DATATYPE_FLOAT32ARRAY = 0;
  13985. VertexBuffer3D.DATATYPE_UINT8ARRAY = 1;
  13986. class SkyMesh {
  13987. constructor() {
  13988. }
  13989. _render(state) {
  13990. }
  13991. }
  13992. class SkyBox extends SkyMesh {
  13993. constructor() {
  13994. super();
  13995. var gl = Laya.LayaGL.instance;
  13996. var halfHeight = 1.0;
  13997. var halfWidth = 1.0;
  13998. var halfDepth = 1.0;
  13999. var vertices = new Float32Array([-halfDepth, halfHeight, -halfWidth, halfDepth, halfHeight, -halfWidth, halfDepth, halfHeight, halfWidth, -halfDepth, halfHeight, halfWidth,
  14000. -halfDepth, -halfHeight, -halfWidth, halfDepth, -halfHeight, -halfWidth, halfDepth, -halfHeight, halfWidth, -halfDepth, -halfHeight, halfWidth]);
  14001. var indices = new Uint8Array([
  14002. 0, 1, 2, 2, 3, 0,
  14003. 4, 7, 6, 6, 5, 4,
  14004. 0, 3, 7, 7, 4, 0,
  14005. 1, 5, 6, 6, 2, 1,
  14006. 3, 2, 6, 6, 7, 3,
  14007. 0, 4, 5, 5, 1, 0
  14008. ]);
  14009. var verDec = VertexMesh.getVertexDeclaration("POSITION");
  14010. this._vertexBuffer = new VertexBuffer3D(verDec.vertexStride * 8, gl.STATIC_DRAW, false);
  14011. this._vertexBuffer.vertexDeclaration = verDec;
  14012. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt8, 36, gl.STATIC_DRAW, false);
  14013. this._vertexBuffer.setData(vertices.buffer);
  14014. this._indexBuffer.setData(indices);
  14015. var bufferState = new BufferState();
  14016. bufferState.bind();
  14017. bufferState.applyVertexBuffer(this._vertexBuffer);
  14018. bufferState.applyIndexBuffer(this._indexBuffer);
  14019. bufferState.unBind();
  14020. this._bufferState = bufferState;
  14021. }
  14022. static __init__() {
  14023. SkyBox.instance = new SkyBox();
  14024. }
  14025. _render(state) {
  14026. var gl = Laya.LayaGL.instance;
  14027. gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_BYTE, 0);
  14028. Laya.Stat.trianglesFaces += 12;
  14029. Laya.Stat.renderBatches++;
  14030. }
  14031. }
  14032. class SkyRenderer {
  14033. constructor() {
  14034. this._mesh = SkyBox.instance;
  14035. }
  14036. get material() {
  14037. return this._material;
  14038. }
  14039. set material(value) {
  14040. if (this._material !== value) {
  14041. (this._material) && (this._material._removeReference());
  14042. (value) && (value._addReference());
  14043. this._material = value;
  14044. }
  14045. }
  14046. get mesh() {
  14047. return this._mesh;
  14048. }
  14049. set mesh(value) {
  14050. if (this._mesh !== value) {
  14051. this._mesh = value;
  14052. }
  14053. }
  14054. _isAvailable() {
  14055. return this._material && this._mesh ? true : false;
  14056. }
  14057. _render(context) {
  14058. if (this._material && this._mesh) {
  14059. var gl = Laya.LayaGL.instance;
  14060. var scene = context.scene;
  14061. var cameraShaderValue = context.cameraShaderValue;
  14062. var camera = context.camera;
  14063. var noteValue = ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_;
  14064. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(false);
  14065. Laya.WebGLContext.setCullFace(gl, false);
  14066. Laya.WebGLContext.setDepthFunc(gl, gl.LEQUAL);
  14067. Laya.WebGLContext.setDepthMask(gl, false);
  14068. var comDef = SkyRenderer._compileDefine;
  14069. this._material._shaderValues._defineDatas.cloneTo(comDef);
  14070. var shader = context.shader = this._material._shader.getSubShaderAt(0)._passes[0].withCompile(comDef);
  14071. var switchShader = shader.bind();
  14072. var switchShaderLoop = (Laya.Stat.loopCount !== shader._uploadMark);
  14073. var uploadScene = (shader._uploadScene !== scene) || switchShaderLoop;
  14074. if (uploadScene || switchShader) {
  14075. shader.uploadUniforms(shader._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  14076. shader._uploadScene = scene;
  14077. }
  14078. var renderTex = camera._getRenderTexture();
  14079. var uploadCamera = (shader._uploadCameraShaderValue !== cameraShaderValue) || switchShaderLoop;
  14080. if (uploadCamera || switchShader) {
  14081. var viewMatrix = SkyRenderer._tempMatrix0;
  14082. var projectionMatrix = SkyRenderer._tempMatrix1;
  14083. camera.viewMatrix.cloneTo(viewMatrix);
  14084. camera.projectionMatrix.cloneTo(projectionMatrix);
  14085. viewMatrix.setTranslationVector(Vector3._ZERO);
  14086. if (camera.orthographic)
  14087. Matrix4x4.createPerspective(camera.fieldOfView, camera.aspectRatio, camera.nearPlane, camera.farPlane, projectionMatrix);
  14088. var epsilon = 1e-6;
  14089. var yScale = 1.0 / Math.tan(3.1416 * camera.fieldOfView / 180 * 0.5);
  14090. projectionMatrix.elements[0] = yScale / camera.aspectRatio;
  14091. projectionMatrix.elements[5] = yScale;
  14092. projectionMatrix.elements[10] = epsilon - 1.0;
  14093. projectionMatrix.elements[11] = -1.0;
  14094. projectionMatrix.elements[14] = -0;
  14095. camera._applyViewProject(context, viewMatrix, projectionMatrix);
  14096. shader.uploadUniforms(shader._cameraUniformParamsMap, cameraShaderValue, uploadCamera);
  14097. shader._uploadCameraShaderValue = cameraShaderValue;
  14098. }
  14099. var uploadMaterial = (shader._uploadMaterial !== this._material) || switchShaderLoop;
  14100. if (uploadMaterial || switchShader) {
  14101. shader.uploadUniforms(shader._materialUniformParamsMap, this._material._shaderValues, uploadMaterial);
  14102. shader._uploadMaterial = this._material;
  14103. }
  14104. this._mesh._bufferState.bind();
  14105. this._mesh._render(context);
  14106. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(noteValue);
  14107. Laya.WebGLContext.setDepthFunc(gl, gl.LESS);
  14108. Laya.WebGLContext.setDepthMask(gl, true);
  14109. camera._applyViewProject(context, camera.viewMatrix, camera.projectionMatrix);
  14110. }
  14111. }
  14112. destroy() {
  14113. if (this._material) {
  14114. this._material._removeReference();
  14115. this._material = null;
  14116. }
  14117. }
  14118. }
  14119. SkyRenderer._tempMatrix0 = new Matrix4x4();
  14120. SkyRenderer._tempMatrix1 = new Matrix4x4();
  14121. SkyRenderer._compileDefine = new DefineDatas();
  14122. class Sprite3D extends Laya.Node {
  14123. constructor(name = null, isStatic = false) {
  14124. super();
  14125. this._needProcessCollisions = false;
  14126. this._needProcessTriggers = false;
  14127. this._id = ++Sprite3D._uniqueIDCounter;
  14128. this._transform = new Transform3D(this);
  14129. this._isStatic = isStatic;
  14130. this.layer = 0;
  14131. this.name = name ? name : "New Sprite3D";
  14132. }
  14133. static __init__() {
  14134. }
  14135. static instantiate(original, parent = null, worldPositionStays = true, position = null, rotation = null) {
  14136. var destSprite3D = original.clone();
  14137. (parent) && (parent.addChild(destSprite3D));
  14138. var transform = destSprite3D.transform;
  14139. if (worldPositionStays) {
  14140. var worldMatrix = transform.worldMatrix;
  14141. original.transform.worldMatrix.cloneTo(worldMatrix);
  14142. transform.worldMatrix = worldMatrix;
  14143. }
  14144. else {
  14145. (position) && (transform.position = position);
  14146. (rotation) && (transform.rotation = rotation);
  14147. }
  14148. return destSprite3D;
  14149. }
  14150. static load(url, complete) {
  14151. Laya.Laya.loader.create(url, complete, null, Sprite3D.HIERARCHY);
  14152. }
  14153. get id() {
  14154. return this._id;
  14155. }
  14156. get layer() {
  14157. return this._layer;
  14158. }
  14159. set layer(value) {
  14160. if (this._layer !== value) {
  14161. if (value >= 0 && value <= 30) {
  14162. this._layer = value;
  14163. }
  14164. else {
  14165. throw new Error("Layer value must be 0-30.");
  14166. }
  14167. }
  14168. }
  14169. get url() {
  14170. return this._url;
  14171. }
  14172. get isStatic() {
  14173. return this._isStatic;
  14174. }
  14175. get transform() {
  14176. return this._transform;
  14177. }
  14178. _setCreateURL(url) {
  14179. this._url = Laya.URL.formatURL(url);
  14180. }
  14181. _changeAnimatorsToLinkSprite3D(sprite3D, isLink, path) {
  14182. var animator = this.getComponent(Animator);
  14183. if (animator) {
  14184. if (!animator.avatar)
  14185. sprite3D._changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path);
  14186. }
  14187. if (this._parent && this._parent instanceof Sprite3D) {
  14188. path.unshift(this._parent.name);
  14189. var p = this._parent;
  14190. (p._hierarchyAnimator) && (p._changeAnimatorsToLinkSprite3D(sprite3D, isLink, path));
  14191. }
  14192. }
  14193. _setHierarchyAnimator(animator, parentAnimator) {
  14194. this._changeHierarchyAnimator(animator);
  14195. this._changeAnimatorAvatar(animator.avatar);
  14196. for (var i = 0, n = this._children.length; i < n; i++) {
  14197. var child = this._children[i];
  14198. (child._hierarchyAnimator == parentAnimator) && (child._setHierarchyAnimator(animator, parentAnimator));
  14199. }
  14200. }
  14201. _clearHierarchyAnimator(animator, parentAnimator) {
  14202. this._changeHierarchyAnimator(parentAnimator);
  14203. this._changeAnimatorAvatar(parentAnimator ? parentAnimator.avatar : null);
  14204. for (var i = 0, n = this._children.length; i < n; i++) {
  14205. var child = this._children[i];
  14206. (child._hierarchyAnimator == animator) && (child._clearHierarchyAnimator(animator, parentAnimator));
  14207. }
  14208. }
  14209. _changeHierarchyAnimatorAvatar(animator, avatar) {
  14210. this._changeAnimatorAvatar(avatar);
  14211. for (var i = 0, n = this._children.length; i < n; i++) {
  14212. var child = this._children[i];
  14213. (child._hierarchyAnimator == animator) && (child._changeHierarchyAnimatorAvatar(animator, avatar));
  14214. }
  14215. }
  14216. _changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path) {
  14217. animator._handleSpriteOwnersBySprite(isLink, path, this);
  14218. for (var i = 0, n = this._children.length; i < n; i++) {
  14219. var child = this._children[i];
  14220. var index = path.length;
  14221. path.push(child.name);
  14222. child._changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path);
  14223. path.splice(index, 1);
  14224. }
  14225. }
  14226. _changeHierarchyAnimator(animator) {
  14227. this._hierarchyAnimator = animator;
  14228. }
  14229. _changeAnimatorAvatar(avatar) {
  14230. }
  14231. _onAdded() {
  14232. if (this._parent instanceof Sprite3D) {
  14233. var parent3D = this._parent;
  14234. this.transform._setParent(parent3D.transform);
  14235. if (parent3D._hierarchyAnimator) {
  14236. (!this._hierarchyAnimator) && (this._setHierarchyAnimator(parent3D._hierarchyAnimator, null));
  14237. parent3D._changeAnimatorsToLinkSprite3D(this, true, [this.name]);
  14238. }
  14239. }
  14240. super._onAdded();
  14241. }
  14242. _onRemoved() {
  14243. super._onRemoved();
  14244. if (this._parent instanceof Sprite3D) {
  14245. var parent3D = this._parent;
  14246. this.transform._setParent(null);
  14247. if (parent3D._hierarchyAnimator) {
  14248. (this._hierarchyAnimator == parent3D._hierarchyAnimator) && (this._clearHierarchyAnimator(parent3D._hierarchyAnimator, null));
  14249. parent3D._changeAnimatorsToLinkSprite3D(this, false, [this.name]);
  14250. }
  14251. }
  14252. }
  14253. _parse(data, spriteMap) {
  14254. (data.isStatic !== undefined) && (this._isStatic = data.isStatic);
  14255. (data.active !== undefined) && (this.active = data.active);
  14256. (data.name != undefined) && (this.name = data.name);
  14257. if (data.position !== undefined) {
  14258. var loccalPosition = this.transform.localPosition;
  14259. loccalPosition.fromArray(data.position);
  14260. this.transform.localPosition = loccalPosition;
  14261. }
  14262. if (data.rotationEuler !== undefined) {
  14263. var localRotationEuler = this.transform.localRotationEuler;
  14264. localRotationEuler.fromArray(data.rotationEuler);
  14265. this.transform.localRotationEuler = localRotationEuler;
  14266. }
  14267. if (data.rotation !== undefined) {
  14268. var localRotation = this.transform.localRotation;
  14269. localRotation.fromArray(data.rotation);
  14270. this.transform.localRotation = localRotation;
  14271. }
  14272. if (data.scale !== undefined) {
  14273. var localScale = this.transform.localScale;
  14274. localScale.fromArray(data.scale);
  14275. this.transform.localScale = localScale;
  14276. }
  14277. (data.layer != undefined) && (this.layer = data.layer);
  14278. }
  14279. _cloneTo(destObject, srcRoot, dstRoot) {
  14280. if (this.destroyed)
  14281. throw new Error("Sprite3D: Can't be cloned if the Sprite3D has destroyed.");
  14282. var destSprite3D = destObject;
  14283. var trans = this._transform;
  14284. var destTrans = destSprite3D._transform;
  14285. destSprite3D.name = this.name;
  14286. destSprite3D.destroyed = this.destroyed;
  14287. destSprite3D.active = this.active;
  14288. destTrans.localPosition = trans.localPosition;
  14289. destTrans.localRotation = trans.localRotation;
  14290. destTrans.localScale = trans.localScale;
  14291. destSprite3D._isStatic = this._isStatic;
  14292. destSprite3D.layer = this.layer;
  14293. super._cloneTo(destSprite3D, srcRoot, dstRoot);
  14294. }
  14295. static _createSprite3DInstance(scrSprite) {
  14296. var node = scrSprite._create();
  14297. var children = scrSprite._children;
  14298. for (var i = 0, n = children.length; i < n; i++) {
  14299. var child = Sprite3D._createSprite3DInstance(children[i]);
  14300. node.addChild(child);
  14301. }
  14302. return node;
  14303. }
  14304. static _parseSprite3DInstance(srcRoot, dstRoot, scrSprite, dstSprite) {
  14305. var srcChildren = scrSprite._children;
  14306. var dstChildren = dstSprite._children;
  14307. for (var i = 0, n = srcChildren.length; i < n; i++)
  14308. Sprite3D._parseSprite3DInstance(srcRoot, dstRoot, srcChildren[i], dstChildren[i]);
  14309. scrSprite._cloneTo(dstSprite, srcRoot, dstRoot);
  14310. }
  14311. clone() {
  14312. var dstSprite3D = Sprite3D._createSprite3DInstance(this);
  14313. Sprite3D._parseSprite3DInstance(this, dstSprite3D, this, dstSprite3D);
  14314. return dstSprite3D;
  14315. }
  14316. destroy(destroyChild = true) {
  14317. if (this.destroyed)
  14318. return;
  14319. super.destroy(destroyChild);
  14320. this._transform = null;
  14321. this._scripts = null;
  14322. this._url && Laya.Loader.clearRes(this._url);
  14323. }
  14324. _create() {
  14325. return new Sprite3D();
  14326. }
  14327. }
  14328. Sprite3D.HIERARCHY = "HIERARCHY";
  14329. Sprite3D.WORLDMATRIX = Shader3D.propertyNameToID("u_WorldMat");
  14330. Sprite3D.MVPMATRIX = Shader3D.propertyNameToID("u_MvpMatrix");
  14331. Sprite3D._uniqueIDCounter = 0;
  14332. class BaseCamera extends Sprite3D {
  14333. constructor(nearPlane = 0.3, farPlane = 1000) {
  14334. super();
  14335. this._skyRenderer = new SkyRenderer();
  14336. this._forward = new Vector3();
  14337. this._up = new Vector3();
  14338. this.clearColor = new Vector4(100 / 255, 149 / 255, 237 / 255, 255 / 255);
  14339. this._shaderValues = new ShaderData(null);
  14340. this._fieldOfView = 60;
  14341. this._useUserProjectionMatrix = false;
  14342. this._orthographic = false;
  14343. this._orthographicVerticalSize = 10;
  14344. this.renderingOrder = 0;
  14345. this._nearPlane = nearPlane;
  14346. this._farPlane = farPlane;
  14347. this.cullingMask = 2147483647;
  14348. this.useOcclusionCulling = true;
  14349. }
  14350. get skyRenderer() {
  14351. return this._skyRenderer;
  14352. }
  14353. get fieldOfView() {
  14354. return this._fieldOfView;
  14355. }
  14356. set fieldOfView(value) {
  14357. this._fieldOfView = value;
  14358. this._calculateProjectionMatrix();
  14359. }
  14360. get nearPlane() {
  14361. return this._nearPlane;
  14362. }
  14363. set nearPlane(value) {
  14364. this._nearPlane = value;
  14365. this._calculateProjectionMatrix();
  14366. }
  14367. get farPlane() {
  14368. return this._farPlane;
  14369. }
  14370. set farPlane(vaule) {
  14371. this._farPlane = vaule;
  14372. this._calculateProjectionMatrix();
  14373. }
  14374. get orthographic() {
  14375. return this._orthographic;
  14376. }
  14377. set orthographic(vaule) {
  14378. this._orthographic = vaule;
  14379. this._calculateProjectionMatrix();
  14380. }
  14381. get orthographicVerticalSize() {
  14382. return this._orthographicVerticalSize;
  14383. }
  14384. set orthographicVerticalSize(vaule) {
  14385. this._orthographicVerticalSize = vaule;
  14386. this._calculateProjectionMatrix();
  14387. }
  14388. get renderingOrder() {
  14389. return this._renderingOrder;
  14390. }
  14391. set renderingOrder(value) {
  14392. this._renderingOrder = value;
  14393. this._sortCamerasByRenderingOrder();
  14394. }
  14395. _sortCamerasByRenderingOrder() {
  14396. if (this.displayedInStage) {
  14397. var cameraPool = this.scene._cameraPool;
  14398. var n = cameraPool.length - 1;
  14399. for (var i = 0; i < n; i++) {
  14400. if (cameraPool[i].renderingOrder > cameraPool[n].renderingOrder) {
  14401. var tempCamera = cameraPool[i];
  14402. cameraPool[i] = cameraPool[n];
  14403. cameraPool[n] = tempCamera;
  14404. }
  14405. }
  14406. }
  14407. }
  14408. _calculateProjectionMatrix() {
  14409. }
  14410. _onScreenSizeChanged() {
  14411. this._calculateProjectionMatrix();
  14412. }
  14413. _prepareCameraToRender() {
  14414. var cameraSV = this._shaderValues;
  14415. this.transform.getForward(this._forward);
  14416. this.transform.getUp(this._up);
  14417. cameraSV.setVector3(BaseCamera.CAMERAPOS, this.transform.position);
  14418. cameraSV.setVector3(BaseCamera.CAMERADIRECTION, this._forward);
  14419. cameraSV.setVector3(BaseCamera.CAMERAUP, this._up);
  14420. }
  14421. render(shader = null, replacementTag = null) {
  14422. }
  14423. addLayer(layer) {
  14424. this.cullingMask |= Math.pow(2, layer);
  14425. }
  14426. removeLayer(layer) {
  14427. this.cullingMask &= ~Math.pow(2, layer);
  14428. }
  14429. addAllLayers() {
  14430. this.cullingMask = 2147483647;
  14431. }
  14432. removeAllLayers() {
  14433. this.cullingMask = 0;
  14434. }
  14435. resetProjectionMatrix() {
  14436. this._useUserProjectionMatrix = false;
  14437. this._calculateProjectionMatrix();
  14438. }
  14439. _onActive() {
  14440. this._scene._addCamera(this);
  14441. super._onActive();
  14442. }
  14443. _onInActive() {
  14444. this._scene._removeCamera(this);
  14445. super._onInActive();
  14446. }
  14447. _parse(data, spriteMap) {
  14448. super._parse(data, spriteMap);
  14449. this.orthographic = data.orthographic;
  14450. (data.orthographicVerticalSize !== undefined) && (this.orthographicVerticalSize = data.orthographicVerticalSize);
  14451. (data.fieldOfView !== undefined) && (this.fieldOfView = data.fieldOfView);
  14452. this.nearPlane = data.nearPlane;
  14453. this.farPlane = data.farPlane;
  14454. var color = data.clearColor;
  14455. this.clearColor = new Vector4(color[0], color[1], color[2], color[3]);
  14456. var skyboxMaterial = data.skyboxMaterial;
  14457. if (skyboxMaterial) {
  14458. this._skyRenderer.material = Laya.Loader.getRes(skyboxMaterial.path);
  14459. }
  14460. }
  14461. destroy(destroyChild = true) {
  14462. this._skyRenderer.destroy();
  14463. this._skyRenderer = null;
  14464. Laya.Laya.stage.off(Laya.Event.RESIZE, this, this._onScreenSizeChanged);
  14465. super.destroy(destroyChild);
  14466. }
  14467. _create() {
  14468. return new BaseCamera();
  14469. }
  14470. }
  14471. BaseCamera._tempMatrix4x40 = new Matrix4x4();
  14472. BaseCamera.CAMERAPOS = Shader3D.propertyNameToID("u_CameraPos");
  14473. BaseCamera.VIEWMATRIX = Shader3D.propertyNameToID("u_View");
  14474. BaseCamera.PROJECTMATRIX = Shader3D.propertyNameToID("u_Projection");
  14475. BaseCamera.VIEWPROJECTMATRIX = Shader3D.propertyNameToID("u_ViewProjection");
  14476. BaseCamera.CAMERADIRECTION = Shader3D.propertyNameToID("u_CameraDirection");
  14477. BaseCamera.CAMERAUP = Shader3D.propertyNameToID("u_CameraUp");
  14478. BaseCamera.VIEWPORT = Shader3D.propertyNameToID("u_Viewport");
  14479. BaseCamera.PROJECTION_PARAMS = Shader3D.propertyNameToID("u_ProjectionParams");
  14480. BaseCamera.RENDERINGTYPE_DEFERREDLIGHTING = "DEFERREDLIGHTING";
  14481. BaseCamera.RENDERINGTYPE_FORWARDRENDERING = "FORWARDRENDERING";
  14482. BaseCamera._invertYScaleMatrix = new Matrix4x4(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  14483. BaseCamera._invertYProjectionMatrix = new Matrix4x4();
  14484. BaseCamera._invertYProjectionViewMatrix = new Matrix4x4();
  14485. BaseCamera.CLEARFLAG_SOLIDCOLOR = 0;
  14486. BaseCamera.CLEARFLAG_SKY = 1;
  14487. BaseCamera.CLEARFLAG_DEPTHONLY = 2;
  14488. BaseCamera.CLEARFLAG_NONE = 3;
  14489. (function (ShadowMode) {
  14490. ShadowMode[ShadowMode["None"] = 0] = "None";
  14491. ShadowMode[ShadowMode["Hard"] = 1] = "Hard";
  14492. ShadowMode[ShadowMode["SoftLow"] = 2] = "SoftLow";
  14493. ShadowMode[ShadowMode["SoftHigh"] = 3] = "SoftHigh";
  14494. })(exports.ShadowMode || (exports.ShadowMode = {}));
  14495. class ScreenQuad extends Laya.Resource {
  14496. constructor() {
  14497. super();
  14498. this._bufferState = new BufferState();
  14499. this._bufferStateInvertUV = new BufferState();
  14500. var gl = Laya.LayaGL.instance;
  14501. this._vertexBuffer = new VertexBuffer3D(16 * 4, gl.STATIC_DRAW, false);
  14502. this._vertexBuffer.vertexDeclaration = ScreenQuad._vertexDeclaration;
  14503. this._vertexBuffer.setData(ScreenQuad._vertices.buffer);
  14504. this._bufferState.bind();
  14505. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  14506. this._bufferState.unBind();
  14507. this._vertexBufferInvertUV = new VertexBuffer3D(16 * 4, gl.STATIC_DRAW, false);
  14508. this._vertexBufferInvertUV.vertexDeclaration = ScreenQuad._vertexDeclaration;
  14509. this._vertexBufferInvertUV.setData(ScreenQuad._verticesInvertUV.buffer);
  14510. this._bufferStateInvertUV.bind();
  14511. this._bufferStateInvertUV.applyVertexBuffer(this._vertexBufferInvertUV);
  14512. this._bufferStateInvertUV.unBind();
  14513. this._setGPUMemory(this._vertexBuffer._byteLength + this._vertexBufferInvertUV._byteLength);
  14514. }
  14515. static __init__() {
  14516. ScreenQuad._vertexDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, ScreenQuad.SCREENQUAD_POSITION_UV)]);
  14517. ScreenQuad.instance = new ScreenQuad();
  14518. ScreenQuad.instance.lock = true;
  14519. }
  14520. render() {
  14521. var gl = Laya.LayaGL.instance;
  14522. this._bufferState.bind();
  14523. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  14524. Laya.Stat.renderBatches++;
  14525. }
  14526. renderInvertUV() {
  14527. var gl = Laya.LayaGL.instance;
  14528. this._bufferStateInvertUV.bind();
  14529. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  14530. Laya.Stat.renderBatches++;
  14531. }
  14532. destroy() {
  14533. super.destroy();
  14534. this._bufferState.destroy();
  14535. this._vertexBuffer.destroy();
  14536. this._bufferStateInvertUV.destroy();
  14537. this._vertexBufferInvertUV.destroy();
  14538. this._setGPUMemory(0);
  14539. }
  14540. }
  14541. ScreenQuad.SCREENQUAD_POSITION_UV = 0;
  14542. ScreenQuad._vertices = new Float32Array([1, 1, 1, 1, 1, -1, 1, 0, -1, 1, 0, 1, -1, -1, 0, 0]);
  14543. ScreenQuad._verticesInvertUV = new Float32Array([1, 1, 1, 0, 1, -1, 1, 1, -1, 1, 0, 0, -1, -1, 0, 1]);
  14544. class ScreenTriangle extends Laya.Resource {
  14545. constructor() {
  14546. super();
  14547. this._bufferState = new BufferState();
  14548. this._bufferStateInvertUV = new BufferState();
  14549. var gl = Laya.LayaGL.instance;
  14550. this._vertexBuffer = new VertexBuffer3D(12 * 4, gl.STATIC_DRAW, false);
  14551. this._vertexBuffer.vertexDeclaration = ScreenTriangle._vertexDeclaration;
  14552. this._vertexBuffer.setData(ScreenTriangle._vertices.buffer);
  14553. this._bufferState.bind();
  14554. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  14555. this._bufferState.unBind();
  14556. this._vertexBufferInvertUV = new VertexBuffer3D(12 * 4, gl.STATIC_DRAW, false);
  14557. this._vertexBufferInvertUV.vertexDeclaration = ScreenTriangle._vertexDeclaration;
  14558. this._vertexBufferInvertUV.setData(ScreenTriangle._verticesInvertUV.buffer);
  14559. this._bufferStateInvertUV.bind();
  14560. this._bufferStateInvertUV.applyVertexBuffer(this._vertexBufferInvertUV);
  14561. this._bufferStateInvertUV.unBind();
  14562. this._setGPUMemory(this._vertexBuffer._byteLength + this._vertexBufferInvertUV._byteLength);
  14563. }
  14564. static __init__() {
  14565. ScreenTriangle._vertexDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, ScreenTriangle.SCREENTRIANGLE_POSITION_UV)]);
  14566. ScreenTriangle.instance = new ScreenTriangle();
  14567. ScreenTriangle.instance.lock = true;
  14568. }
  14569. render() {
  14570. var gl = Laya.LayaGL.instance;
  14571. this._bufferState.bind();
  14572. gl.drawArrays(gl.TRIANGLES, 0, 3);
  14573. Laya.Stat.renderBatches++;
  14574. }
  14575. renderInvertUV() {
  14576. var gl = Laya.LayaGL.instance;
  14577. this._bufferStateInvertUV.bind();
  14578. gl.drawArrays(gl.TRIANGLES, 0, 3);
  14579. Laya.Stat.renderBatches++;
  14580. }
  14581. destroy() {
  14582. super.destroy();
  14583. this._bufferState.destroy();
  14584. this._vertexBuffer.destroy();
  14585. this._bufferStateInvertUV.destroy();
  14586. this._vertexBufferInvertUV.destroy();
  14587. this._setGPUMemory(0);
  14588. }
  14589. }
  14590. ScreenTriangle.SCREENTRIANGLE_POSITION_UV = 0;
  14591. ScreenTriangle._vertices = new Float32Array([-1, -1, 0, 0, -1, 3, 0, 2, 3, -1, 2, 0]);
  14592. ScreenTriangle._verticesInvertUV = new Float32Array([-1, -1, 0, 1, -1, 3, 0, -1, 3, -1, 2, 1]);
  14593. class Command {
  14594. constructor() {
  14595. this._commandBuffer = null;
  14596. }
  14597. static __init__() {
  14598. Command._screenShaderData = new ShaderData();
  14599. Command._screenShader = Shader3D.find("BlitScreen");
  14600. }
  14601. run() {
  14602. }
  14603. recover() {
  14604. this._commandBuffer = null;
  14605. }
  14606. }
  14607. Command.SCREENTEXTURE_NAME = "u_MainTex";
  14608. Command.SCREENTEXTUREOFFSETSCALE_NAME = "u_OffsetScale";
  14609. Command.MAINTEXTURE_TEXELSIZE_NAME = "u_MainTex_TexelSize";
  14610. Command.SCREENTEXTURE_ID = Shader3D.propertyNameToID(Command.SCREENTEXTURE_NAME);
  14611. Command.SCREENTEXTUREOFFSETSCALE_ID = Shader3D.propertyNameToID(Command.SCREENTEXTUREOFFSETSCALE_NAME);
  14612. Command.MAINTEXTURE_TEXELSIZE_ID = Shader3D.propertyNameToID(Command.MAINTEXTURE_TEXELSIZE_NAME);
  14613. class BlitScreenQuadCMD extends Command {
  14614. constructor() {
  14615. super(...arguments);
  14616. this._source = null;
  14617. this._dest = null;
  14618. this._offsetScale = null;
  14619. this._shader = null;
  14620. this._shaderData = null;
  14621. this._subShader = 0;
  14622. this._sourceTexelSize = new Vector4();
  14623. this._screenType = 0;
  14624. }
  14625. static create(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0, screenType = BlitScreenQuadCMD._SCREENTYPE_QUAD) {
  14626. var cmd;
  14627. cmd = BlitScreenQuadCMD._pool.length > 0 ? BlitScreenQuadCMD._pool.pop() : new BlitScreenQuadCMD();
  14628. cmd._source = source;
  14629. cmd._dest = dest;
  14630. cmd._offsetScale = offsetScale;
  14631. cmd._shader = shader;
  14632. cmd._shaderData = shaderData;
  14633. cmd._subShader = subShader;
  14634. cmd._screenType = screenType;
  14635. return cmd;
  14636. }
  14637. run() {
  14638. var shader = this._shader || Command._screenShader;
  14639. var shaderData = this._shaderData || Command._screenShaderData;
  14640. var dest = this._dest;
  14641. Laya.LayaGL.instance.viewport(0, 0, dest ? dest.width : RenderContext3D.clientWidth, dest ? dest.height : RenderContext3D.clientHeight);
  14642. shaderData.setTexture(Command.SCREENTEXTURE_ID, this._source);
  14643. shaderData.setVector(Command.SCREENTEXTUREOFFSETSCALE_ID, this._offsetScale || BlitScreenQuadCMD._defaultOffsetScale);
  14644. this._sourceTexelSize.setValue(1.0 / this._source.width, 1.0 / this._source.height, this._source.width, this._source.height);
  14645. shaderData.setVector(Command.MAINTEXTURE_TEXELSIZE_ID, this._sourceTexelSize);
  14646. (dest) && (dest._start());
  14647. var subShader = shader.getSubShaderAt(this._subShader);
  14648. var passes = subShader._passes;
  14649. for (var i = 0, n = passes.length; i < n; i++) {
  14650. var comDef = BlitScreenQuadCMD._compileDefine;
  14651. shaderData._defineDatas.cloneTo(comDef);
  14652. var shaderPass = passes[i].withCompile(comDef);
  14653. shaderPass.bind();
  14654. shaderPass.uploadUniforms(shaderPass._materialUniformParamsMap, shaderData, true);
  14655. shaderPass.uploadRenderStateBlendDepth(shaderData);
  14656. shaderPass.uploadRenderStateFrontFace(shaderData, false, null);
  14657. switch (this._screenType) {
  14658. case BlitScreenQuadCMD._SCREENTYPE_QUAD:
  14659. RenderContext3D._instance.invertY ? ScreenQuad.instance.renderInvertUV() : ScreenQuad.instance.render();
  14660. break;
  14661. case BlitScreenQuadCMD._SCREENTYPE_TRIANGLE:
  14662. RenderContext3D._instance.invertY ? ScreenTriangle.instance.renderInvertUV() : ScreenTriangle.instance.render();
  14663. break;
  14664. default:
  14665. throw "BlitScreenQuadCMD:unknown screen Type.";
  14666. }
  14667. }
  14668. (dest) && (dest._end());
  14669. }
  14670. recover() {
  14671. BlitScreenQuadCMD._pool.push(this);
  14672. this._source = null;
  14673. this._dest = null;
  14674. this._offsetScale = null;
  14675. this._shader = null;
  14676. this._shaderData = null;
  14677. super.recover();
  14678. }
  14679. }
  14680. BlitScreenQuadCMD._SCREENTYPE_QUAD = 0;
  14681. BlitScreenQuadCMD._SCREENTYPE_TRIANGLE = 1;
  14682. BlitScreenQuadCMD._compileDefine = new DefineDatas();
  14683. BlitScreenQuadCMD._pool = [];
  14684. BlitScreenQuadCMD._defaultOffsetScale = new Vector4(0, 0, 1, 1);
  14685. class SetRenderTargetCMD extends Command {
  14686. constructor() {
  14687. super(...arguments);
  14688. this._renderTexture = null;
  14689. }
  14690. static create(renderTexture) {
  14691. var cmd;
  14692. cmd = SetRenderTargetCMD._pool.length > 0 ? SetRenderTargetCMD._pool.pop() : new SetRenderTargetCMD();
  14693. cmd._renderTexture = renderTexture;
  14694. return cmd;
  14695. }
  14696. run() {
  14697. this._renderTexture._start();
  14698. }
  14699. recover() {
  14700. SetRenderTargetCMD._pool.push(this);
  14701. this._renderTexture = null;
  14702. }
  14703. }
  14704. SetRenderTargetCMD._pool = [];
  14705. class SetShaderDataTextureCMD extends Command {
  14706. constructor() {
  14707. super(...arguments);
  14708. this._shaderData = null;
  14709. this._nameID = 0;
  14710. this._texture = null;
  14711. }
  14712. static create(shaderData, nameID, texture) {
  14713. var cmd;
  14714. cmd = SetShaderDataTextureCMD._pool.length > 0 ? SetShaderDataTextureCMD._pool.pop() : new SetShaderDataTextureCMD();
  14715. cmd._shaderData = shaderData;
  14716. cmd._nameID = nameID;
  14717. cmd._texture = texture;
  14718. return cmd;
  14719. }
  14720. run() {
  14721. this._shaderData.setTexture(this._nameID, this._texture);
  14722. }
  14723. recover() {
  14724. SetShaderDataTextureCMD._pool.push(this);
  14725. this._shaderData = null;
  14726. this._nameID = 0;
  14727. this._texture = null;
  14728. }
  14729. }
  14730. SetShaderDataTextureCMD._pool = [];
  14731. class CommandBuffer {
  14732. constructor() {
  14733. this._camera = null;
  14734. this._commands = [];
  14735. }
  14736. _apply() {
  14737. for (var i = 0, n = this._commands.length; i < n; i++)
  14738. this._commands[i].run();
  14739. }
  14740. setShaderDataTexture(shaderData, nameID, source) {
  14741. this._commands.push(SetShaderDataTextureCMD.create(shaderData, nameID, source));
  14742. }
  14743. blitScreenQuad(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0) {
  14744. this._commands.push(BlitScreenQuadCMD.create(source, dest, offsetScale, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_QUAD));
  14745. }
  14746. blitScreenTriangle(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0) {
  14747. this._commands.push(BlitScreenQuadCMD.create(source, dest, offsetScale, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_TRIANGLE));
  14748. }
  14749. setRenderTarget(renderTexture) {
  14750. this._commands.push(SetRenderTargetCMD.create(renderTexture));
  14751. }
  14752. clear() {
  14753. for (var i = 0, n = this._commands.length; i < n; i++)
  14754. this._commands[i].recover();
  14755. this._commands.length = 0;
  14756. }
  14757. }
  14758. class Scene3DShaderDeclaration {
  14759. }
  14760. (function (LightType) {
  14761. LightType[LightType["Directional"] = 0] = "Directional";
  14762. LightType[LightType["Spot"] = 1] = "Spot";
  14763. LightType[LightType["Point"] = 2] = "Point";
  14764. })(exports.LightType || (exports.LightType = {}));
  14765. class LightSprite extends Sprite3D {
  14766. constructor() {
  14767. super();
  14768. this._shadowMode = exports.ShadowMode.None;
  14769. this._isAlternate = false;
  14770. this._shadowResolution = 2048;
  14771. this._shadowDistance = 50.0;
  14772. this._shadowDepthBias = 1.0;
  14773. this._shadowNormalBias = 1.0;
  14774. this._shadowNearPlane = 0.1;
  14775. this._shadowStrength = 1.0;
  14776. this._intensity = 1.0;
  14777. this._intensityColor = new Vector3();
  14778. this.color = new Vector3(1.0, 1.0, 1.0);
  14779. this._lightmapBakedType = LightSprite.LIGHTMAPBAKEDTYPE_REALTIME;
  14780. }
  14781. get intensity() {
  14782. return this._intensity;
  14783. }
  14784. set intensity(value) {
  14785. this._intensity = value;
  14786. }
  14787. get shadowMode() {
  14788. return this._shadowMode;
  14789. }
  14790. set shadowMode(value) {
  14791. this._shadowMode = value;
  14792. }
  14793. get shadowDistance() {
  14794. return this._shadowDistance;
  14795. }
  14796. set shadowDistance(value) {
  14797. this._shadowDistance = value;
  14798. }
  14799. get shadowResolution() {
  14800. return this._shadowResolution;
  14801. }
  14802. set shadowResolution(value) {
  14803. this._shadowResolution = value;
  14804. }
  14805. get shadowDepthBias() {
  14806. return this._shadowDepthBias;
  14807. }
  14808. set shadowDepthBias(value) {
  14809. this._shadowDepthBias = value;
  14810. }
  14811. get shadowNormalBias() {
  14812. return this._shadowNormalBias;
  14813. }
  14814. set shadowNormalBias(value) {
  14815. this._shadowNormalBias = value;
  14816. }
  14817. get shadowStrength() {
  14818. return this._shadowStrength;
  14819. }
  14820. set shadowStrength(value) {
  14821. this._shadowStrength = value;
  14822. }
  14823. get shadowNearPlane() {
  14824. return this._shadowNearPlane;
  14825. }
  14826. set shadowNearPlane(value) {
  14827. this._shadowNearPlane = value;
  14828. }
  14829. get lightmapBakedType() {
  14830. return this._lightmapBakedType;
  14831. }
  14832. set lightmapBakedType(value) {
  14833. if (this._lightmapBakedType !== value) {
  14834. this._lightmapBakedType = value;
  14835. if (this.activeInHierarchy) {
  14836. if (value !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED)
  14837. this._addToScene();
  14838. else
  14839. this._removeFromScene();
  14840. }
  14841. }
  14842. }
  14843. _parse(data, spriteMap) {
  14844. super._parse(data, spriteMap);
  14845. var colorData = data.color;
  14846. this.color.fromArray(colorData);
  14847. this.intensity = data.intensity;
  14848. this.lightmapBakedType = data.lightmapBakedType;
  14849. }
  14850. _addToScene() {
  14851. var scene = this._scene;
  14852. var maxLightCount = Config3D._config.maxLightCount;
  14853. if (scene._lightCount < maxLightCount) {
  14854. scene._lightCount++;
  14855. this._addToLightQueue();
  14856. this._isAlternate = false;
  14857. }
  14858. else {
  14859. scene._alternateLights.add(this);
  14860. this._isAlternate = true;
  14861. console.warn("LightSprite:light count has large than maxLightCount,the latest added light will be ignore.");
  14862. }
  14863. }
  14864. _removeFromScene() {
  14865. var scene = this._scene;
  14866. if (this._isAlternate) {
  14867. scene._alternateLights.remove(this);
  14868. }
  14869. else {
  14870. scene._lightCount--;
  14871. this._removeFromLightQueue();
  14872. if (scene._alternateLights._length > 0) {
  14873. var alternateLight = scene._alternateLights.shift();
  14874. alternateLight._addToLightQueue();
  14875. alternateLight._isAlternate = false;
  14876. scene._lightCount++;
  14877. }
  14878. }
  14879. }
  14880. _addToLightQueue() {
  14881. }
  14882. _removeFromLightQueue() {
  14883. }
  14884. _onActive() {
  14885. super._onActive();
  14886. (this.lightmapBakedType !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED) && (this._addToScene());
  14887. }
  14888. _onInActive() {
  14889. super._onInActive();
  14890. (this.lightmapBakedType !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED) && (this._removeFromScene());
  14891. }
  14892. _create() {
  14893. return new LightSprite();
  14894. }
  14895. get diffuseColor() {
  14896. console.log("LightSprite: discard property,please use color property instead.");
  14897. return this.color;
  14898. }
  14899. set diffuseColor(value) {
  14900. console.log("LightSprite: discard property,please use color property instead.");
  14901. this.color = value;
  14902. }
  14903. }
  14904. LightSprite.LIGHTMAPBAKEDTYPE_REALTIME = 0;
  14905. LightSprite.LIGHTMAPBAKEDTYPE_MIXED = 1;
  14906. LightSprite.LIGHTMAPBAKEDTYPE_BAKED = 2;
  14907. (function (ShadowCascadesMode) {
  14908. ShadowCascadesMode[ShadowCascadesMode["NoCascades"] = 0] = "NoCascades";
  14909. ShadowCascadesMode[ShadowCascadesMode["TwoCascades"] = 1] = "TwoCascades";
  14910. ShadowCascadesMode[ShadowCascadesMode["FourCascades"] = 2] = "FourCascades";
  14911. })(exports.ShadowCascadesMode || (exports.ShadowCascadesMode = {}));
  14912. var FrustumFace;
  14913. (function (FrustumFace) {
  14914. FrustumFace[FrustumFace["Near"] = 0] = "Near";
  14915. FrustumFace[FrustumFace["Far"] = 1] = "Far";
  14916. FrustumFace[FrustumFace["Left"] = 2] = "Left";
  14917. FrustumFace[FrustumFace["Right"] = 3] = "Right";
  14918. FrustumFace[FrustumFace["Bottom"] = 4] = "Bottom";
  14919. FrustumFace[FrustumFace["Top"] = 5] = "Top";
  14920. })(FrustumFace || (FrustumFace = {}));
  14921. class ShadowUtils {
  14922. static supportShadow() {
  14923. return Laya.LayaGL.layaGPUInstance._isWebGL2 || Laya.SystemUtils.supportRenderTextureFormat(Laya.RenderTextureFormat.Depth);
  14924. }
  14925. static init() {
  14926. if (Laya.LayaGL.layaGPUInstance._isWebGL2)
  14927. ShadowUtils._shadowTextureFormat = Laya.RenderTextureFormat.ShadowMap;
  14928. else
  14929. ShadowUtils._shadowTextureFormat = Laya.RenderTextureFormat.Depth;
  14930. }
  14931. static getTemporaryShadowTexture(witdh, height, depthFormat) {
  14932. var shadowMap = RenderTexture.createFromPool(witdh, height, ShadowUtils._shadowTextureFormat, depthFormat);
  14933. shadowMap.filterMode = Laya.FilterMode.Bilinear;
  14934. shadowMap.wrapModeU = Laya.WarpMode.Clamp;
  14935. shadowMap.wrapModeV = Laya.WarpMode.Clamp;
  14936. return shadowMap;
  14937. }
  14938. static getShadowBias(light, shadowProjectionMatrix, shadowResolution, out) {
  14939. var frustumSize;
  14940. if (light._lightType == exports.LightType.Directional) {
  14941. frustumSize = 2.0 / shadowProjectionMatrix.elements[0];
  14942. }
  14943. else if (light._lightType == exports.LightType.Spot) {
  14944. frustumSize = Math.tan(light.spotAngle * 0.5 * MathUtils3D.Deg2Rad) * light.range;
  14945. }
  14946. else {
  14947. console.warn("ShadowUtils:Only spot and directional shadow casters are supported now.");
  14948. frustumSize = 0.0;
  14949. }
  14950. var texelSize = frustumSize / shadowResolution;
  14951. var depthBias = -light._shadowDepthBias * texelSize;
  14952. var normalBias = -light._shadowNormalBias * texelSize;
  14953. if (light.shadowMode == exports.ShadowMode.SoftHigh) {
  14954. const kernelRadius = 2.5;
  14955. depthBias *= kernelRadius;
  14956. normalBias *= kernelRadius;
  14957. }
  14958. out.setValue(depthBias, normalBias, 0.0, 0.0);
  14959. }
  14960. static getCameraFrustumPlanes(cameraViewProjectMatrix, frustumPlanes) {
  14961. BoundFrustum.getPlanesFromMatrix(cameraViewProjectMatrix, frustumPlanes[FrustumFace.Near], frustumPlanes[FrustumFace.Far], frustumPlanes[FrustumFace.Left], frustumPlanes[FrustumFace.Right], frustumPlanes[FrustumFace.Top], frustumPlanes[FrustumFace.Bottom]);
  14962. }
  14963. static getFarWithRadius(radius, denominator) {
  14964. return Math.sqrt(radius * radius / denominator);
  14965. }
  14966. static getCascadesSplitDistance(twoSplitRatio, fourSplitRatio, cameraNear, shadowFar, fov, aspectRatio, cascadesMode, out) {
  14967. out[0] = cameraNear;
  14968. var range = shadowFar - cameraNear;
  14969. var tFov = Math.tan(fov * 0.5);
  14970. var denominator = 1.0 + tFov * tFov * (aspectRatio * aspectRatio + 1.0);
  14971. switch (cascadesMode) {
  14972. case exports.ShadowCascadesMode.NoCascades:
  14973. out[1] = ShadowUtils.getFarWithRadius(shadowFar, denominator);
  14974. break;
  14975. case exports.ShadowCascadesMode.TwoCascades:
  14976. out[1] = ShadowUtils.getFarWithRadius(cameraNear + range * twoSplitRatio, denominator);
  14977. out[2] = ShadowUtils.getFarWithRadius(shadowFar, denominator);
  14978. break;
  14979. case exports.ShadowCascadesMode.FourCascades:
  14980. out[1] = ShadowUtils.getFarWithRadius(cameraNear + range * fourSplitRatio.x, denominator);
  14981. out[2] = ShadowUtils.getFarWithRadius(cameraNear + range * fourSplitRatio.y, denominator);
  14982. out[3] = ShadowUtils.getFarWithRadius(cameraNear + range * fourSplitRatio.z, denominator);
  14983. out[4] = ShadowUtils.getFarWithRadius(shadowFar, denominator);
  14984. break;
  14985. }
  14986. }
  14987. static applySliceTransform(shadowSliceData, atlasWidth, atlasHeight, cascadeIndex, outShadowMatrices) {
  14988. var sliceE = ShadowUtils._tempMatrix0.elements;
  14989. var oneOverAtlasWidth = 1.0 / atlasWidth;
  14990. var oneOverAtlasHeight = 1.0 / atlasHeight;
  14991. sliceE[0] = shadowSliceData.resolution * oneOverAtlasWidth;
  14992. sliceE[5] = shadowSliceData.resolution * oneOverAtlasHeight;
  14993. sliceE[12] = shadowSliceData.offsetX * oneOverAtlasWidth;
  14994. sliceE[13] = shadowSliceData.offsetY * oneOverAtlasHeight;
  14995. sliceE[1] = sliceE[2] = sliceE[2] = sliceE[4] = sliceE[6] = sliceE[7] = sliceE[8] = sliceE[9] = sliceE[11] = sliceE[14] = 0;
  14996. sliceE[10] = sliceE[15] = 1;
  14997. var offset = cascadeIndex * 16;
  14998. Utils3D._mulMatrixArray(sliceE, outShadowMatrices, offset, outShadowMatrices, offset);
  14999. }
  15000. static getDirectionLightShadowCullPlanes(cameraFrustumPlanes, cascadeIndex, splitDistance, cameraNear, direction, shadowSliceData) {
  15001. var frustumCorners = ShadowUtils._frustumCorners;
  15002. var backPlaneFaces = ShadowUtils._backPlaneFaces;
  15003. var planeNeighbors = ShadowUtils._frustumPlaneNeighbors;
  15004. var twoPlaneCorners = ShadowUtils._frustumTwoPlaneCorners;
  15005. var edgePlanePoint2 = ShadowUtils._edgePlanePoint2;
  15006. var out = shadowSliceData.cullPlanes;
  15007. var near = cameraFrustumPlanes[FrustumFace.Near], far = cameraFrustumPlanes[FrustumFace.Far];
  15008. var left = cameraFrustumPlanes[FrustumFace.Left], right = cameraFrustumPlanes[FrustumFace.Right];
  15009. var bottom = cameraFrustumPlanes[FrustumFace.Bottom], top = cameraFrustumPlanes[FrustumFace.Top];
  15010. var splitNearDistance = splitDistance[cascadeIndex] - cameraNear;
  15011. var splitNear = ShadowUtils._adjustNearPlane;
  15012. var splitFar = ShadowUtils._adjustFarPlane;
  15013. near.normal.cloneTo(splitNear.normal);
  15014. far.normal.cloneTo(splitFar.normal);
  15015. splitNear.distance = near.distance - splitNearDistance;
  15016. splitFar.distance = Math.min(-near.distance + shadowSliceData.sphereCenterZ + shadowSliceData.splitBoundSphere.radius, far.distance);
  15017. BoundFrustum.get3PlaneInterPoint(splitNear, bottom, right, frustumCorners[exports.FrustumCorner.nearBottomRight]);
  15018. BoundFrustum.get3PlaneInterPoint(splitNear, top, right, frustumCorners[exports.FrustumCorner.nearTopRight]);
  15019. BoundFrustum.get3PlaneInterPoint(splitNear, top, left, frustumCorners[exports.FrustumCorner.nearTopLeft]);
  15020. BoundFrustum.get3PlaneInterPoint(splitNear, bottom, left, frustumCorners[exports.FrustumCorner.nearBottomLeft]);
  15021. BoundFrustum.get3PlaneInterPoint(splitFar, bottom, right, frustumCorners[exports.FrustumCorner.FarBottomRight]);
  15022. BoundFrustum.get3PlaneInterPoint(splitFar, top, right, frustumCorners[exports.FrustumCorner.FarTopRight]);
  15023. BoundFrustum.get3PlaneInterPoint(splitFar, top, left, frustumCorners[exports.FrustumCorner.FarTopLeft]);
  15024. BoundFrustum.get3PlaneInterPoint(splitFar, bottom, left, frustumCorners[exports.FrustumCorner.FarBottomLeft]);
  15025. var backIndex = 0;
  15026. for (var i = 0; i < 6; i++) {
  15027. var plane;
  15028. switch (i) {
  15029. case FrustumFace.Near:
  15030. plane = splitNear;
  15031. break;
  15032. case FrustumFace.Far:
  15033. plane = splitFar;
  15034. break;
  15035. default:
  15036. plane = cameraFrustumPlanes[i];
  15037. break;
  15038. }
  15039. if (Vector3.dot(plane.normal, direction) < 0.0) {
  15040. plane.cloneTo(out[backIndex]);
  15041. backPlaneFaces[backIndex] = i;
  15042. backIndex++;
  15043. }
  15044. }
  15045. var edgeIndex = backIndex;
  15046. for (var i = 0; i < backIndex; i++) {
  15047. var backFace = backPlaneFaces[i];
  15048. var neighborFaces = planeNeighbors[backFace];
  15049. for (var j = 0; j < 4; j++) {
  15050. var neighborFace = neighborFaces[j];
  15051. var notBackFace = true;
  15052. for (var k = 0; k < backIndex; k++)
  15053. if (neighborFace == backPlaneFaces[k]) {
  15054. notBackFace = false;
  15055. break;
  15056. }
  15057. if (notBackFace) {
  15058. var corners = twoPlaneCorners[backFace][neighborFace];
  15059. var point0 = frustumCorners[corners[0]];
  15060. var point1 = frustumCorners[corners[1]];
  15061. Vector3.add(point0, direction, edgePlanePoint2);
  15062. Plane.createPlaneBy3P(point0, point1, edgePlanePoint2, out[edgeIndex++]);
  15063. }
  15064. }
  15065. }
  15066. shadowSliceData.cullPlaneCount = edgeIndex;
  15067. }
  15068. static getBoundSphereByFrustum(near, far, fov, aspectRatio, cameraPos, forward, outBoundSphere) {
  15069. var centerZ;
  15070. var radius;
  15071. var k = Math.sqrt(1.0 + aspectRatio * aspectRatio) * Math.tan(fov / 2.0);
  15072. var k2 = k * k;
  15073. var farSNear = far - near;
  15074. var farANear = far + near;
  15075. if (k2 > farSNear / farANear) {
  15076. centerZ = far;
  15077. radius = far * k;
  15078. }
  15079. else {
  15080. centerZ = 0.5 * farANear * (1 + k2);
  15081. radius = 0.5 * Math.sqrt(farSNear * farSNear + 2.0 * (far * far + near * near) * k2 + farANear * farANear * k2 * k2);
  15082. }
  15083. var center = outBoundSphere.center;
  15084. outBoundSphere.radius = radius;
  15085. Vector3.scale(forward, centerZ, center);
  15086. Vector3.add(cameraPos, center, center);
  15087. return centerZ;
  15088. }
  15089. static getMaxTileResolutionInAtlas(atlasWidth, atlasHeight, tileCount) {
  15090. var resolution = Math.min(atlasWidth, atlasHeight);
  15091. var currentTileCount = Math.floor(atlasWidth / resolution) * Math.floor(atlasHeight / resolution);
  15092. while (currentTileCount < tileCount) {
  15093. resolution = Math.floor(resolution >> 1);
  15094. currentTileCount = Math.floor(atlasWidth / resolution) * Math.floor(atlasHeight / resolution);
  15095. }
  15096. return resolution;
  15097. }
  15098. static getDirectionalLightMatrices(lightUp, lightSide, lightForward, cascadeIndex, nearPlane, shadowResolution, shadowSliceData, shadowMatrices) {
  15099. var boundSphere = shadowSliceData.splitBoundSphere;
  15100. var center = boundSphere.center;
  15101. var radius = boundSphere.radius;
  15102. var halfShadowResolution = shadowResolution / 2;
  15103. var borderRadius = radius * halfShadowResolution / (halfShadowResolution - ShadowUtils.atlasBorderSize);
  15104. var borderDiam = borderRadius * 2.0;
  15105. var sizeUnit = shadowResolution / borderDiam;
  15106. var radiusUnit = borderDiam / shadowResolution;
  15107. var upLen = Math.ceil(Vector3.dot(center, lightUp) * sizeUnit) * radiusUnit;
  15108. var sideLen = Math.ceil(Vector3.dot(center, lightSide) * sizeUnit) * radiusUnit;
  15109. var forwardLen = Vector3.dot(center, lightForward);
  15110. center.x = lightUp.x * upLen + lightSide.x * sideLen + lightForward.x * forwardLen;
  15111. center.y = lightUp.y * upLen + lightSide.y * sideLen + lightForward.y * forwardLen;
  15112. center.z = lightUp.z * upLen + lightSide.z * sideLen + lightForward.z * forwardLen;
  15113. var origin = shadowSliceData.position;
  15114. var viewMatrix = shadowSliceData.viewMatrix;
  15115. var projectMatrix = shadowSliceData.projectionMatrix;
  15116. var viewProjectMatrix = shadowSliceData.viewProjectMatrix;
  15117. shadowSliceData.resolution = shadowResolution;
  15118. shadowSliceData.offsetX = (cascadeIndex % 2) * shadowResolution;
  15119. shadowSliceData.offsetY = Math.floor(cascadeIndex / 2) * shadowResolution;
  15120. Vector3.scale(lightForward, radius + nearPlane, origin);
  15121. Vector3.subtract(center, origin, origin);
  15122. Matrix4x4.createLookAt(origin, center, lightUp, viewMatrix);
  15123. Matrix4x4.createOrthoOffCenter(-borderRadius, borderRadius, -borderRadius, borderRadius, 0.0, radius * 2.0 + nearPlane, projectMatrix);
  15124. Matrix4x4.multiply(projectMatrix, viewMatrix, viewProjectMatrix);
  15125. Utils3D._mulMatrixArray(ShadowUtils._shadowMapScaleOffsetMatrix.elements, viewProjectMatrix.elements, 0, shadowMatrices, cascadeIndex * 16);
  15126. }
  15127. static getSpotLightShadowData(shadowSpotData, spotLight, resolution, shadowParams, shadowSpotMatrices, shadowMapSize) {
  15128. var out = shadowSpotData.position = spotLight.transform.position;
  15129. shadowSpotData.resolution = resolution;
  15130. shadowMapSize.setValue(1.0 / resolution, 1.0 / resolution, resolution, resolution);
  15131. shadowSpotData.offsetX = 0;
  15132. shadowSpotData.offsetY = 0;
  15133. var spotWorldMatrix = spotLight.transform.worldMatrix;
  15134. var viewMatrix = shadowSpotData.viewMatrix;
  15135. var projectMatrix = shadowSpotData.projectionMatrix;
  15136. var viewProjectMatrix = shadowSpotData.viewProjectMatrix;
  15137. var BoundFrustum = shadowSpotData.cameraCullInfo.boundFrustum;
  15138. spotWorldMatrix.invert(viewMatrix);
  15139. Matrix4x4.createPerspective(3.1416 * spotLight.spotAngle / 180.0, 1, 0.1, spotLight.range, projectMatrix);
  15140. shadowParams.y = spotLight.shadowStrength;
  15141. Matrix4x4.multiply(projectMatrix, viewMatrix, viewProjectMatrix);
  15142. BoundFrustum.matrix = viewProjectMatrix;
  15143. viewProjectMatrix.cloneTo(shadowSpotMatrices);
  15144. shadowSpotData.cameraCullInfo.position = out;
  15145. }
  15146. static prepareShadowReceiverShaderValues(light, shadowMapWidth, shadowMapHeight, shadowSliceDatas, cascadeCount, shadowMapSize, shadowParams, shadowMatrices, splitBoundSpheres) {
  15147. shadowMapSize.setValue(1.0 / shadowMapWidth, 1.0 / shadowMapHeight, shadowMapWidth, shadowMapHeight);
  15148. shadowParams.setValue(light._shadowStrength, 0.0, 0.0, 0.0);
  15149. if (cascadeCount > 1) {
  15150. const matrixFloatCount = 16;
  15151. for (var i = cascadeCount * matrixFloatCount, n = 4 * matrixFloatCount; i < n; i++)
  15152. shadowMatrices[i] = 0.0;
  15153. for (var i = 0; i < cascadeCount; i++) {
  15154. var boundSphere = shadowSliceDatas[i].splitBoundSphere;
  15155. var center = boundSphere.center;
  15156. var radius = boundSphere.radius;
  15157. var offset = i * 4;
  15158. splitBoundSpheres[offset] = center.x;
  15159. splitBoundSpheres[offset + 1] = center.y;
  15160. splitBoundSpheres[offset + 2] = center.z;
  15161. splitBoundSpheres[offset + 3] = radius * radius;
  15162. }
  15163. const sphereFloatCount = 4;
  15164. for (var i = cascadeCount * sphereFloatCount, n = 4 * sphereFloatCount; i < n; i++)
  15165. splitBoundSpheres[i] = 0.0;
  15166. }
  15167. }
  15168. }
  15169. ShadowUtils._tempMatrix0 = new Matrix4x4();
  15170. ShadowUtils._shadowMapScaleOffsetMatrix = new Matrix4x4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0);
  15171. ShadowUtils._frustumCorners = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  15172. ShadowUtils._adjustNearPlane = new Plane(new Vector3());
  15173. ShadowUtils._adjustFarPlane = new Plane(new Vector3());
  15174. ShadowUtils._backPlaneFaces = new Array(5);
  15175. ShadowUtils._edgePlanePoint2 = new Vector3();
  15176. ShadowUtils._frustumPlaneNeighbors = [
  15177. [FrustumFace.Left, FrustumFace.Right, FrustumFace.Top, FrustumFace.Bottom],
  15178. [FrustumFace.Left, FrustumFace.Right, FrustumFace.Top, FrustumFace.Bottom],
  15179. [FrustumFace.Near, FrustumFace.Far, FrustumFace.Top, FrustumFace.Bottom],
  15180. [FrustumFace.Near, FrustumFace.Far, FrustumFace.Top, FrustumFace.Bottom],
  15181. [FrustumFace.Near, FrustumFace.Far, FrustumFace.Left, FrustumFace.Right],
  15182. [FrustumFace.Near, FrustumFace.Far, FrustumFace.Left, FrustumFace.Right]
  15183. ];
  15184. ShadowUtils._frustumTwoPlaneCorners = [
  15185. [[exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.nearBottomLeft, exports.FrustumCorner.nearTopLeft], [exports.FrustumCorner.nearTopRight, exports.FrustumCorner.nearBottomRight], [exports.FrustumCorner.nearBottomRight, exports.FrustumCorner.nearBottomLeft], [exports.FrustumCorner.nearTopLeft, exports.FrustumCorner.nearTopRight]],
  15186. [[exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.FarTopLeft, exports.FrustumCorner.FarBottomLeft], [exports.FrustumCorner.FarBottomRight, exports.FrustumCorner.FarTopRight], [exports.FrustumCorner.FarBottomLeft, exports.FrustumCorner.FarBottomRight], [exports.FrustumCorner.FarTopRight, exports.FrustumCorner.FarTopLeft]],
  15187. [[exports.FrustumCorner.nearTopLeft, exports.FrustumCorner.nearBottomLeft], [exports.FrustumCorner.FarBottomLeft, exports.FrustumCorner.FarTopLeft], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.nearBottomLeft, exports.FrustumCorner.FarBottomLeft], [exports.FrustumCorner.FarTopLeft, exports.FrustumCorner.nearTopLeft]],
  15188. [[exports.FrustumCorner.nearBottomRight, exports.FrustumCorner.nearTopRight], [exports.FrustumCorner.FarTopRight, exports.FrustumCorner.FarBottomRight], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.FarBottomRight, exports.FrustumCorner.nearBottomRight], [exports.FrustumCorner.nearTopRight, exports.FrustumCorner.FarTopRight]],
  15189. [[exports.FrustumCorner.nearBottomLeft, exports.FrustumCorner.nearBottomRight], [exports.FrustumCorner.FarBottomRight, exports.FrustumCorner.FarBottomLeft], [exports.FrustumCorner.FarBottomLeft, exports.FrustumCorner.nearBottomLeft], [exports.FrustumCorner.nearBottomRight, exports.FrustumCorner.FarBottomRight], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown]],
  15190. [[exports.FrustumCorner.nearTopRight, exports.FrustumCorner.nearTopLeft], [exports.FrustumCorner.FarTopLeft, exports.FrustumCorner.FarTopRight], [exports.FrustumCorner.nearTopLeft, exports.FrustumCorner.FarTopLeft], [exports.FrustumCorner.FarTopRight, exports.FrustumCorner.nearTopRight], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown]]
  15191. ];
  15192. ShadowUtils.atlasBorderSize = 4.0;
  15193. (function (CameraClearFlags) {
  15194. CameraClearFlags[CameraClearFlags["SolidColor"] = 0] = "SolidColor";
  15195. CameraClearFlags[CameraClearFlags["Sky"] = 1] = "Sky";
  15196. CameraClearFlags[CameraClearFlags["DepthOnly"] = 2] = "DepthOnly";
  15197. CameraClearFlags[CameraClearFlags["Nothing"] = 3] = "Nothing";
  15198. })(exports.CameraClearFlags || (exports.CameraClearFlags = {}));
  15199. class Camera extends BaseCamera {
  15200. constructor(aspectRatio = 0, nearPlane = 0.3, farPlane = 1000) {
  15201. super(nearPlane, farPlane);
  15202. this._updateViewMatrix = true;
  15203. this._postProcess = null;
  15204. this._enableHDR = false;
  15205. this._viewportParams = new Vector4();
  15206. this._projectionParams = new Vector4();
  15207. this._offScreenRenderTexture = null;
  15208. this._internalRenderTexture = null;
  15209. this._postProcessCommandBuffers = [];
  15210. this._clusterPlaneCacheFlag = new Vector2(-1, -1);
  15211. this._screenOffsetScale = new Vector4();
  15212. this.enableRender = true;
  15213. this.clearFlag = exports.CameraClearFlags.SolidColor;
  15214. this._viewMatrix = new Matrix4x4();
  15215. this._projectionMatrix = new Matrix4x4();
  15216. this._projectionViewMatrix = new Matrix4x4();
  15217. this._viewport = new Viewport(0, 0, 0, 0);
  15218. this._normalizedViewport = new Viewport(0, 0, 1, 1);
  15219. this._aspectRatio = aspectRatio;
  15220. this._boundFrustum = new BoundFrustum(new Matrix4x4());
  15221. if (Laya.Render.supportWebGLPlusCulling)
  15222. this._boundFrustumBuffer = new Float32Array(24);
  15223. this._calculateProjectionMatrix();
  15224. Laya.Laya.stage.on(Laya.Event.RESIZE, this, this._onScreenSizeChanged);
  15225. this.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  15226. }
  15227. get aspectRatio() {
  15228. if (this._aspectRatio === 0) {
  15229. var vp = this.viewport;
  15230. return vp.width / vp.height;
  15231. }
  15232. return this._aspectRatio;
  15233. }
  15234. set aspectRatio(value) {
  15235. if (value < 0)
  15236. throw new Error("Camera: the aspect ratio has to be a positive real number.");
  15237. this._aspectRatio = value;
  15238. this._calculateProjectionMatrix();
  15239. }
  15240. get viewport() {
  15241. if (this._offScreenRenderTexture)
  15242. this._calculationViewport(this._normalizedViewport, this._offScreenRenderTexture.width, this._offScreenRenderTexture.height);
  15243. else
  15244. this._calculationViewport(this._normalizedViewport, RenderContext3D.clientWidth, RenderContext3D.clientHeight);
  15245. return this._viewport;
  15246. }
  15247. set viewport(value) {
  15248. var width;
  15249. var height;
  15250. if (this._offScreenRenderTexture) {
  15251. width = this._offScreenRenderTexture.width;
  15252. height = this._offScreenRenderTexture.height;
  15253. }
  15254. else {
  15255. width = RenderContext3D.clientWidth;
  15256. height = RenderContext3D.clientHeight;
  15257. }
  15258. this._normalizedViewport.x = value.x / width;
  15259. this._normalizedViewport.y = value.y / height;
  15260. this._normalizedViewport.width = value.width / width;
  15261. this._normalizedViewport.height = value.height / height;
  15262. this._calculationViewport(this._normalizedViewport, width, height);
  15263. this._calculateProjectionMatrix();
  15264. }
  15265. get normalizedViewport() {
  15266. return this._normalizedViewport;
  15267. }
  15268. set normalizedViewport(value) {
  15269. var width;
  15270. var height;
  15271. if (this._offScreenRenderTexture) {
  15272. width = this._offScreenRenderTexture.width;
  15273. height = this._offScreenRenderTexture.height;
  15274. }
  15275. else {
  15276. width = RenderContext3D.clientWidth;
  15277. height = RenderContext3D.clientHeight;
  15278. }
  15279. if (this._normalizedViewport !== value)
  15280. value.cloneTo(this._normalizedViewport);
  15281. this._calculationViewport(value, width, height);
  15282. this._calculateProjectionMatrix();
  15283. }
  15284. get viewMatrix() {
  15285. if (this._updateViewMatrix) {
  15286. var scale = this.transform.getWorldLossyScale();
  15287. var scaleX = scale.x;
  15288. var scaleY = scale.y;
  15289. var scaleZ = scale.z;
  15290. var viewMatE = this._viewMatrix.elements;
  15291. this.transform.worldMatrix.cloneTo(this._viewMatrix);
  15292. viewMatE[0] /= scaleX;
  15293. viewMatE[1] /= scaleX;
  15294. viewMatE[2] /= scaleX;
  15295. viewMatE[4] /= scaleY;
  15296. viewMatE[5] /= scaleY;
  15297. viewMatE[6] /= scaleY;
  15298. viewMatE[8] /= scaleZ;
  15299. viewMatE[9] /= scaleZ;
  15300. viewMatE[10] /= scaleZ;
  15301. this._viewMatrix.invert(this._viewMatrix);
  15302. this._updateViewMatrix = false;
  15303. }
  15304. return this._viewMatrix;
  15305. }
  15306. get projectionMatrix() {
  15307. return this._projectionMatrix;
  15308. }
  15309. set projectionMatrix(value) {
  15310. this._projectionMatrix = value;
  15311. this._useUserProjectionMatrix = true;
  15312. }
  15313. get projectionViewMatrix() {
  15314. Matrix4x4.multiply(this.projectionMatrix, this.viewMatrix, this._projectionViewMatrix);
  15315. return this._projectionViewMatrix;
  15316. }
  15317. get boundFrustum() {
  15318. this._boundFrustum.matrix = this.projectionViewMatrix;
  15319. if (Laya.Render.supportWebGLPlusCulling) {
  15320. var near = this._boundFrustum.near;
  15321. var far = this._boundFrustum.far;
  15322. var left = this._boundFrustum.left;
  15323. var right = this._boundFrustum.right;
  15324. var top = this._boundFrustum.top;
  15325. var bottom = this._boundFrustum.bottom;
  15326. var nearNE = near.normal;
  15327. var farNE = far.normal;
  15328. var leftNE = left.normal;
  15329. var rightNE = right.normal;
  15330. var topNE = top.normal;
  15331. var bottomNE = bottom.normal;
  15332. var buffer = this._boundFrustumBuffer;
  15333. buffer[0] = nearNE.x, buffer[1] = nearNE.y, buffer[2] = nearNE.z, buffer[3] = near.distance;
  15334. buffer[4] = farNE.x, buffer[5] = farNE.y, buffer[6] = farNE.z, buffer[7] = far.distance;
  15335. buffer[8] = leftNE.x, buffer[9] = leftNE.y, buffer[10] = leftNE.z, buffer[11] = left.distance;
  15336. buffer[12] = rightNE.x, buffer[13] = rightNE.y, buffer[14] = rightNE.z, buffer[15] = right.distance;
  15337. buffer[16] = topNE.x, buffer[17] = topNE.y, buffer[18] = topNE.z, buffer[19] = top.distance;
  15338. buffer[20] = bottomNE.x, buffer[21] = bottomNE.y, buffer[22] = bottomNE.z, buffer[23] = bottom.distance;
  15339. }
  15340. return this._boundFrustum;
  15341. }
  15342. get renderTarget() {
  15343. return this._offScreenRenderTexture;
  15344. }
  15345. set renderTarget(value) {
  15346. var lastValue = this._offScreenRenderTexture;
  15347. if (lastValue !== value) {
  15348. (lastValue) && (lastValue._isCameraTarget = false);
  15349. (value) && (value._isCameraTarget = true);
  15350. this._offScreenRenderTexture = value;
  15351. this._calculateProjectionMatrix();
  15352. }
  15353. }
  15354. get postProcess() {
  15355. return this._postProcess;
  15356. }
  15357. set postProcess(value) {
  15358. this._postProcess = value;
  15359. var postProcessCommandBuffer = new CommandBuffer();
  15360. this.addCommandBuffer(Camera.CAMERAEVENT_POSTPROCESS, postProcessCommandBuffer);
  15361. value._init(this, postProcessCommandBuffer);
  15362. }
  15363. get enableHDR() {
  15364. return this._enableHDR;
  15365. }
  15366. set enableHDR(value) {
  15367. if (value && !Laya.SystemUtils.supportRenderTextureFormat(Laya.RenderTextureFormat.R16G16B16A16)) {
  15368. console.warn("Camera:can't enable HDR in this device.");
  15369. return;
  15370. }
  15371. this._enableHDR = value;
  15372. }
  15373. _calculationViewport(normalizedViewport, width, height) {
  15374. var lx = normalizedViewport.x * width;
  15375. var ly = normalizedViewport.y * height;
  15376. var rx = lx + Math.max(normalizedViewport.width * width, 0);
  15377. var ry = ly + Math.max(normalizedViewport.height * height, 0);
  15378. var ceilLeftX = Math.ceil(lx);
  15379. var ceilLeftY = Math.ceil(ly);
  15380. var floorRightX = Math.floor(rx);
  15381. var floorRightY = Math.floor(ry);
  15382. var pixelLeftX = ceilLeftX - lx >= 0.5 ? Math.floor(lx) : ceilLeftX;
  15383. var pixelLeftY = ceilLeftY - ly >= 0.5 ? Math.floor(ly) : ceilLeftY;
  15384. var pixelRightX = rx - floorRightX >= 0.5 ? Math.ceil(rx) : floorRightX;
  15385. var pixelRightY = ry - floorRightY >= 0.5 ? Math.ceil(ry) : floorRightY;
  15386. this._viewport.x = pixelLeftX;
  15387. this._viewport.y = pixelLeftY;
  15388. this._viewport.width = pixelRightX - pixelLeftX;
  15389. this._viewport.height = pixelRightY - pixelLeftY;
  15390. }
  15391. _calculateProjectionMatrix() {
  15392. if (!this._useUserProjectionMatrix) {
  15393. if (this._orthographic) {
  15394. var halfHeight = this.orthographicVerticalSize * 0.5;
  15395. var halfWidth = halfHeight * this.aspectRatio;
  15396. Matrix4x4.createOrthoOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, this.nearPlane, this.farPlane, this._projectionMatrix);
  15397. }
  15398. else {
  15399. Matrix4x4.createPerspective(3.1416 * this.fieldOfView / 180.0, this.aspectRatio, this.nearPlane, this.farPlane, this._projectionMatrix);
  15400. }
  15401. }
  15402. }
  15403. _isLayerVisible(layer) {
  15404. return (Math.pow(2, layer) & this.cullingMask) != 0;
  15405. }
  15406. _onTransformChanged(flag) {
  15407. flag &= Transform3D.TRANSFORM_WORLDMATRIX;
  15408. (flag) && (this._updateViewMatrix = true);
  15409. }
  15410. _parse(data, spriteMap) {
  15411. super._parse(data, spriteMap);
  15412. var clearFlagData = data.clearFlag;
  15413. (clearFlagData !== undefined) && (this.clearFlag = clearFlagData);
  15414. var viewport = data.viewport;
  15415. this.normalizedViewport = new Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);
  15416. var enableHDR = data.enableHDR;
  15417. (enableHDR !== undefined) && (this.enableHDR = enableHDR);
  15418. }
  15419. _getCanvasWidth() {
  15420. if (this._offScreenRenderTexture)
  15421. return this._offScreenRenderTexture.width;
  15422. else
  15423. return RenderContext3D.clientWidth;
  15424. }
  15425. _getCanvasHeight() {
  15426. if (this._offScreenRenderTexture)
  15427. return this._offScreenRenderTexture.height;
  15428. else
  15429. return RenderContext3D.clientHeight;
  15430. }
  15431. _getRenderTexture() {
  15432. return this._internalRenderTexture || this._offScreenRenderTexture;
  15433. }
  15434. _needInternalRenderTexture() {
  15435. return this._postProcess || this._enableHDR ? true : false;
  15436. }
  15437. _applyPostProcessCommandBuffers() {
  15438. for (var i = 0, n = this._postProcessCommandBuffers.length; i < n; i++)
  15439. this._postProcessCommandBuffers[i]._apply();
  15440. }
  15441. _getRenderTextureFormat() {
  15442. if (this._enableHDR)
  15443. return Laya.RenderTextureFormat.R16G16B16A16;
  15444. else
  15445. return Laya.RenderTextureFormat.R8G8B8;
  15446. }
  15447. _prepareCameraToRender() {
  15448. super._prepareCameraToRender();
  15449. var vp = this.viewport;
  15450. this._viewportParams.setValue(vp.x, vp.y, vp.width, vp.height);
  15451. this._projectionParams.setValue(this._nearPlane, this._farPlane, RenderContext3D._instance.invertY ? -1 : 1, 0);
  15452. this._shaderValues.setVector(BaseCamera.VIEWPORT, this._viewportParams);
  15453. this._shaderValues.setVector(BaseCamera.PROJECTION_PARAMS, this._projectionParams);
  15454. }
  15455. _applyViewProject(context, viewMat, proMat) {
  15456. var projectView;
  15457. var shaderData = this._shaderValues;
  15458. if (context.invertY) {
  15459. Matrix4x4.multiply(BaseCamera._invertYScaleMatrix, proMat, BaseCamera._invertYProjectionMatrix);
  15460. Matrix4x4.multiply(BaseCamera._invertYProjectionMatrix, viewMat, BaseCamera._invertYProjectionViewMatrix);
  15461. proMat = BaseCamera._invertYProjectionMatrix;
  15462. projectView = BaseCamera._invertYProjectionViewMatrix;
  15463. }
  15464. else {
  15465. Matrix4x4.multiply(proMat, viewMat, this._projectionViewMatrix);
  15466. projectView = this._projectionViewMatrix;
  15467. }
  15468. context.viewMatrix = viewMat;
  15469. context.projectionMatrix = proMat;
  15470. context.projectionViewMatrix = projectView;
  15471. shaderData.setMatrix4x4(BaseCamera.VIEWMATRIX, viewMat);
  15472. shaderData.setMatrix4x4(BaseCamera.PROJECTMATRIX, proMat);
  15473. shaderData.setMatrix4x4(BaseCamera.VIEWPROJECTMATRIX, projectView);
  15474. }
  15475. _updateClusterPlaneXY() {
  15476. var fieldOfView = this.fieldOfView;
  15477. var aspectRatio = this.aspectRatio;
  15478. if (this._clusterPlaneCacheFlag.x !== fieldOfView || this._clusterPlaneCacheFlag.y !== aspectRatio) {
  15479. var clusterCount = Config3D._config.lightClusterCount;
  15480. var xSlixe = clusterCount.x, ySlice = clusterCount.y;
  15481. var xCount = xSlixe + 1, yCount = ySlice + 1;
  15482. var xPlanes = this._clusterXPlanes, yPlanes = this._clusterYPlanes;
  15483. if (!xPlanes) {
  15484. xPlanes = this._clusterXPlanes = new Array(xCount);
  15485. yPlanes = this._clusterYPlanes = new Array(yCount);
  15486. for (var i = 0; i < xCount; i++)
  15487. xPlanes[i] = new Vector3();
  15488. for (var i = 0; i < yCount; i++)
  15489. yPlanes[i] = new Vector3();
  15490. }
  15491. var halfY = Math.tan((this.fieldOfView / 2) * Math.PI / 180);
  15492. var halfX = this.aspectRatio * halfY;
  15493. var yLengthPerCluster = 2 * halfY / xSlixe;
  15494. var xLengthPerCluster = 2 * halfX / ySlice;
  15495. for (var i = 0; i < xCount; i++) {
  15496. var angle = -halfX + xLengthPerCluster * i;
  15497. var bigHypot = Math.sqrt(1 + angle * angle);
  15498. var normX = 1 / bigHypot;
  15499. var xPlane = xPlanes[i];
  15500. xPlane.setValue(normX, 0, -angle * normX);
  15501. }
  15502. for (var i = 0; i < yCount; i++) {
  15503. var angle = halfY - yLengthPerCluster * i;
  15504. var bigHypot = Math.sqrt(1 + angle * angle);
  15505. var normY = -1 / bigHypot;
  15506. var yPlane = yPlanes[i];
  15507. yPlane.setValue(0, normY, -angle * normY);
  15508. }
  15509. this._clusterPlaneCacheFlag.x = fieldOfView;
  15510. this._clusterPlaneCacheFlag.y = aspectRatio;
  15511. }
  15512. }
  15513. render(shader = null, replacementTag = null) {
  15514. if (!this.activeInHierarchy)
  15515. return;
  15516. var viewport = this.viewport;
  15517. var needInternalRT = this._needInternalRenderTexture();
  15518. var gl = Laya.LayaGL.instance;
  15519. var context = RenderContext3D._instance;
  15520. var scene = context.scene = this._scene;
  15521. context.pipelineMode = "Forward";
  15522. if (needInternalRT) {
  15523. this._internalRenderTexture = RenderTexture.createFromPool(viewport.width, viewport.height, this._getRenderTextureFormat(), Laya.RenderTextureDepthFormat.DEPTH_16);
  15524. this._internalRenderTexture.filterMode = Laya.FilterMode.Bilinear;
  15525. }
  15526. else {
  15527. this._internalRenderTexture = null;
  15528. }
  15529. var shadowCasterPass;
  15530. var mainDirectLight = scene._mainDirectionLight;
  15531. var needShadowCasterPass = mainDirectLight && mainDirectLight.shadowMode !== exports.ShadowMode.None && ShadowUtils.supportShadow();
  15532. if (needShadowCasterPass) {
  15533. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT);
  15534. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW);
  15535. shadowCasterPass = ILaya3D.Scene3D._shadowCasterPass;
  15536. shadowCasterPass.update(this, mainDirectLight, ILaya3D.ShadowLightType.DirectionLight);
  15537. shadowCasterPass.render(context, scene, ILaya3D.ShadowLightType.DirectionLight);
  15538. }
  15539. else {
  15540. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW);
  15541. }
  15542. var spotMainLight = scene._mainSpotLight;
  15543. var spotneedShadowCasterPass = spotMainLight && spotMainLight.shadowMode !== exports.ShadowMode.None && ShadowUtils.supportShadow();
  15544. if (spotneedShadowCasterPass) {
  15545. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW);
  15546. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT);
  15547. shadowCasterPass = ILaya3D.Scene3D._shadowCasterPass;
  15548. shadowCasterPass.update(this, spotMainLight, ILaya3D.ShadowLightType.SpotLight);
  15549. shadowCasterPass.render(context, scene, ILaya3D.ShadowLightType.SpotLight);
  15550. }
  15551. else {
  15552. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT);
  15553. }
  15554. if (needShadowCasterPass)
  15555. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW);
  15556. if (spotneedShadowCasterPass)
  15557. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT);
  15558. context.camera = this;
  15559. context.cameraShaderValue = this._shaderValues;
  15560. Camera._updateMark++;
  15561. scene._preRenderScript();
  15562. if (needInternalRT && !this._offScreenRenderTexture && (this.clearFlag == exports.CameraClearFlags.DepthOnly || this.clearFlag == exports.CameraClearFlags.Nothing)) {
  15563. if (this._enableHDR) {
  15564. var grabTexture = RenderTexture.createFromPool(viewport.width, viewport.height, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTH_16);
  15565. grabTexture.filterMode = Laya.FilterMode.Bilinear;
  15566. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, grabTexture._getSource());
  15567. gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, viewport.x, RenderContext3D.clientHeight - (viewport.y + viewport.height), viewport.width, viewport.height);
  15568. var blit = BlitScreenQuadCMD.create(grabTexture, this._internalRenderTexture);
  15569. blit.run();
  15570. blit.recover();
  15571. RenderTexture.recoverToPool(grabTexture);
  15572. }
  15573. else {
  15574. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, this._internalRenderTexture._getSource());
  15575. gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, viewport.x, RenderContext3D.clientHeight - (viewport.y + viewport.height), viewport.width, viewport.height);
  15576. }
  15577. }
  15578. var renderTex = this._getRenderTexture();
  15579. (renderTex) && (renderTex._start());
  15580. context.viewport = viewport;
  15581. this._prepareCameraToRender();
  15582. var multiLighting = Config3D._config._multiLighting;
  15583. (multiLighting) && (Cluster.instance.update(this, (this._scene)));
  15584. this._applyViewProject(context, this.viewMatrix, this._projectionMatrix);
  15585. scene._preCulling(context, this, shader, replacementTag);
  15586. scene._clear(gl, context);
  15587. scene._renderScene(context);
  15588. scene._postRenderScript();
  15589. (renderTex) && (renderTex._end());
  15590. if (needInternalRT) {
  15591. if (this._postProcess) {
  15592. this._postProcess._render();
  15593. this._applyPostProcessCommandBuffers();
  15594. }
  15595. else if (this._enableHDR) {
  15596. var canvasWidth = this._getCanvasWidth(), canvasHeight = this._getCanvasHeight();
  15597. this._screenOffsetScale.setValue(viewport.x / canvasWidth, viewport.y / canvasHeight, viewport.width / canvasWidth, viewport.height / canvasHeight);
  15598. var blit = BlitScreenQuadCMD.create(this._internalRenderTexture, this._offScreenRenderTexture ? this._offScreenRenderTexture : null, this._screenOffsetScale);
  15599. blit.run();
  15600. blit.recover();
  15601. }
  15602. RenderTexture.recoverToPool(this._internalRenderTexture);
  15603. }
  15604. if (needShadowCasterPass || spotneedShadowCasterPass)
  15605. shadowCasterPass.cleanUp();
  15606. }
  15607. viewportPointToRay(point, out) {
  15608. Picker.calculateCursorRay(point, this.viewport, this._projectionMatrix, this.viewMatrix, null, out);
  15609. }
  15610. normalizedViewportPointToRay(point, out) {
  15611. var finalPoint = Camera._tempVector20;
  15612. var vp = this.viewport;
  15613. finalPoint.x = point.x * vp.width;
  15614. finalPoint.y = point.y * vp.height;
  15615. Picker.calculateCursorRay(finalPoint, this.viewport, this._projectionMatrix, this.viewMatrix, null, out);
  15616. }
  15617. worldToViewportPoint(position, out) {
  15618. Matrix4x4.multiply(this._projectionMatrix, this._viewMatrix, this._projectionViewMatrix);
  15619. this.viewport.project(position, this._projectionViewMatrix, out);
  15620. out.x = out.x / Laya.Laya.stage.clientScaleX;
  15621. out.y = out.y / Laya.Laya.stage.clientScaleY;
  15622. }
  15623. worldToNormalizedViewportPoint(position, out) {
  15624. Matrix4x4.multiply(this._projectionMatrix, this._viewMatrix, this._projectionViewMatrix);
  15625. this.normalizedViewport.project(position, this._projectionViewMatrix, out);
  15626. out.x = out.x / Laya.Laya.stage.clientScaleX;
  15627. out.y = out.y / Laya.Laya.stage.clientScaleY;
  15628. }
  15629. convertScreenCoordToOrthographicCoord(source, out) {
  15630. if (this._orthographic) {
  15631. var clientWidth = RenderContext3D.clientWidth;
  15632. var clientHeight = RenderContext3D.clientHeight;
  15633. var ratioX = this.orthographicVerticalSize * this.aspectRatio / clientWidth;
  15634. var ratioY = this.orthographicVerticalSize / clientHeight;
  15635. out.x = (-clientWidth / 2 + source.x * Laya.Laya.stage.clientScaleX) * ratioX;
  15636. out.y = (clientHeight / 2 - source.y * Laya.Laya.stage.clientScaleY) * ratioY;
  15637. out.z = (this.nearPlane - this.farPlane) * (source.z + 1) / 2 - this.nearPlane;
  15638. Vector3.transformCoordinate(out, this.transform.worldMatrix, out);
  15639. return true;
  15640. }
  15641. else {
  15642. return false;
  15643. }
  15644. }
  15645. destroy(destroyChild = true) {
  15646. this._offScreenRenderTexture = null;
  15647. this.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  15648. super.destroy(destroyChild);
  15649. }
  15650. addCommandBuffer(event, commandBuffer) {
  15651. switch (event) {
  15652. case Camera.CAMERAEVENT_POSTPROCESS:
  15653. this._postProcessCommandBuffers.push(commandBuffer);
  15654. commandBuffer._camera = this;
  15655. break;
  15656. default:
  15657. throw "Camera:unknown event.";
  15658. }
  15659. }
  15660. removeCommandBuffer(event, commandBuffer) {
  15661. switch (event) {
  15662. case Camera.CAMERAEVENT_POSTPROCESS:
  15663. var index = this._postProcessCommandBuffers.indexOf(commandBuffer);
  15664. if (index !== -1)
  15665. this._postProcessCommandBuffers.splice(index, 1);
  15666. break;
  15667. default:
  15668. throw "Camera:unknown event.";
  15669. }
  15670. }
  15671. removeCommandBuffers(event) {
  15672. switch (event) {
  15673. case Camera.CAMERAEVENT_POSTPROCESS:
  15674. this._postProcessCommandBuffers.length = 0;
  15675. break;
  15676. default:
  15677. throw "Camera:unknown event.";
  15678. }
  15679. }
  15680. _create() {
  15681. return new Camera();
  15682. }
  15683. }
  15684. Camera.CAMERAEVENT_POSTPROCESS = 0;
  15685. Camera._tempVector20 = new Vector2();
  15686. Camera._updateMark = 0;
  15687. class Input3D {
  15688. constructor() {
  15689. this._eventList = [];
  15690. this._mouseTouch = new MouseTouch();
  15691. this._touchPool = [];
  15692. this._touches = new SimpleSingletonList();
  15693. this._multiTouchEnabled = true;
  15694. this._pushEventList = ((e) => {
  15695. (e.cancelable) && (e.preventDefault());
  15696. this._eventList.push(e);
  15697. }).bind(this);
  15698. }
  15699. __init__(canvas, scene) {
  15700. this._scene = scene;
  15701. canvas.oncontextmenu = function (e) {
  15702. return false;
  15703. };
  15704. }
  15705. _onCanvasEvent(canvas) {
  15706. canvas.addEventListener('mousedown', this._pushEventList);
  15707. canvas.addEventListener('mouseup', this._pushEventList, true);
  15708. canvas.addEventListener('mousemove', this._pushEventList, true);
  15709. canvas.addEventListener("touchstart", this._pushEventList);
  15710. canvas.addEventListener("touchend", this._pushEventList, true);
  15711. canvas.addEventListener("touchmove", this._pushEventList, true);
  15712. canvas.addEventListener("touchcancel", this._pushEventList, true);
  15713. }
  15714. _offCanvasEvent(canvas) {
  15715. canvas.removeEventListener('mousedown', this._pushEventList);
  15716. canvas.removeEventListener('mouseup', this._pushEventList, true);
  15717. canvas.removeEventListener('mousemove', this._pushEventList, true);
  15718. canvas.removeEventListener("touchstart", this._pushEventList);
  15719. canvas.removeEventListener("touchend", this._pushEventList, true);
  15720. canvas.removeEventListener("touchmove", this._pushEventList, true);
  15721. canvas.removeEventListener("touchcancel", this._pushEventList, true);
  15722. this._eventList.length = 0;
  15723. this._touches.clear();
  15724. }
  15725. touchCount() {
  15726. return this._touches.length;
  15727. }
  15728. get multiTouchEnabled() {
  15729. return this._multiTouchEnabled;
  15730. }
  15731. set multiTouchEnabled(value) {
  15732. this._multiTouchEnabled = value;
  15733. }
  15734. _getTouch(touchID, type) {
  15735. var touch = this._touchPool[touchID];
  15736. if ((type == 0 && touch && touch._getIndexInList() != -1))
  15737. return null;
  15738. if (type == 1 && touch && (touch._getIndexInList() == -1))
  15739. return null;
  15740. if (!touch) {
  15741. touch = new Touch();
  15742. this._touchPool[touchID] = touch;
  15743. touch._identifier = touchID;
  15744. }
  15745. return touch;
  15746. }
  15747. _mouseTouchDown() {
  15748. var touch = this._mouseTouch;
  15749. var sprite = touch.sprite;
  15750. touch._pressedSprite = sprite;
  15751. touch._pressedLoopCount = Laya.Stat.loopCount;
  15752. if (sprite) {
  15753. var scripts = sprite._scripts;
  15754. if (scripts) {
  15755. for (var i = 0, n = scripts.length; i < n; i++)
  15756. scripts[i].onMouseDown();
  15757. }
  15758. }
  15759. }
  15760. _mouseTouchUp() {
  15761. var i, n;
  15762. var touch = this._mouseTouch;
  15763. var lastPressedSprite = touch._pressedSprite;
  15764. touch._pressedSprite = null;
  15765. touch._pressedLoopCount = -1;
  15766. var sprite = touch.sprite;
  15767. if (sprite) {
  15768. if (sprite === lastPressedSprite) {
  15769. var scripts = sprite._scripts;
  15770. if (scripts) {
  15771. for (i = 0, n = scripts.length; i < n; i++)
  15772. scripts[i].onMouseClick();
  15773. }
  15774. }
  15775. }
  15776. if (lastPressedSprite) {
  15777. var lastScripts = lastPressedSprite._scripts;
  15778. if (lastScripts) {
  15779. for (i = 0, n = lastScripts.length; i < n; i++)
  15780. lastScripts[i].onMouseUp();
  15781. }
  15782. }
  15783. }
  15784. _mouseTouchRayCast(cameras) {
  15785. var touchHitResult = Input3D._tempHitResult0;
  15786. var touchPos = Input3D._tempVector20;
  15787. var touchRay = Input3D._tempRay0;
  15788. touchHitResult.succeeded = false;
  15789. var x = this._mouseTouch.mousePositionX;
  15790. var y = this._mouseTouch.mousePositionY;
  15791. touchPos.x = x;
  15792. touchPos.y = y;
  15793. for (var i = cameras.length - 1; i >= 0; i--) {
  15794. var camera = cameras[i];
  15795. var viewport = camera.viewport;
  15796. if (touchPos.x >= viewport.x && touchPos.y >= viewport.y && touchPos.x <= viewport.width && touchPos.y <= viewport.height) {
  15797. camera.viewportPointToRay(touchPos, touchRay);
  15798. var sucess = this._scene._physicsSimulation.rayCast(touchRay, touchHitResult);
  15799. if (sucess || (camera.clearFlag === exports.CameraClearFlags.SolidColor || camera.clearFlag === exports.CameraClearFlags.Sky))
  15800. break;
  15801. }
  15802. }
  15803. var touch = this._mouseTouch;
  15804. var lastSprite = touch.sprite;
  15805. if (touchHitResult.succeeded) {
  15806. var touchSprite = touchHitResult.collider.owner;
  15807. touch.sprite = touchSprite;
  15808. var scripts = touchSprite._scripts;
  15809. if (lastSprite !== touchSprite) {
  15810. if (scripts) {
  15811. for (var j = 0, m = scripts.length; j < m; j++)
  15812. scripts[j].onMouseEnter();
  15813. }
  15814. }
  15815. }
  15816. else {
  15817. touch.sprite = null;
  15818. }
  15819. if (lastSprite && (lastSprite !== touchSprite)) {
  15820. var outScripts = lastSprite._scripts;
  15821. if (outScripts) {
  15822. for (j = 0, m = outScripts.length; j < m; j++)
  15823. outScripts[j].onMouseOut();
  15824. }
  15825. }
  15826. }
  15827. _changeTouches(changedTouches, flag) {
  15828. var offsetX = 0, offsetY = 0;
  15829. var lastCount = this._touches.length;
  15830. for (var j = 0, m = changedTouches.length; j < m; j++) {
  15831. var nativeTouch = changedTouches[j];
  15832. var identifier = nativeTouch.identifier;
  15833. if (!this._multiTouchEnabled && identifier !== 0)
  15834. continue;
  15835. var touch = this._getTouch(identifier, flag);
  15836. var pos = this._touchPool[identifier]._position;
  15837. var mousePoint = Input3D._tempPoint;
  15838. mousePoint.setTo(nativeTouch.pageX, nativeTouch.pageY);
  15839. Laya.ILaya.stage._canvasTransform.invertTransformPoint(mousePoint);
  15840. var posX = mousePoint.x;
  15841. var posY = mousePoint.y;
  15842. switch (flag) {
  15843. case 0:
  15844. if (!!touch)
  15845. this._touches.add(touch);
  15846. offsetX += posX;
  15847. offsetY += posY;
  15848. break;
  15849. case 1:
  15850. if (!!touch)
  15851. this._touches.remove(touch);
  15852. offsetX -= posX;
  15853. offsetY -= posY;
  15854. break;
  15855. case 2:
  15856. offsetX = posX - pos.x;
  15857. offsetY = posY - pos.y;
  15858. break;
  15859. }
  15860. pos.x = posX;
  15861. pos.y = posY;
  15862. }
  15863. var touchCount = this._touches.length;
  15864. if (touchCount === 0) {
  15865. this._mouseTouch.mousePositionX = 0;
  15866. this._mouseTouch.mousePositionY = 0;
  15867. }
  15868. else {
  15869. this._mouseTouch.mousePositionX = (this._mouseTouch.mousePositionX * lastCount + offsetX) / touchCount;
  15870. this._mouseTouch.mousePositionY = (this._mouseTouch.mousePositionY * lastCount + offsetY) / touchCount;
  15871. }
  15872. }
  15873. _update() {
  15874. var enablePhysics = Physics3D._enablePhysics && !PhysicsSimulation.disableSimulation;
  15875. var i, n, j, m;
  15876. n = this._eventList.length;
  15877. var cameras = this._scene._cameraPool;
  15878. if (n > 0) {
  15879. var rayCast = false;
  15880. for (i = 0; i < n; i++) {
  15881. var e = this._eventList[i];
  15882. switch (e.type) {
  15883. case "mousedown":
  15884. (enablePhysics) && (this._mouseTouchDown());
  15885. break;
  15886. case "mouseup":
  15887. (enablePhysics) && (this._mouseTouchUp());
  15888. break;
  15889. case "mousemove":
  15890. var mousePoint = Input3D._tempPoint;
  15891. mousePoint.setTo(e.pageX, e.pageY);
  15892. Laya.ILaya.stage._canvasTransform.invertTransformPoint(mousePoint);
  15893. this._mouseTouch.mousePositionX = mousePoint.x;
  15894. this._mouseTouch.mousePositionY = mousePoint.y;
  15895. (enablePhysics) && (rayCast = true);
  15896. break;
  15897. case "touchstart":
  15898. var lastLength = this._touches.length;
  15899. this._changeTouches(e.changedTouches, 0);
  15900. if (enablePhysics) {
  15901. (!Config3D._config.isUseCannonPhysicsEngine) && (this._mouseTouchRayCast(cameras));
  15902. (lastLength === 0) && (this._mouseTouchDown());
  15903. }
  15904. break;
  15905. case "touchend":
  15906. case "touchcancel":
  15907. this._changeTouches(e.changedTouches, 1);
  15908. (enablePhysics && this._touches.length === 0) && (this._mouseTouchUp());
  15909. break;
  15910. case "touchmove":
  15911. this._changeTouches(e.changedTouches, 2);
  15912. (enablePhysics) && (rayCast = true);
  15913. break;
  15914. default:
  15915. throw "Input3D:unkonwn event type.";
  15916. }
  15917. }
  15918. (rayCast) && (!Config3D._config.isUseCannonPhysicsEngine) && (this._mouseTouchRayCast(cameras));
  15919. this._eventList.length = 0;
  15920. }
  15921. if (enablePhysics) {
  15922. var mouseTouch = this._mouseTouch;
  15923. var pressedSprite = mouseTouch._pressedSprite;
  15924. if (pressedSprite && (Laya.Stat.loopCount > mouseTouch._pressedLoopCount)) {
  15925. var pressedScripts = pressedSprite._scripts;
  15926. if (pressedScripts) {
  15927. for (j = 0, m = pressedScripts.length; j < m; j++)
  15928. pressedScripts[j].onMouseDrag();
  15929. }
  15930. }
  15931. var touchSprite = mouseTouch.sprite;
  15932. if (touchSprite) {
  15933. var scripts = touchSprite._scripts;
  15934. if (scripts) {
  15935. for (j = 0, m = scripts.length; j < m; j++)
  15936. scripts[j].onMouseOver();
  15937. }
  15938. }
  15939. }
  15940. }
  15941. getTouch(index) {
  15942. if (index < this._touches.length) {
  15943. return this._touches.elements[index];
  15944. }
  15945. else {
  15946. return null;
  15947. }
  15948. }
  15949. }
  15950. Input3D._tempPoint = new Laya.Point();
  15951. Input3D._tempVector20 = new Vector2();
  15952. Input3D._tempRay0 = new Ray(new Vector3(), new Vector3());
  15953. Input3D._tempHitResult0 = new HitResult();
  15954. class PhysicsSettings {
  15955. constructor() {
  15956. this.flags = 0;
  15957. this.maxSubSteps = 1;
  15958. this.fixedTimeStep = 1.0 / 60.0;
  15959. }
  15960. }
  15961. class VertexPositionTexture0 {
  15962. constructor(position, textureCoordinate0) {
  15963. this._position = position;
  15964. this._textureCoordinate0 = textureCoordinate0;
  15965. }
  15966. static get vertexDeclaration() {
  15967. return VertexPositionTexture0._vertexDeclaration;
  15968. }
  15969. static __init__() {
  15970. VertexPositionTexture0._vertexDeclaration = new VertexDeclaration(20, [new VertexElement(0, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0),
  15971. new VertexElement(12, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE0)]);
  15972. }
  15973. get position() {
  15974. return this._position;
  15975. }
  15976. get textureCoordinate0() {
  15977. return this._textureCoordinate0;
  15978. }
  15979. get vertexDeclaration() {
  15980. return VertexPositionTexture0._vertexDeclaration;
  15981. }
  15982. }
  15983. class SkyDome extends SkyMesh {
  15984. constructor(stacks = 48, slices = 48) {
  15985. super();
  15986. var gl = Laya.LayaGL.instance;
  15987. this._stacks = stacks;
  15988. this._slices = slices;
  15989. var vertexDeclaration = VertexPositionTexture0.vertexDeclaration;
  15990. var vertexFloatCount = vertexDeclaration.vertexStride / 4;
  15991. var numberVertices = (this._stacks + 1) * (this._slices + 1);
  15992. var numberIndices = (3 * this._stacks * (this._slices + 1)) * 2;
  15993. var vertices = new Float32Array(numberVertices * vertexFloatCount);
  15994. var indices = new Uint16Array(numberIndices);
  15995. var stackAngle = Math.PI / this._stacks;
  15996. var sliceAngle = (Math.PI * 2.0) / this._slices;
  15997. var vertexIndex = 0;
  15998. var vertexCount = 0;
  15999. var indexCount = 0;
  16000. for (var stack = 0; stack < (this._stacks + 1); stack++) {
  16001. var r = Math.sin(stack * stackAngle);
  16002. var y = Math.cos(stack * stackAngle);
  16003. for (var slice = 0; slice < (this._slices + 1); slice++) {
  16004. var x = r * Math.sin(slice * sliceAngle);
  16005. var z = r * Math.cos(slice * sliceAngle);
  16006. vertices[vertexCount + 0] = x * SkyDome._radius;
  16007. vertices[vertexCount + 1] = y * SkyDome._radius;
  16008. vertices[vertexCount + 2] = z * SkyDome._radius;
  16009. vertices[vertexCount + 3] = -(slice / this._slices) + 0.75;
  16010. vertices[vertexCount + 4] = stack / this._stacks;
  16011. vertexCount += vertexFloatCount;
  16012. if (stack != (this._stacks - 1)) {
  16013. indices[indexCount++] = vertexIndex + 1;
  16014. indices[indexCount++] = vertexIndex;
  16015. indices[indexCount++] = vertexIndex + (this._slices + 1);
  16016. indices[indexCount++] = vertexIndex + (this._slices + 1);
  16017. indices[indexCount++] = vertexIndex;
  16018. indices[indexCount++] = vertexIndex + (this._slices);
  16019. vertexIndex++;
  16020. }
  16021. }
  16022. }
  16023. this._vertexBuffer = new VertexBuffer3D(vertices.length * 4, gl.STATIC_DRAW, false);
  16024. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  16025. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indices.length, gl.STATIC_DRAW, false);
  16026. this._vertexBuffer.setData(vertices.buffer);
  16027. this._indexBuffer.setData(indices);
  16028. var bufferState = new BufferState();
  16029. bufferState.bind();
  16030. bufferState.applyVertexBuffer(this._vertexBuffer);
  16031. bufferState.applyIndexBuffer(this._indexBuffer);
  16032. bufferState.unBind();
  16033. this._bufferState = bufferState;
  16034. }
  16035. static __init__() {
  16036. SkyDome.instance = new SkyDome();
  16037. }
  16038. get stacks() {
  16039. return this._stacks;
  16040. }
  16041. get slices() {
  16042. return this._slices;
  16043. }
  16044. _render(state) {
  16045. var gl = Laya.LayaGL.instance;
  16046. var indexCount = this._indexBuffer.indexCount;
  16047. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  16048. Laya.Stat.trianglesFaces += indexCount / 3;
  16049. Laya.Stat.renderBatches++;
  16050. }
  16051. }
  16052. SkyDome._radius = 1;
  16053. (function (TextureCubeFace) {
  16054. TextureCubeFace[TextureCubeFace["PositiveX"] = 0] = "PositiveX";
  16055. TextureCubeFace[TextureCubeFace["NegativeX"] = 1] = "NegativeX";
  16056. TextureCubeFace[TextureCubeFace["PositiveY"] = 2] = "PositiveY";
  16057. TextureCubeFace[TextureCubeFace["NegativeY"] = 3] = "NegativeY";
  16058. TextureCubeFace[TextureCubeFace["PositiveZ"] = 4] = "PositiveZ";
  16059. TextureCubeFace[TextureCubeFace["NegativeZ"] = 5] = "NegativeZ";
  16060. })(exports.TextureCubeFace || (exports.TextureCubeFace = {}));
  16061. class TextureCube extends Laya.BaseTexture {
  16062. constructor(size, format = Laya.TextureFormat.R8G8B8, mipmap = false) {
  16063. super(format, mipmap);
  16064. this._glTextureType = Laya.LayaGL.instance.TEXTURE_CUBE_MAP;
  16065. this._width = size;
  16066. this._height = size;
  16067. var gl = Laya.LayaGL.instance;
  16068. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  16069. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  16070. this._setFilterMode(this._filterMode);
  16071. this._setAnisotropy(this._anisoLevel);
  16072. if (this._mipmap) {
  16073. this._mipmapCount = Math.ceil(Math.log2(size)) + 1;
  16074. for (var i = 0; i < this._mipmapCount; i++)
  16075. this._setPixels([], i, Math.max(size >> i, 1), Math.max(size >> i, 1));
  16076. this._setGPUMemory(size * size * 4 * (1 + 1 / 3) * 6);
  16077. }
  16078. else {
  16079. this._mipmapCount = 1;
  16080. this._setGPUMemory(size * size * 4 * 6);
  16081. }
  16082. }
  16083. static get blackTexture() {
  16084. return TextureCube._blackTexture;
  16085. }
  16086. static get grayTexture() {
  16087. return TextureCube._grayTexture;
  16088. }
  16089. static __init__() {
  16090. var blackTexture = new TextureCube(1, Laya.TextureFormat.R8G8B8, false);
  16091. var grayTexture = new TextureCube(1, Laya.TextureFormat.R8G8B8, false);
  16092. var pixels = new Uint8Array(3);
  16093. pixels[0] = 0, pixels[1] = 0, pixels[2] = 0;
  16094. blackTexture.setSixSidePixels([pixels, pixels, pixels, pixels, pixels, pixels]);
  16095. blackTexture.lock = true;
  16096. pixels[0] = 128, pixels[1] = 128, pixels[2] = 128;
  16097. grayTexture.setSixSidePixels([pixels, pixels, pixels, pixels, pixels, pixels]);
  16098. grayTexture.lock = true;
  16099. TextureCube._grayTexture = grayTexture;
  16100. TextureCube._blackTexture = blackTexture;
  16101. }
  16102. static _parse(data, propertyParams = null, constructParams = null) {
  16103. var texture = constructParams ? new TextureCube(0, constructParams[0], constructParams[1]) : new TextureCube(0);
  16104. texture.setSixSideImageSources(data);
  16105. return texture;
  16106. }
  16107. static _parseBin(data, propertyParams = null, constructParams = null) {
  16108. var texture = constructParams ? new TextureCube(0, constructParams[0], constructParams[1]) : new TextureCube(0);
  16109. texture.setSixSideImageSources(data);
  16110. return texture;
  16111. }
  16112. static load(url, complete) {
  16113. Laya.ILaya.loader.create(url, complete, null, TextureCube.TEXTURECUBE);
  16114. }
  16115. get defaulteTexture() {
  16116. return TextureCube.grayTexture;
  16117. }
  16118. _setPixels(pixels, miplevel, width, height) {
  16119. var gl = Laya.LayaGL.instance;
  16120. var glFormat = this._getGLFormat();
  16121. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  16122. if (this.format === Laya.TextureFormat.R8G8B8) {
  16123. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16124. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[0]);
  16125. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[1]);
  16126. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[2]);
  16127. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[3]);
  16128. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[4]);
  16129. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[5]);
  16130. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
  16131. }
  16132. else {
  16133. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[0]);
  16134. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[1]);
  16135. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[2]);
  16136. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[3]);
  16137. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[4]);
  16138. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[5]);
  16139. }
  16140. }
  16141. setSixSideImageSources(source, premultiplyAlpha = false) {
  16142. var width;
  16143. var height;
  16144. for (var i = 0; i < 6; i++) {
  16145. var img = source[i];
  16146. if (!img) {
  16147. console.log("TextureCube: image Source can't be null.");
  16148. return;
  16149. }
  16150. var nextWidth = img.width;
  16151. var nextHeight = img.height;
  16152. if (i > 0) {
  16153. if (width !== nextWidth) {
  16154. console.log("TextureCube: each side image's width and height must same.");
  16155. return;
  16156. }
  16157. }
  16158. width = nextWidth;
  16159. height = nextHeight;
  16160. if (width !== height) {
  16161. console.log("TextureCube: each side image's width and height must same.");
  16162. return;
  16163. }
  16164. }
  16165. this._width = width;
  16166. this._height = height;
  16167. var gl = Laya.LayaGL.instance;
  16168. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  16169. var glFormat = this._getGLFormat();
  16170. if (!Laya.Render.isConchApp) {
  16171. (premultiplyAlpha) && (gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true));
  16172. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[0]);
  16173. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[1]);
  16174. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[2]);
  16175. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[3]);
  16176. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[4]);
  16177. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[5]);
  16178. (premultiplyAlpha) && (gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false));
  16179. }
  16180. else {
  16181. if (premultiplyAlpha == true) {
  16182. for (var j = 0; j < 6; j++)
  16183. source[j].setPremultiplyAlpha(premultiplyAlpha);
  16184. }
  16185. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[0]);
  16186. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[1]);
  16187. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[2]);
  16188. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[3]);
  16189. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[4]);
  16190. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[5]);
  16191. }
  16192. if (this._mipmap && this._isPot(width) && this._isPot(height)) {
  16193. gl.generateMipmap(this._glTextureType);
  16194. this._setGPUMemory(width * height * 4 * (1 + 1 / 3) * 6);
  16195. }
  16196. else {
  16197. this._setGPUMemory(width * height * 4 * 6);
  16198. }
  16199. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  16200. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  16201. this._setFilterMode(this._filterMode);
  16202. this._readyed = true;
  16203. this._activeResource();
  16204. }
  16205. setSixSidePixels(pixels, miplevel = 0) {
  16206. if (!pixels)
  16207. throw new Error("TextureCube:pixels can't be null.");
  16208. var width = Math.max(this._width >> miplevel, 1);
  16209. var height = Math.max(this._height >> miplevel, 1);
  16210. var pixelsCount = width * height * this._getFormatByteCount();
  16211. if (pixels[0].length < pixelsCount)
  16212. throw "TextureCube:pixels length should at least " + pixelsCount + ".";
  16213. this._setPixels(pixels, miplevel, width, height);
  16214. if (miplevel === 0) {
  16215. var gl = Laya.LayaGL.instance;
  16216. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  16217. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  16218. }
  16219. this._readyed = true;
  16220. this._activeResource();
  16221. }
  16222. setImageSource(face, imageSource, miplevel = 0) {
  16223. var width = this._width;
  16224. var height = this._height;
  16225. if (imageSource) {
  16226. if (width !== imageSource.width || height !== imageSource.height) {
  16227. console.log("TextureCube: imageSource's width and height must same.");
  16228. return;
  16229. }
  16230. }
  16231. var gl = Laya.LayaGL.instance;
  16232. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  16233. var glFormat = this._getGLFormat();
  16234. switch (face) {
  16235. case exports.TextureCubeFace.NegativeX:
  16236. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  16237. break;
  16238. case exports.TextureCubeFace.PositiveX:
  16239. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  16240. break;
  16241. case exports.TextureCubeFace.NegativeY:
  16242. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  16243. break;
  16244. case exports.TextureCubeFace.PositiveY:
  16245. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  16246. break;
  16247. case exports.TextureCubeFace.NegativeZ:
  16248. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  16249. break;
  16250. case exports.TextureCubeFace.PositiveZ:
  16251. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  16252. break;
  16253. }
  16254. if (this._mipmap && this._isPot(width) && this._isPot(height)) {
  16255. gl.generateMipmap(this._glTextureType);
  16256. this._setGPUMemory(width * height * 4 * (1 + 1 / 3) * 6);
  16257. }
  16258. else {
  16259. this._setGPUMemory(width * height * 4 * 6);
  16260. }
  16261. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  16262. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  16263. this._setFilterMode(this._filterMode);
  16264. this._readyed = true;
  16265. }
  16266. }
  16267. TextureCube.TEXTURECUBE = "TEXTURECUBE";
  16268. class LightQueue {
  16269. constructor() {
  16270. this._length = 0;
  16271. this._elements = [];
  16272. }
  16273. add(light) {
  16274. if (this._length === this._elements.length)
  16275. this._elements.push(light);
  16276. else
  16277. this._elements[this._length] = light;
  16278. this._length++;
  16279. }
  16280. remove(light) {
  16281. var index = this._elements.indexOf(light);
  16282. this._length--;
  16283. if (index !== this._length) {
  16284. var end = this._elements[this._length];
  16285. this._elements[index] = end;
  16286. }
  16287. }
  16288. shift() {
  16289. this._length--;
  16290. return this._elements.shift();
  16291. }
  16292. getBrightestLight() {
  16293. var maxIntIndex;
  16294. var maxIntensity = -1;
  16295. var elements = this._elements;
  16296. for (var i = 0; i < this._length; i++) {
  16297. var intensity = elements[i]._intensity;
  16298. if (maxIntensity < intensity) {
  16299. maxIntensity = intensity;
  16300. maxIntIndex = i;
  16301. }
  16302. }
  16303. return maxIntIndex;
  16304. }
  16305. normalLightOrdering(brightestIndex) {
  16306. var slements = this._elements;
  16307. var firstLight = this._elements[0];
  16308. this._elements[0] = this._elements[brightestIndex];
  16309. this._elements[brightestIndex] = firstLight;
  16310. }
  16311. }
  16312. class AlternateLightQueue extends LightQueue {
  16313. remove(light) {
  16314. var index = this._elements.indexOf(light);
  16315. this._elements.splice(index, 1);
  16316. this._length--;
  16317. }
  16318. }
  16319. class PixelLineMaterial extends Material {
  16320. constructor() {
  16321. super();
  16322. this.setShaderName("LineShader");
  16323. this._shaderValues.setVector(PixelLineMaterial.COLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  16324. }
  16325. static __initDefine__() {
  16326. }
  16327. get color() {
  16328. return this._shaderValues.getVector(PixelLineMaterial.COLOR);
  16329. }
  16330. set color(value) {
  16331. this._shaderValues.setVector(PixelLineMaterial.COLOR, value);
  16332. }
  16333. set depthWrite(value) {
  16334. this._shaderValues.setBool(PixelLineMaterial.DEPTH_WRITE, value);
  16335. }
  16336. get depthWrite() {
  16337. return this._shaderValues.getBool(PixelLineMaterial.DEPTH_WRITE);
  16338. }
  16339. set cull(value) {
  16340. this._shaderValues.setInt(PixelLineMaterial.CULL, value);
  16341. }
  16342. get cull() {
  16343. return this._shaderValues.getInt(PixelLineMaterial.CULL);
  16344. }
  16345. set blend(value) {
  16346. this._shaderValues.setInt(PixelLineMaterial.BLEND, value);
  16347. }
  16348. get blend() {
  16349. return this._shaderValues.getInt(PixelLineMaterial.BLEND);
  16350. }
  16351. set blendSrc(value) {
  16352. this._shaderValues.setInt(PixelLineMaterial.BLEND_SRC, value);
  16353. }
  16354. get blendSrc() {
  16355. return this._shaderValues.getInt(PixelLineMaterial.BLEND_SRC);
  16356. }
  16357. set blendDst(value) {
  16358. this._shaderValues.setInt(PixelLineMaterial.BLEND_DST, value);
  16359. }
  16360. get blendDst() {
  16361. return this._shaderValues.getInt(PixelLineMaterial.BLEND_DST);
  16362. }
  16363. set depthTest(value) {
  16364. this._shaderValues.setInt(PixelLineMaterial.DEPTH_TEST, value);
  16365. }
  16366. get depthTest() {
  16367. return this._shaderValues.getInt(PixelLineMaterial.DEPTH_TEST);
  16368. }
  16369. clone() {
  16370. var dest = new PixelLineMaterial();
  16371. this.cloneTo(dest);
  16372. return dest;
  16373. }
  16374. }
  16375. PixelLineMaterial.COLOR = Shader3D.propertyNameToID("u_Color");
  16376. PixelLineMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  16377. PixelLineMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  16378. PixelLineMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  16379. PixelLineMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  16380. PixelLineMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  16381. PixelLineMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  16382. class BoundBox {
  16383. constructor(min, max) {
  16384. this.min = min;
  16385. this.max = max;
  16386. }
  16387. _rotateExtents(extents, rotation, out) {
  16388. var extentsX = extents.x;
  16389. var extentsY = extents.y;
  16390. var extentsZ = extents.z;
  16391. var matElements = rotation.elements;
  16392. out.x = Math.abs(matElements[0] * extentsX) + Math.abs(matElements[4] * extentsY) + Math.abs(matElements[8] * extentsZ);
  16393. out.y = Math.abs(matElements[1] * extentsX) + Math.abs(matElements[5] * extentsY) + Math.abs(matElements[9] * extentsZ);
  16394. out.z = Math.abs(matElements[2] * extentsX) + Math.abs(matElements[6] * extentsY) + Math.abs(matElements[10] * extentsZ);
  16395. }
  16396. getCorners(corners) {
  16397. corners.length = 8;
  16398. var minX = this.min.x;
  16399. var minY = this.min.y;
  16400. var minZ = this.min.z;
  16401. var maxX = this.max.x;
  16402. var maxY = this.max.y;
  16403. var maxZ = this.max.z;
  16404. corners[0] = new Vector3(minX, maxY, maxZ);
  16405. corners[1] = new Vector3(maxX, maxY, maxZ);
  16406. corners[2] = new Vector3(maxX, minY, maxZ);
  16407. corners[3] = new Vector3(minX, minY, maxZ);
  16408. corners[4] = new Vector3(minX, maxY, minZ);
  16409. corners[5] = new Vector3(maxX, maxY, minZ);
  16410. corners[6] = new Vector3(maxX, minY, minZ);
  16411. corners[7] = new Vector3(minX, minY, minZ);
  16412. }
  16413. getCenter(out) {
  16414. Vector3.add(this.min, this.max, out);
  16415. Vector3.scale(out, 0.5, out);
  16416. }
  16417. getExtent(out) {
  16418. Vector3.subtract(this.max, this.min, out);
  16419. Vector3.scale(out, 0.5, out);
  16420. }
  16421. setCenterAndExtent(center, extent) {
  16422. Vector3.subtract(center, extent, this.min);
  16423. Vector3.add(center, extent, this.max);
  16424. }
  16425. tranform(matrix, out) {
  16426. var center = BoundBox._tempVector30;
  16427. var extent = BoundBox._tempVector31;
  16428. this.getCenter(center);
  16429. this.getExtent(extent);
  16430. Vector3.transformCoordinate(center, matrix, center);
  16431. this._rotateExtents(extent, matrix, extent);
  16432. out.setCenterAndExtent(center, extent);
  16433. }
  16434. toDefault() {
  16435. this.min.toDefault();
  16436. this.max.toDefault();
  16437. }
  16438. static createfromPoints(points, out) {
  16439. if (points == null)
  16440. throw new Error("points");
  16441. var min = out.min;
  16442. var max = out.max;
  16443. min.x = Number.MAX_VALUE;
  16444. min.y = Number.MAX_VALUE;
  16445. min.z = Number.MAX_VALUE;
  16446. max.x = -Number.MAX_VALUE;
  16447. max.y = -Number.MAX_VALUE;
  16448. max.z = -Number.MAX_VALUE;
  16449. for (var i = 0, n = points.length; i < n; ++i) {
  16450. Vector3.min(min, points[i], min);
  16451. Vector3.max(max, points[i], max);
  16452. }
  16453. }
  16454. static merge(box1, box2, out) {
  16455. Vector3.min(box1.min, box2.min, out.min);
  16456. Vector3.max(box1.max, box2.max, out.max);
  16457. }
  16458. cloneTo(destObject) {
  16459. var dest = destObject;
  16460. this.min.cloneTo(dest.min);
  16461. this.max.cloneTo(dest.max);
  16462. }
  16463. clone() {
  16464. var dest = new BoundBox(new Vector3(), new Vector3());
  16465. this.cloneTo(dest);
  16466. return dest;
  16467. }
  16468. }
  16469. BoundBox._tempVector30 = new Vector3();
  16470. BoundBox._tempVector31 = new Vector3();
  16471. class Bounds {
  16472. constructor(min, max) {
  16473. this._updateFlag = 0;
  16474. this._center = new Vector3();
  16475. this._extent = new Vector3();
  16476. this._boundBox = new BoundBox(new Vector3(), new Vector3());
  16477. min.cloneTo(this._boundBox.min);
  16478. max.cloneTo(this._boundBox.max);
  16479. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  16480. }
  16481. setMin(value) {
  16482. var min = this._boundBox.min;
  16483. if (value !== min)
  16484. value.cloneTo(min);
  16485. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  16486. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  16487. }
  16488. getMin() {
  16489. var min = this._boundBox.min;
  16490. if (this._getUpdateFlag(Bounds._UPDATE_MIN)) {
  16491. this._getMin(this.getCenter(), this.getExtent(), min);
  16492. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  16493. }
  16494. return min;
  16495. }
  16496. setMax(value) {
  16497. var max = this._boundBox.max;
  16498. if (value !== max)
  16499. value.cloneTo(max);
  16500. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  16501. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  16502. }
  16503. getMax() {
  16504. var max = this._boundBox.max;
  16505. if (this._getUpdateFlag(Bounds._UPDATE_MAX)) {
  16506. this._getMax(this.getCenter(), this.getExtent(), max);
  16507. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  16508. }
  16509. return max;
  16510. }
  16511. setCenter(value) {
  16512. if (value !== this._center)
  16513. value.cloneTo(this._center);
  16514. this._setUpdateFlag(Bounds._UPDATE_MIN | Bounds._UPDATE_MAX, true);
  16515. this._setUpdateFlag(Bounds._UPDATE_CENTER, false);
  16516. }
  16517. getCenter() {
  16518. if (this._getUpdateFlag(Bounds._UPDATE_CENTER)) {
  16519. this._getCenter(this.getMin(), this.getMax(), this._center);
  16520. this._setUpdateFlag(Bounds._UPDATE_CENTER, false);
  16521. }
  16522. return this._center;
  16523. }
  16524. setExtent(value) {
  16525. if (value !== this._extent)
  16526. value.cloneTo(this._extent);
  16527. this._setUpdateFlag(Bounds._UPDATE_MIN | Bounds._UPDATE_MAX, true);
  16528. this._setUpdateFlag(Bounds._UPDATE_EXTENT, false);
  16529. }
  16530. getExtent() {
  16531. if (this._getUpdateFlag(Bounds._UPDATE_EXTENT)) {
  16532. this._getExtent(this.getMin(), this.getMax(), this._extent);
  16533. this._setUpdateFlag(Bounds._UPDATE_EXTENT, false);
  16534. }
  16535. return this._extent;
  16536. }
  16537. _getUpdateFlag(type) {
  16538. return (this._updateFlag & type) != 0;
  16539. }
  16540. _setUpdateFlag(type, value) {
  16541. if (value)
  16542. this._updateFlag |= type;
  16543. else
  16544. this._updateFlag &= ~type;
  16545. }
  16546. _getCenter(min, max, out) {
  16547. Vector3.add(min, max, out);
  16548. Vector3.scale(out, 0.5, out);
  16549. }
  16550. _getExtent(min, max, out) {
  16551. Vector3.subtract(max, min, out);
  16552. Vector3.scale(out, 0.5, out);
  16553. }
  16554. _getMin(center, extent, out) {
  16555. Vector3.subtract(center, extent, out);
  16556. }
  16557. _getMax(center, extent, out) {
  16558. Vector3.add(center, extent, out);
  16559. }
  16560. _rotateExtents(extents, rotation, out) {
  16561. var extentsX = extents.x;
  16562. var extentsY = extents.y;
  16563. var extentsZ = extents.z;
  16564. var matE = rotation.elements;
  16565. out.x = Math.abs(matE[0] * extentsX) + Math.abs(matE[4] * extentsY) + Math.abs(matE[8] * extentsZ);
  16566. out.y = Math.abs(matE[1] * extentsX) + Math.abs(matE[5] * extentsY) + Math.abs(matE[9] * extentsZ);
  16567. out.z = Math.abs(matE[2] * extentsX) + Math.abs(matE[6] * extentsY) + Math.abs(matE[10] * extentsZ);
  16568. }
  16569. _tranform(matrix, out) {
  16570. var outCen = out._center;
  16571. var outExt = out._extent;
  16572. Vector3.transformCoordinate(this.getCenter(), matrix, outCen);
  16573. this._rotateExtents(this.getExtent(), matrix, outExt);
  16574. out._boundBox.setCenterAndExtent(outCen, outExt);
  16575. out._updateFlag = 0;
  16576. }
  16577. _getBoundBox() {
  16578. if (this._updateFlag & Bounds._UPDATE_MIN) {
  16579. var min = this._boundBox.min;
  16580. this._getMin(this.getCenter(), this.getExtent(), min);
  16581. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  16582. }
  16583. if (this._updateFlag & Bounds._UPDATE_MAX) {
  16584. var max = this._boundBox.max;
  16585. this._getMax(this.getCenter(), this.getExtent(), max);
  16586. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  16587. }
  16588. return this._boundBox;
  16589. }
  16590. cloneTo(destObject) {
  16591. var destBounds = destObject;
  16592. this.getMin().cloneTo(destBounds._boundBox.min);
  16593. this.getMax().cloneTo(destBounds._boundBox.max);
  16594. this.getCenter().cloneTo(destBounds._center);
  16595. this.getExtent().cloneTo(destBounds._extent);
  16596. destBounds._updateFlag = 0;
  16597. }
  16598. clone() {
  16599. var dest = new Bounds(new Vector3(), new Vector3());
  16600. this.cloneTo(dest);
  16601. return dest;
  16602. }
  16603. }
  16604. Bounds._UPDATE_MIN = 0x01;
  16605. Bounds._UPDATE_MAX = 0x02;
  16606. Bounds._UPDATE_CENTER = 0x04;
  16607. Bounds._UPDATE_EXTENT = 0x08;
  16608. class GeometryElement {
  16609. constructor() {
  16610. this._destroyed = false;
  16611. }
  16612. get destroyed() {
  16613. return this._destroyed;
  16614. }
  16615. _getType() {
  16616. throw "GeometryElement:must override it.";
  16617. }
  16618. _prepareRender(state) {
  16619. return true;
  16620. }
  16621. _render(state) {
  16622. throw "GeometryElement:must override it.";
  16623. }
  16624. destroy() {
  16625. if (this._destroyed)
  16626. return;
  16627. this._destroyed = true;
  16628. }
  16629. }
  16630. GeometryElement._typeCounter = 0;
  16631. class PixelLineVertex {
  16632. constructor() {
  16633. }
  16634. static get vertexDeclaration() {
  16635. return PixelLineVertex._vertexDeclaration;
  16636. }
  16637. static __init__() {
  16638. PixelLineVertex._vertexDeclaration = new VertexDeclaration(28, [new VertexElement(0, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0),
  16639. new VertexElement(12, VertexElementFormat.Vector4, VertexMesh.MESH_COLOR0)]);
  16640. }
  16641. get vertexDeclaration() {
  16642. return PixelLineVertex._vertexDeclaration;
  16643. }
  16644. }
  16645. class PixelLineFilter extends GeometryElement {
  16646. constructor(owner, maxLineCount) {
  16647. super();
  16648. this._floatCountPerVertices = 7;
  16649. this._minUpdate = Number.MAX_VALUE;
  16650. this._maxUpdate = Number.MIN_VALUE;
  16651. this._bufferState = new BufferState();
  16652. this._floatBound = new Float32Array(6);
  16653. this._calculateBound = false;
  16654. this._maxLineCount = 0;
  16655. this._lineCount = 0;
  16656. var pointCount = maxLineCount * 2;
  16657. this._owner = owner;
  16658. this._maxLineCount = maxLineCount;
  16659. this._vertices = new Float32Array(pointCount * this._floatCountPerVertices);
  16660. this._vertexBuffer = new VertexBuffer3D(PixelLineVertex.vertexDeclaration.vertexStride * pointCount, Laya.LayaGL.instance.STATIC_DRAW, false);
  16661. this._vertexBuffer.vertexDeclaration = PixelLineVertex.vertexDeclaration;
  16662. this._bufferState.bind();
  16663. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  16664. this._bufferState.unBind();
  16665. var min = PixelLineFilter._tempVector0;
  16666. var max = PixelLineFilter._tempVector1;
  16667. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16668. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16669. this._bounds = new Bounds(min, max);
  16670. }
  16671. _getType() {
  16672. return PixelLineFilter._type;
  16673. }
  16674. _resizeLineData(maxCount) {
  16675. var pointCount = maxCount * 2;
  16676. var lastVertices = this._vertices;
  16677. this._vertexBuffer.destroy();
  16678. this._maxLineCount = maxCount;
  16679. var vertexCount = pointCount * this._floatCountPerVertices;
  16680. this._vertices = new Float32Array(vertexCount);
  16681. this._vertexBuffer = new VertexBuffer3D(PixelLineVertex.vertexDeclaration.vertexStride * pointCount, Laya.LayaGL.instance.STATIC_DRAW, false);
  16682. this._vertexBuffer.vertexDeclaration = PixelLineVertex.vertexDeclaration;
  16683. if (vertexCount < lastVertices.length) {
  16684. this._vertices.set(new Float32Array(lastVertices.buffer, 0, vertexCount));
  16685. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, vertexCount * 4);
  16686. }
  16687. else {
  16688. this._vertices.set(lastVertices);
  16689. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, lastVertices.length * 4);
  16690. }
  16691. this._bufferState.bind();
  16692. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  16693. this._bufferState.unBind();
  16694. }
  16695. _updateLineVertices(offset, startPosition, endPosition, startColor, endColor) {
  16696. if (startPosition) {
  16697. this._vertices[offset + 0] = startPosition.x;
  16698. this._vertices[offset + 1] = startPosition.y;
  16699. this._vertices[offset + 2] = startPosition.z;
  16700. }
  16701. if (startColor) {
  16702. this._vertices[offset + 3] = startColor.r;
  16703. this._vertices[offset + 4] = startColor.g;
  16704. this._vertices[offset + 5] = startColor.b;
  16705. this._vertices[offset + 6] = startColor.a;
  16706. }
  16707. if (endPosition) {
  16708. this._vertices[offset + 7] = endPosition.x;
  16709. this._vertices[offset + 8] = endPosition.y;
  16710. this._vertices[offset + 9] = endPosition.z;
  16711. }
  16712. if (endColor) {
  16713. this._vertices[offset + 10] = endColor.r;
  16714. this._vertices[offset + 11] = endColor.g;
  16715. this._vertices[offset + 12] = endColor.b;
  16716. this._vertices[offset + 13] = endColor.a;
  16717. }
  16718. this._minUpdate = Math.min(this._minUpdate, offset);
  16719. this._maxUpdate = Math.max(this._maxUpdate, offset + this._floatCountPerVertices * 2);
  16720. var bounds = this._bounds;
  16721. var floatBound = this._floatBound;
  16722. var min = bounds.getMin(), max = bounds.getMax();
  16723. Vector3.min(min, startPosition, min);
  16724. Vector3.min(min, endPosition, min);
  16725. Vector3.max(max, startPosition, max);
  16726. Vector3.max(max, endPosition, max);
  16727. bounds.setMin(min);
  16728. bounds.setMax(max);
  16729. floatBound[0] = min.x, floatBound[1] = min.y, floatBound[2] = min.z;
  16730. floatBound[3] = max.x, floatBound[4] = max.y, floatBound[5] = max.z;
  16731. }
  16732. _reCalculateBound() {
  16733. if (this._calculateBound) {
  16734. var vertices = this._vertices;
  16735. var min = PixelLineFilter._tempVector0;
  16736. var max = PixelLineFilter._tempVector1;
  16737. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16738. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16739. for (var i = 0; i < this._lineCount * 2; ++i) {
  16740. var offset = this._floatCountPerVertices * i;
  16741. var x = vertices[offset + 0], y = vertices[offset + 1], z = vertices[offset + 2];
  16742. min.x = Math.min(x, min.x);
  16743. min.y = Math.min(y, min.y);
  16744. min.z = Math.min(z, min.z);
  16745. max.x = Math.max(x, max.x);
  16746. max.y = Math.max(y, max.y);
  16747. max.z = Math.max(z, max.z);
  16748. }
  16749. this._bounds.setMin(min);
  16750. this._bounds.setMax(max);
  16751. var floatBound = this._floatBound;
  16752. floatBound[0] = min.x, floatBound[1] = min.y, floatBound[2] = min.z;
  16753. floatBound[3] = max.x, floatBound[4] = max.y, floatBound[5] = max.z;
  16754. this._calculateBound = false;
  16755. }
  16756. }
  16757. _removeLineData(index) {
  16758. var floatCount = this._floatCountPerVertices * 2;
  16759. var nextIndex = index + 1;
  16760. var offset = index * floatCount;
  16761. var vertices = this._vertices;
  16762. var rightPartVertices = new Float32Array(vertices.buffer, nextIndex * floatCount * 4, (this._lineCount - nextIndex) * floatCount);
  16763. vertices.set(rightPartVertices, offset);
  16764. this._minUpdate = Math.min(this._minUpdate, offset);
  16765. this._maxUpdate = Math.max(this._maxUpdate, offset + rightPartVertices.length);
  16766. this._lineCount--;
  16767. var floatBound = this._floatBound;
  16768. var startX = vertices[offset], startY = vertices[offset + 1], startZ = vertices[offset + 2];
  16769. var endX = vertices[offset + 7], endY = vertices[offset + 8], endZ = vertices[offset + 9];
  16770. var minX = floatBound[0], minY = floatBound[1], minZ = floatBound[2];
  16771. var maxX = floatBound[3], maxY = floatBound[4], maxZ = floatBound[5];
  16772. if ((startX === minX) || (startX === maxX) || (startY === minY) || (startY === maxY) || (startZ === minZ) || (startZ === maxZ) ||
  16773. (endX === minX) || (endX === maxX) || (endY === minY) || (endY === maxY) || (endZ === minZ) || (endZ === maxZ))
  16774. this._calculateBound = true;
  16775. }
  16776. _updateLineData(index, startPosition, endPosition, startColor, endColor) {
  16777. var floatCount = this._floatCountPerVertices * 2;
  16778. this._updateLineVertices(index * floatCount, startPosition, endPosition, startColor, endColor);
  16779. }
  16780. _updateLineDatas(index, data) {
  16781. var floatCount = this._floatCountPerVertices * 2;
  16782. var count = data.length;
  16783. for (var i = 0; i < count; i++) {
  16784. var line = data[i];
  16785. this._updateLineVertices((index + i) * floatCount, line.startPosition, line.endPosition, line.startColor, line.endColor);
  16786. }
  16787. }
  16788. _getLineData(index, out) {
  16789. var startPosition = out.startPosition;
  16790. var startColor = out.startColor;
  16791. var endPosition = out.endPosition;
  16792. var endColor = out.endColor;
  16793. var vertices = this._vertices;
  16794. var offset = index * this._floatCountPerVertices * 2;
  16795. startPosition.x = vertices[offset + 0];
  16796. startPosition.y = vertices[offset + 1];
  16797. startPosition.z = vertices[offset + 2];
  16798. startColor.r = vertices[offset + 3];
  16799. startColor.g = vertices[offset + 4];
  16800. startColor.b = vertices[offset + 5];
  16801. startColor.a = vertices[offset + 6];
  16802. endPosition.x = vertices[offset + 7];
  16803. endPosition.y = vertices[offset + 8];
  16804. endPosition.z = vertices[offset + 9];
  16805. endColor.r = vertices[offset + 10];
  16806. endColor.g = vertices[offset + 11];
  16807. endColor.b = vertices[offset + 12];
  16808. endColor.a = vertices[offset + 13];
  16809. }
  16810. _prepareRender(state) {
  16811. return true;
  16812. }
  16813. _render(state) {
  16814. if (this._minUpdate !== Number.MAX_VALUE && this._maxUpdate !== Number.MIN_VALUE) {
  16815. this._vertexBuffer.setData(this._vertices.buffer, this._minUpdate * 4, this._minUpdate * 4, (this._maxUpdate - this._minUpdate) * 4);
  16816. this._minUpdate = Number.MAX_VALUE;
  16817. this._maxUpdate = Number.MIN_VALUE;
  16818. }
  16819. if (this._lineCount > 0) {
  16820. this._bufferState.bind();
  16821. var gl = Laya.LayaGL.instance;
  16822. gl.drawArrays(gl.LINES, 0, this._lineCount * 2);
  16823. Laya.Stat.renderBatches++;
  16824. }
  16825. }
  16826. destroy() {
  16827. if (this._destroyed)
  16828. return;
  16829. super.destroy();
  16830. this._bufferState.destroy();
  16831. this._vertexBuffer.destroy();
  16832. this._bufferState = null;
  16833. this._vertexBuffer = null;
  16834. this._vertices = null;
  16835. }
  16836. }
  16837. PixelLineFilter._tempVector0 = new Vector3();
  16838. PixelLineFilter._tempVector1 = new Vector3();
  16839. PixelLineFilter._type = GeometryElement._typeCounter++;
  16840. class RenderableSprite3D extends Sprite3D {
  16841. constructor(name) {
  16842. super(name);
  16843. }
  16844. static __init__() {
  16845. RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW = Shader3D.getDefineByName("RECEIVESHADOW");
  16846. RenderableSprite3D.SAHDERDEFINE_LIGHTMAP = Shader3D.getDefineByName("LIGHTMAP");
  16847. RenderableSprite3D.SHADERDEFINE_LIGHTMAP_DIRECTIONAL = Shader3D.getDefineByName("LIGHTMAP_DIRECTIONAL");
  16848. }
  16849. _onInActive() {
  16850. super._onInActive();
  16851. this._scene._removeRenderObject(this._render);
  16852. }
  16853. _onActive() {
  16854. super._onActive();
  16855. this._scene._addRenderObject(this._render);
  16856. }
  16857. _onActiveInScene() {
  16858. super._onActiveInScene();
  16859. if (ILaya3D.Laya3D._editerEnvironment) {
  16860. var scene = this._scene;
  16861. var pickColor = new Vector4();
  16862. scene._allotPickColorByID(this.id, pickColor);
  16863. scene._pickIdToSprite[this.id] = this;
  16864. this._render._shaderValues.setVector(RenderableSprite3D.PICKCOLOR, pickColor);
  16865. }
  16866. }
  16867. _addToInitStaticBatchManager() {
  16868. }
  16869. _setBelongScene(scene) {
  16870. super._setBelongScene(scene);
  16871. this._render._setBelongScene(scene);
  16872. }
  16873. _setUnBelongScene() {
  16874. this._render._shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  16875. super._setUnBelongScene();
  16876. }
  16877. _changeHierarchyAnimator(animator) {
  16878. if (this._hierarchyAnimator) {
  16879. var renderableSprites = this._hierarchyAnimator._renderableSprites;
  16880. renderableSprites.splice(renderableSprites.indexOf(this), 1);
  16881. }
  16882. if (animator)
  16883. animator._renderableSprites.push(this);
  16884. super._changeHierarchyAnimator(animator);
  16885. }
  16886. destroy(destroyChild = true) {
  16887. super.destroy(destroyChild);
  16888. this._render._destroy();
  16889. this._render = null;
  16890. }
  16891. _create() {
  16892. return new RenderableSprite3D(this.name);
  16893. }
  16894. }
  16895. RenderableSprite3D.LIGHTMAPSCALEOFFSET = Shader3D.propertyNameToID("u_LightmapScaleOffset");
  16896. RenderableSprite3D.LIGHTMAP = Shader3D.propertyNameToID("u_LightMap");
  16897. RenderableSprite3D.LIGHTMAP_DIRECTION = Shader3D.propertyNameToID("u_LightMapDirection");
  16898. RenderableSprite3D.PICKCOLOR = Shader3D.propertyNameToID("u_PickColor");
  16899. class BatchMark {
  16900. constructor() {
  16901. this.updateMark = -1;
  16902. this.indexInList = -1;
  16903. this.batched = false;
  16904. }
  16905. }
  16906. class SubMeshInstanceBatch extends GeometryElement {
  16907. constructor() {
  16908. super();
  16909. this.maxInstanceCount = 1024;
  16910. this.instanceWorldMatrixData = new Float32Array(this.maxInstanceCount * 16);
  16911. this.instanceMVPMatrixData = new Float32Array(this.maxInstanceCount * 16);
  16912. var gl = Laya.LayaGL.instance;
  16913. this.instanceWorldMatrixBuffer = new VertexBuffer3D(this.instanceWorldMatrixData.length * 4, gl.DYNAMIC_DRAW);
  16914. this.instanceMVPMatrixBuffer = new VertexBuffer3D(this.instanceMVPMatrixData.length * 4, gl.DYNAMIC_DRAW);
  16915. this.instanceWorldMatrixBuffer.vertexDeclaration = VertexMesh.instanceWorldMatrixDeclaration;
  16916. this.instanceMVPMatrixBuffer.vertexDeclaration = VertexMesh.instanceMVPMatrixDeclaration;
  16917. }
  16918. static __init__() {
  16919. SubMeshInstanceBatch.instance = new SubMeshInstanceBatch();
  16920. }
  16921. _render(state) {
  16922. var gl = Laya.LayaGL.instance;
  16923. var element = state.renderElement;
  16924. var subMesh = element.instanceSubMesh;
  16925. var count = element.instanceBatchElementList.length;
  16926. var indexCount = subMesh._indexCount;
  16927. subMesh._mesh._instanceBufferState.bind();
  16928. Laya.LayaGL.layaGPUInstance.drawElementsInstanced(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, subMesh._indexStart * 2, count);
  16929. Laya.Stat.renderBatches++;
  16930. Laya.Stat.savedRenderBatches += count - 1;
  16931. Laya.Stat.trianglesFaces += indexCount * count / 3;
  16932. }
  16933. }
  16934. class RenderElement {
  16935. constructor() {
  16936. this.renderSubShader = null;
  16937. this.renderType = RenderElement.RENDERTYPE_NORMAL;
  16938. }
  16939. getInvertFront() {
  16940. return this._transform._isFrontFaceInvert;
  16941. }
  16942. setTransform(transform) {
  16943. this._transform = transform;
  16944. }
  16945. setGeometry(geometry) {
  16946. this._geometry = geometry;
  16947. }
  16948. addToOpaqueRenderQueue(context, queue) {
  16949. queue.elements.add(this);
  16950. }
  16951. addToTransparentRenderQueue(context, queue) {
  16952. queue.elements.add(this);
  16953. queue.lastTransparentBatched = false;
  16954. queue.lastTransparentRenderElement = this;
  16955. }
  16956. _update(scene, context, customShader, replacementTag) {
  16957. if (this.material) {
  16958. var subShader = this.material._shader.getSubShaderAt(0);
  16959. this.renderSubShader = null;
  16960. if (customShader) {
  16961. if (replacementTag) {
  16962. var oriTag = subShader.getFlag(replacementTag);
  16963. if (oriTag) {
  16964. var customSubShaders = customShader._subShaders;
  16965. for (var k = 0, p = customSubShaders.length; k < p; k++) {
  16966. var customSubShader = customSubShaders[k];
  16967. if (oriTag === customSubShader.getFlag(replacementTag)) {
  16968. this.renderSubShader = customSubShader;
  16969. break;
  16970. }
  16971. }
  16972. if (!this.renderSubShader)
  16973. return;
  16974. }
  16975. else {
  16976. return;
  16977. }
  16978. }
  16979. else {
  16980. this.renderSubShader = customShader.getSubShaderAt(0);
  16981. }
  16982. }
  16983. else {
  16984. this.renderSubShader = subShader;
  16985. }
  16986. var renderQueue = scene._getRenderQueue(this.material.renderQueue);
  16987. if (renderQueue.isTransparent)
  16988. this.addToTransparentRenderQueue(context, renderQueue);
  16989. else
  16990. this.addToOpaqueRenderQueue(context, renderQueue);
  16991. }
  16992. }
  16993. _render(context) {
  16994. var forceInvertFace = context.invertY;
  16995. var lastStateMaterial, lastStateShaderInstance, lastStateRender;
  16996. var updateMark = Camera._updateMark;
  16997. var scene = context.scene;
  16998. var cameraShaderValue = context.cameraShaderValue;
  16999. var transform = this._transform;
  17000. var geometry = this._geometry;
  17001. context.renderElement = this;
  17002. var updateRender = updateMark !== this.render._updateMark || this.renderType !== this.render._updateRenderType;
  17003. if (updateRender) {
  17004. this.render._renderUpdate(context, transform);
  17005. this.render._renderUpdateWithCamera(context, transform);
  17006. this.render._updateMark = updateMark;
  17007. this.render._updateRenderType = this.renderType;
  17008. }
  17009. else {
  17010. if (this.renderType == RenderElement.RENDERTYPE_INSTANCEBATCH) {
  17011. this.render._renderUpdate(context, transform);
  17012. this.render._renderUpdateWithCamera(context, transform);
  17013. }
  17014. }
  17015. var currentPipelineMode = context.pipelineMode;
  17016. if (geometry._prepareRender(context)) {
  17017. var passes = this.renderSubShader._passes;
  17018. for (var j = 0, m = passes.length; j < m; j++) {
  17019. var pass = passes[j];
  17020. if (pass._pipelineMode !== currentPipelineMode)
  17021. continue;
  17022. var comDef = RenderElement._compileDefine;
  17023. scene._shaderValues._defineDatas.cloneTo(comDef);
  17024. comDef.addDefineDatas(this.render._shaderValues._defineDatas);
  17025. comDef.addDefineDatas(this.material._shaderValues._defineDatas);
  17026. var shaderIns = context.shader = pass.withCompile(comDef);
  17027. var switchShader = shaderIns.bind();
  17028. var switchUpdateMark = (updateMark !== shaderIns._uploadMark);
  17029. var uploadScene = (shaderIns._uploadScene !== scene) || switchUpdateMark;
  17030. if (uploadScene || switchShader) {
  17031. shaderIns.uploadUniforms(shaderIns._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  17032. shaderIns._uploadScene = scene;
  17033. }
  17034. var uploadSprite3D = (shaderIns._uploadRender !== this.render || shaderIns._uploadRenderType !== this.renderType) || switchUpdateMark;
  17035. if (uploadSprite3D || switchShader) {
  17036. shaderIns.uploadUniforms(shaderIns._spriteUniformParamsMap, this.render._shaderValues, uploadSprite3D);
  17037. shaderIns._uploadRender = this.render;
  17038. shaderIns._uploadRenderType = this.renderType;
  17039. }
  17040. var uploadCamera = shaderIns._uploadCameraShaderValue !== cameraShaderValue || switchUpdateMark;
  17041. if (uploadCamera || switchShader) {
  17042. shaderIns.uploadUniforms(shaderIns._cameraUniformParamsMap, cameraShaderValue, uploadCamera);
  17043. shaderIns._uploadCameraShaderValue = cameraShaderValue;
  17044. }
  17045. var uploadMaterial = (shaderIns._uploadMaterial !== this.material) || switchUpdateMark;
  17046. if (uploadMaterial || switchShader) {
  17047. shaderIns.uploadUniforms(shaderIns._materialUniformParamsMap, this.material._shaderValues, uploadMaterial);
  17048. shaderIns._uploadMaterial = this.material;
  17049. }
  17050. var matValues = this.material._shaderValues;
  17051. if (lastStateMaterial !== this.material || lastStateShaderInstance !== shaderIns) {
  17052. shaderIns.uploadRenderStateBlendDepth(matValues);
  17053. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, this.getInvertFront());
  17054. lastStateMaterial = this.material;
  17055. lastStateShaderInstance = shaderIns;
  17056. lastStateRender = this.render;
  17057. }
  17058. else {
  17059. if (lastStateRender !== this.render) {
  17060. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, this.getInvertFront());
  17061. lastStateRender = this.render;
  17062. }
  17063. }
  17064. geometry._render(context);
  17065. shaderIns._uploadMark = updateMark;
  17066. }
  17067. }
  17068. if (this.renderType !== RenderElement.RENDERTYPE_NORMAL)
  17069. this.render._revertBatchRenderUpdate(context);
  17070. }
  17071. destroy() {
  17072. this._transform = null;
  17073. this._geometry = null;
  17074. this.material = null;
  17075. this.render = null;
  17076. }
  17077. }
  17078. RenderElement.RENDERTYPE_NORMAL = 0;
  17079. RenderElement.RENDERTYPE_STATICBATCH = 1;
  17080. RenderElement.RENDERTYPE_INSTANCEBATCH = 2;
  17081. RenderElement.RENDERTYPE_VERTEXBATCH = 3;
  17082. RenderElement._compileDefine = new DefineDatas();
  17083. class SubMeshRenderElement extends RenderElement {
  17084. constructor() {
  17085. super();
  17086. this._dynamicWorldPositionNormalNeedUpdate = true;
  17087. }
  17088. _onWorldMatrixChanged() {
  17089. this._dynamicWorldPositionNormalNeedUpdate = true;
  17090. }
  17091. _computeWorldPositionsAndNormals(positionOffset, normalOffset, multiSubMesh, vertexCount) {
  17092. if (this._dynamicWorldPositionNormalNeedUpdate) {
  17093. var subMesh = this._geometry;
  17094. var vertexBuffer = subMesh._vertexBuffer;
  17095. var vertexFloatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  17096. var oriVertexes = vertexBuffer.getFloat32Data();
  17097. var worldMat = this._transform.worldMatrix;
  17098. var rotation = this._transform.rotation;
  17099. var indices = subMesh._indices;
  17100. for (var i = 0; i < vertexCount; i++) {
  17101. var index = multiSubMesh ? indices[i] : i;
  17102. var oriOffset = index * vertexFloatCount;
  17103. var bakeOffset = i * 3;
  17104. Utils3D.transformVector3ArrayToVector3ArrayCoordinate(oriVertexes, oriOffset + positionOffset, worldMat, this._dynamicWorldPositions, bakeOffset);
  17105. (normalOffset !== -1) && (Utils3D.transformVector3ArrayByQuat(oriVertexes, oriOffset + normalOffset, rotation, this._dynamicWorldNormals, bakeOffset));
  17106. }
  17107. this._dynamicWorldPositionNormalNeedUpdate = false;
  17108. }
  17109. }
  17110. setTransform(transform) {
  17111. if (this._transform !== transform) {
  17112. (this._transform) && (this._transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatrixChanged));
  17113. (transform) && (transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatrixChanged));
  17114. this._dynamicWorldPositionNormalNeedUpdate = true;
  17115. this._transform = transform;
  17116. }
  17117. }
  17118. setGeometry(geometry) {
  17119. if (this._geometry !== geometry) {
  17120. var subMesh = geometry;
  17121. var mesh = subMesh._mesh;
  17122. if (mesh) {
  17123. var multiSubMesh = mesh._subMeshes.length > 1;
  17124. var dynBatVerCount = multiSubMesh ? subMesh._indexCount : mesh._vertexCount;
  17125. if (dynBatVerCount <= ILaya3D.SubMeshDynamicBatch.maxAllowVertexCount) {
  17126. var length = dynBatVerCount * 3;
  17127. this._dynamicVertexBatch = true;
  17128. this._dynamicWorldPositions = new Float32Array(length);
  17129. this._dynamicWorldNormals = new Float32Array(length);
  17130. this._dynamicVertexCount = dynBatVerCount;
  17131. this._dynamicMultiSubMesh = multiSubMesh;
  17132. }
  17133. else {
  17134. this._dynamicVertexBatch = false;
  17135. }
  17136. }
  17137. this._geometry = geometry;
  17138. }
  17139. }
  17140. addToOpaqueRenderQueue(context, queue) {
  17141. var subMeshStaticBatch = this.staticBatch;
  17142. var queueElements = queue.elements;
  17143. var elements = queueElements.elements;
  17144. if (subMeshStaticBatch) {
  17145. var staManager = ILaya3D.MeshRenderStaticBatchManager.instance;
  17146. var staBatchMarks = staManager.getBatchOpaquaMark(this.render.lightmapIndex + 1, this.render.receiveShadow, this.material.id, subMeshStaticBatch._batchID);
  17147. if (staManager._updateCountMark === staBatchMarks.updateMark) {
  17148. var staBatchIndex = staBatchMarks.indexInList;
  17149. if (staBatchMarks.batched) {
  17150. elements[staBatchIndex].staticBatchElementList.add(this);
  17151. }
  17152. else {
  17153. var staOriElement = elements[staBatchIndex];
  17154. var staOriRender = staOriElement.render;
  17155. var staBatchElement = staManager._getBatchRenderElementFromPool();
  17156. staBatchElement.renderType = RenderElement.RENDERTYPE_STATICBATCH;
  17157. staBatchElement.setGeometry(subMeshStaticBatch);
  17158. staBatchElement.material = staOriElement.material;
  17159. var staRootOwner = subMeshStaticBatch.batchOwner;
  17160. var staBatchTransform = staRootOwner ? staRootOwner._transform : null;
  17161. staBatchElement.setTransform(staBatchTransform);
  17162. staBatchElement.render = staOriRender;
  17163. staBatchElement.renderSubShader = staOriElement.renderSubShader;
  17164. var staBatchList = staBatchElement.staticBatchElementList;
  17165. staBatchList.length = 0;
  17166. staBatchList.add(staOriElement);
  17167. staBatchList.add(this);
  17168. elements[staBatchIndex] = staBatchElement;
  17169. staBatchMarks.batched = true;
  17170. }
  17171. }
  17172. else {
  17173. staBatchMarks.updateMark = staManager._updateCountMark;
  17174. staBatchMarks.indexInList = queueElements.length;
  17175. staBatchMarks.batched = false;
  17176. queueElements.add(this);
  17177. }
  17178. }
  17179. else if (this.renderSubShader._owner._enableInstancing && Laya.LayaGL.layaGPUInstance.supportInstance() && this.render.lightmapIndex < 0) {
  17180. var subMesh = this._geometry;
  17181. var insManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  17182. var insBatchMarks = insManager.getInstanceBatchOpaquaMark(this.render.receiveShadow, this.material.id, subMesh._id, this._transform._isFrontFaceInvert);
  17183. if (insManager._updateCountMark === insBatchMarks.updateMark) {
  17184. var insBatchIndex = insBatchMarks.indexInList;
  17185. if (insBatchMarks.batched) {
  17186. var instanceBatchElementList = elements[insBatchIndex].instanceBatchElementList;
  17187. if (instanceBatchElementList.length === SubMeshInstanceBatch.instance.maxInstanceCount) {
  17188. insBatchMarks.updateMark = insManager._updateCountMark;
  17189. insBatchMarks.indexInList = queueElements.length;
  17190. insBatchMarks.batched = false;
  17191. queueElements.add(this);
  17192. }
  17193. else {
  17194. instanceBatchElementList.add(this);
  17195. }
  17196. }
  17197. else {
  17198. var insOriElement = elements[insBatchIndex];
  17199. var insOriRender = insOriElement.render;
  17200. var insBatchElement = insManager._getBatchRenderElementFromPool();
  17201. insBatchElement.renderType = RenderElement.RENDERTYPE_INSTANCEBATCH;
  17202. insBatchElement.setGeometry(SubMeshInstanceBatch.instance);
  17203. insBatchElement.material = insOriElement.material;
  17204. insBatchElement.setTransform(null);
  17205. insBatchElement.render = insOriRender;
  17206. insBatchElement.instanceSubMesh = subMesh;
  17207. insBatchElement.renderSubShader = insOriElement.renderSubShader;
  17208. var insBatchList = insBatchElement.instanceBatchElementList;
  17209. insBatchList.length = 0;
  17210. insBatchList.add(insOriElement);
  17211. insBatchList.add(this);
  17212. elements[insBatchIndex] = insBatchElement;
  17213. insBatchMarks.batched = true;
  17214. }
  17215. }
  17216. else {
  17217. insBatchMarks.updateMark = insManager._updateCountMark;
  17218. insBatchMarks.indexInList = queueElements.length;
  17219. insBatchMarks.batched = false;
  17220. queueElements.add(this);
  17221. }
  17222. }
  17223. else if (this._dynamicVertexBatch) {
  17224. var verDec = this._geometry._vertexBuffer.vertexDeclaration;
  17225. var dynManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  17226. var dynBatchMarks = dynManager.getVertexBatchOpaquaMark(this.render.lightmapIndex + 1, this.render.receiveShadow, this.material.id, verDec.id);
  17227. if (dynManager._updateCountMark === dynBatchMarks.updateMark) {
  17228. var dynBatchIndex = dynBatchMarks.indexInList;
  17229. if (dynBatchMarks.batched) {
  17230. elements[dynBatchIndex].vertexBatchElementList.add(this);
  17231. }
  17232. else {
  17233. var dynOriElement = elements[dynBatchIndex];
  17234. var dynOriRender = dynOriElement.render;
  17235. var dynBatchElement = dynManager._getBatchRenderElementFromPool();
  17236. dynBatchElement.renderType = RenderElement.RENDERTYPE_VERTEXBATCH;
  17237. dynBatchElement.setGeometry(ILaya3D.SubMeshDynamicBatch.instance);
  17238. dynBatchElement.material = dynOriElement.material;
  17239. dynBatchElement.setTransform(null);
  17240. dynBatchElement.render = dynOriRender;
  17241. dynBatchElement.vertexBatchVertexDeclaration = verDec;
  17242. dynBatchElement.renderSubShader = dynOriElement.renderSubShader;
  17243. var dynBatchList = dynBatchElement.vertexBatchElementList;
  17244. dynBatchList.length = 0;
  17245. dynBatchList.add(dynOriElement);
  17246. dynBatchList.add(this);
  17247. elements[dynBatchIndex] = dynBatchElement;
  17248. dynBatchMarks.batched = true;
  17249. }
  17250. }
  17251. else {
  17252. dynBatchMarks.updateMark = dynManager._updateCountMark;
  17253. dynBatchMarks.indexInList = queueElements.length;
  17254. dynBatchMarks.batched = false;
  17255. queueElements.add(this);
  17256. }
  17257. }
  17258. else {
  17259. queueElements.add(this);
  17260. }
  17261. }
  17262. addToTransparentRenderQueue(context, queue) {
  17263. var subMeshStaticBatch = this.staticBatch;
  17264. var queueElements = queue.elements;
  17265. var elements = queueElements.elements;
  17266. if (subMeshStaticBatch) {
  17267. var staManager = ILaya3D.MeshRenderStaticBatchManager.instance;
  17268. var staLastElement = queue.lastTransparentRenderElement;
  17269. if (staLastElement) {
  17270. var staLastRender = staLastElement.render;
  17271. if (staLastElement._geometry._getType() !== this._geometry._getType() || staLastElement.staticBatch !== subMeshStaticBatch || staLastElement.material !== this.material || staLastRender.receiveShadow !== this.render.receiveShadow || staLastRender.lightmapIndex !== this.render.lightmapIndex) {
  17272. queueElements.add(this);
  17273. queue.lastTransparentBatched = false;
  17274. }
  17275. else {
  17276. if (queue.lastTransparentBatched) {
  17277. elements[queueElements.length - 1].staticBatchElementList.add((this));
  17278. }
  17279. else {
  17280. var staBatchElement = staManager._getBatchRenderElementFromPool();
  17281. staBatchElement.renderType = RenderElement.RENDERTYPE_STATICBATCH;
  17282. staBatchElement.setGeometry(subMeshStaticBatch);
  17283. staBatchElement.material = staLastElement.material;
  17284. var staRootOwner = subMeshStaticBatch.batchOwner;
  17285. var staBatchTransform = staRootOwner ? staRootOwner._transform : null;
  17286. staBatchElement.setTransform(staBatchTransform);
  17287. staBatchElement.render = this.render;
  17288. staBatchElement.renderSubShader = staLastElement.renderSubShader;
  17289. var staBatchList = staBatchElement.staticBatchElementList;
  17290. staBatchList.length = 0;
  17291. staBatchList.add(staLastElement);
  17292. staBatchList.add(this);
  17293. elements[queueElements.length - 1] = staBatchElement;
  17294. }
  17295. queue.lastTransparentBatched = true;
  17296. }
  17297. }
  17298. else {
  17299. queueElements.add(this);
  17300. queue.lastTransparentBatched = false;
  17301. }
  17302. }
  17303. else if (this.renderSubShader._owner._enableInstancing && Laya.LayaGL.layaGPUInstance.supportInstance() && this.render.lightmapIndex < 0) {
  17304. var subMesh = this._geometry;
  17305. var insManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  17306. var insLastElement = queue.lastTransparentRenderElement;
  17307. if (insLastElement) {
  17308. var insLastRender = insLastElement.render;
  17309. if (insLastElement._geometry._getType() !== this._geometry._getType() || insLastElement._geometry !== subMesh || insLastElement.material !== this.material || insLastRender.receiveShadow !== this.render.receiveShadow) {
  17310. queueElements.add(this);
  17311. queue.lastTransparentBatched = false;
  17312. }
  17313. else {
  17314. if (queue.lastTransparentBatched) {
  17315. var instanceBatchElementList = elements[queueElements.length - 1].instanceBatchElementList;
  17316. if (instanceBatchElementList.length === SubMeshInstanceBatch.instance.maxInstanceCount) {
  17317. queueElements.add(this);
  17318. queue.lastTransparentBatched = false;
  17319. }
  17320. else {
  17321. instanceBatchElementList.add(this);
  17322. queue.lastTransparentBatched = true;
  17323. }
  17324. }
  17325. else {
  17326. var insBatchElement = insManager._getBatchRenderElementFromPool();
  17327. insBatchElement.renderType = RenderElement.RENDERTYPE_INSTANCEBATCH;
  17328. insBatchElement.setGeometry(SubMeshInstanceBatch.instance);
  17329. insBatchElement.material = insLastElement.material;
  17330. insBatchElement.setTransform(null);
  17331. insBatchElement.render = this.render;
  17332. insBatchElement.instanceSubMesh = subMesh;
  17333. insBatchElement.renderSubShader = insLastElement.renderSubShader;
  17334. var insBatchList = insBatchElement.instanceBatchElementList;
  17335. insBatchList.length = 0;
  17336. insBatchList.add(insLastElement);
  17337. insBatchList.add(this);
  17338. elements[queueElements.length - 1] = insBatchElement;
  17339. queue.lastTransparentBatched = true;
  17340. }
  17341. }
  17342. }
  17343. else {
  17344. queueElements.add(this);
  17345. queue.lastTransparentBatched = false;
  17346. }
  17347. }
  17348. else if (this._dynamicVertexBatch) {
  17349. var verDec = this._geometry._vertexBuffer.vertexDeclaration;
  17350. var dynManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  17351. var dynLastElement = queue.lastTransparentRenderElement;
  17352. if (dynLastElement) {
  17353. var dynLastRender = dynLastElement.render;
  17354. if (!dynLastElement._dynamicVertexBatch || 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) {
  17355. queueElements.add(this);
  17356. queue.lastTransparentBatched = false;
  17357. }
  17358. else {
  17359. if (queue.lastTransparentBatched) {
  17360. elements[queueElements.length - 1].vertexBatchElementList.add((this));
  17361. }
  17362. else {
  17363. var dynBatchElement = dynManager._getBatchRenderElementFromPool();
  17364. dynBatchElement.renderType = RenderElement.RENDERTYPE_VERTEXBATCH;
  17365. dynBatchElement.setGeometry(ILaya3D.SubMeshDynamicBatch.instance);
  17366. dynBatchElement.material = dynLastElement.material;
  17367. dynBatchElement.setTransform(null);
  17368. dynBatchElement.render = this.render;
  17369. dynBatchElement.vertexBatchVertexDeclaration = verDec;
  17370. dynBatchElement.renderSubShader = dynLastElement.renderSubShader;
  17371. var dynBatchList = dynBatchElement.vertexBatchElementList;
  17372. dynBatchList.length = 0;
  17373. dynBatchList.add(dynLastElement);
  17374. dynBatchList.add(this);
  17375. elements[queueElements.length - 1] = dynBatchElement;
  17376. }
  17377. queue.lastTransparentBatched = true;
  17378. }
  17379. }
  17380. else {
  17381. queueElements.add(this);
  17382. queue.lastTransparentBatched = false;
  17383. }
  17384. }
  17385. else {
  17386. queueElements.add(this);
  17387. }
  17388. queue.lastTransparentRenderElement = this;
  17389. }
  17390. getInvertFront() {
  17391. switch (this.renderType) {
  17392. case RenderElement.RENDERTYPE_NORMAL:
  17393. return this._transform._isFrontFaceInvert;
  17394. case RenderElement.RENDERTYPE_STATICBATCH:
  17395. case RenderElement.RENDERTYPE_VERTEXBATCH:
  17396. return false;
  17397. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  17398. return this.instanceBatchElementList.elements[0]._transform._isFrontFaceInvert;
  17399. default:
  17400. throw "SubMeshRenderElement: unknown renderType";
  17401. }
  17402. }
  17403. destroy() {
  17404. super.destroy();
  17405. this._dynamicWorldPositions = null;
  17406. this._dynamicWorldNormals = null;
  17407. this.staticBatch = null;
  17408. this.staticBatchElementList = null;
  17409. this.vertexBatchElementList = null;
  17410. this.vertexBatchVertexDeclaration = null;
  17411. }
  17412. }
  17413. class StaticBatchManager {
  17414. constructor() {
  17415. this._initBatchSprites = [];
  17416. this._staticBatches = {};
  17417. this._batchRenderElementPoolIndex = 0;
  17418. this._batchRenderElementPool = [];
  17419. }
  17420. static _addToStaticBatchQueue(sprite3D, renderableSprite3D) {
  17421. if (sprite3D instanceof RenderableSprite3D)
  17422. renderableSprite3D.push(sprite3D);
  17423. for (var i = 0, n = sprite3D.numChildren; i < n; i++)
  17424. StaticBatchManager._addToStaticBatchQueue(sprite3D._children[i], renderableSprite3D);
  17425. }
  17426. static _registerManager(manager) {
  17427. StaticBatchManager._managers.push(manager);
  17428. }
  17429. static combine(staticBatchRoot, renderableSprite3Ds = null) {
  17430. if (!renderableSprite3Ds) {
  17431. renderableSprite3Ds = [];
  17432. if (staticBatchRoot)
  17433. StaticBatchManager._addToStaticBatchQueue(staticBatchRoot, renderableSprite3Ds);
  17434. }
  17435. var batchSpritesCount = renderableSprite3Ds.length;
  17436. if (batchSpritesCount > 0) {
  17437. for (var i = 0; i < batchSpritesCount; i++) {
  17438. var sprite = renderableSprite3Ds[i];
  17439. if (!sprite.destroyed) {
  17440. if (sprite._render._isPartOfStaticBatch)
  17441. console.warn("StaticBatchManager: Sprite " + sprite.name + " has a part of Static Batch,it will be ignore.");
  17442. else
  17443. sprite._addToInitStaticBatchManager();
  17444. }
  17445. }
  17446. for (var k = 0, m = StaticBatchManager._managers.length; k < m; k++) {
  17447. var manager = StaticBatchManager._managers[k];
  17448. manager._initStaticBatchs(staticBatchRoot);
  17449. }
  17450. }
  17451. }
  17452. _partition(items, left, right) {
  17453. var pivot = items[Math.floor((right + left) / 2)];
  17454. while (left <= right) {
  17455. while (this._compare(items[left], pivot) < 0)
  17456. left++;
  17457. while (this._compare(items[right], pivot) > 0)
  17458. right--;
  17459. if (left < right) {
  17460. var temp = items[left];
  17461. items[left] = items[right];
  17462. items[right] = temp;
  17463. left++;
  17464. right--;
  17465. }
  17466. else if (left === right) {
  17467. left++;
  17468. break;
  17469. }
  17470. }
  17471. return left;
  17472. }
  17473. _quickSort(items, left, right) {
  17474. if (items.length > 1) {
  17475. var index = this._partition(items, left, right);
  17476. var leftIndex = index - 1;
  17477. if (left < leftIndex)
  17478. this._quickSort(items, left, leftIndex);
  17479. if (index < right)
  17480. this._quickSort(items, index, right);
  17481. }
  17482. }
  17483. _compare(left, right) {
  17484. throw "StaticBatch:must override this function.";
  17485. }
  17486. _initStaticBatchs(rootSprite) {
  17487. throw "StaticBatch:must override this function.";
  17488. }
  17489. _getBatchRenderElementFromPool() {
  17490. throw "StaticBatch:must override this function.";
  17491. }
  17492. _addBatchSprite(renderableSprite3D) {
  17493. this._initBatchSprites.push(renderableSprite3D);
  17494. }
  17495. _clear() {
  17496. this._batchRenderElementPoolIndex = 0;
  17497. }
  17498. _garbageCollection() {
  17499. throw "StaticBatchManager: must override it.";
  17500. }
  17501. dispose() {
  17502. this._staticBatches = null;
  17503. }
  17504. }
  17505. StaticBatchManager._managers = [];
  17506. class SubMeshStaticBatch extends GeometryElement {
  17507. constructor(batchOwner, vertexDeclaration) {
  17508. super();
  17509. this._bufferState = new BufferState();
  17510. this._batchID = SubMeshStaticBatch._batchIDCounter++;
  17511. this._batchElements = [];
  17512. this._currentBatchVertexCount = 0;
  17513. this._currentBatchIndexCount = 0;
  17514. this._vertexDeclaration = vertexDeclaration;
  17515. this.batchOwner = batchOwner;
  17516. }
  17517. _getStaticBatchBakedVertexs(batchVertices, batchOffset, batchOwnerTransform, transform, render, mesh) {
  17518. var vertexBuffer = mesh._vertexBuffer;
  17519. var vertexDeclaration = vertexBuffer.vertexDeclaration;
  17520. var positionOffset = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  17521. var normalElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_NORMAL0);
  17522. var normalOffset = normalElement ? normalElement._offset / 4 : -1;
  17523. var colorElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  17524. var colorOffset = colorElement ? colorElement._offset / 4 : -1;
  17525. var uv0Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  17526. var uv0Offset = uv0Element ? uv0Element._offset / 4 : -1;
  17527. var uv1Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE1);
  17528. var uv1Offset = uv1Element ? uv1Element._offset / 4 : -1;
  17529. var tangentElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TANGENT0);
  17530. var sTangentOffset = tangentElement ? tangentElement._offset / 4 : -1;
  17531. var bakeVertexFloatCount = 18;
  17532. var oriVertexFloatCount = vertexDeclaration.vertexStride / 4;
  17533. var oriVertexes = vertexBuffer.getFloat32Data();
  17534. var worldMat;
  17535. if (batchOwnerTransform) {
  17536. var rootMat = batchOwnerTransform.worldMatrix;
  17537. rootMat.invert(SubMeshStaticBatch._tempMatrix4x40);
  17538. worldMat = SubMeshStaticBatch._tempMatrix4x41;
  17539. Matrix4x4.multiply(SubMeshStaticBatch._tempMatrix4x40, transform.worldMatrix, worldMat);
  17540. }
  17541. else {
  17542. worldMat = transform.worldMatrix;
  17543. }
  17544. var normalMat = SubMeshStaticBatch._tempMatrix4x42;
  17545. worldMat.invert(normalMat);
  17546. normalMat.transpose();
  17547. var rotation = SubMeshStaticBatch._tempQuaternion0;
  17548. worldMat.decomposeTransRotScale(SubMeshStaticBatch._tempVector30, rotation, SubMeshStaticBatch._tempVector31);
  17549. var lightmapScaleOffset = render.lightmapScaleOffset;
  17550. var vertexCount = mesh.vertexCount;
  17551. for (var i = 0; i < vertexCount; i++) {
  17552. var oriOffset = i * oriVertexFloatCount;
  17553. var bakeOffset = (i + batchOffset) * bakeVertexFloatCount;
  17554. Utils3D.transformVector3ArrayToVector3ArrayCoordinate(oriVertexes, oriOffset + positionOffset, worldMat, batchVertices, bakeOffset + 0);
  17555. if (normalOffset !== -1)
  17556. Utils3D.transformVector3ArrayToVector3ArrayNormal(oriVertexes, oriOffset + normalOffset, normalMat, batchVertices, bakeOffset + 3);
  17557. var j, m;
  17558. var bakOff = bakeOffset + 6;
  17559. if (colorOffset !== -1) {
  17560. var oriOff = oriOffset + colorOffset;
  17561. for (j = 0, m = 4; j < m; j++)
  17562. batchVertices[bakOff + j] = oriVertexes[oriOff + j];
  17563. }
  17564. else {
  17565. for (j = 0, m = 4; j < m; j++)
  17566. batchVertices[bakOff + j] = 1.0;
  17567. }
  17568. if (uv0Offset !== -1) {
  17569. var absUv0Offset = oriOffset + uv0Offset;
  17570. batchVertices[bakeOffset + 10] = oriVertexes[absUv0Offset];
  17571. batchVertices[bakeOffset + 11] = oriVertexes[absUv0Offset + 1];
  17572. }
  17573. if (lightmapScaleOffset) {
  17574. if (uv1Offset !== -1)
  17575. Utils3D.transformLightingMapTexcoordArray(oriVertexes, oriOffset + uv1Offset, lightmapScaleOffset, batchVertices, bakeOffset + 12);
  17576. else
  17577. Utils3D.transformLightingMapTexcoordArray(oriVertexes, oriOffset + uv0Offset, lightmapScaleOffset, batchVertices, bakeOffset + 12);
  17578. }
  17579. if (sTangentOffset !== -1) {
  17580. var absSTanegntOffset = oriOffset + sTangentOffset;
  17581. batchVertices[bakeOffset + 14] = oriVertexes[absSTanegntOffset];
  17582. batchVertices[bakeOffset + 15] = oriVertexes[absSTanegntOffset + 1];
  17583. batchVertices[bakeOffset + 16] = oriVertexes[absSTanegntOffset + 2];
  17584. batchVertices[bakeOffset + 17] = oriVertexes[absSTanegntOffset + 3];
  17585. }
  17586. }
  17587. return vertexCount;
  17588. }
  17589. addTest(sprite) {
  17590. var vertexCount;
  17591. var subMeshVertexCount = sprite.meshFilter.sharedMesh.vertexCount;
  17592. vertexCount = this._currentBatchVertexCount + subMeshVertexCount;
  17593. if (vertexCount > SubMeshStaticBatch.maxBatchVertexCount)
  17594. return false;
  17595. return true;
  17596. }
  17597. add(sprite) {
  17598. var mesh = sprite.meshFilter.sharedMesh;
  17599. var subMeshVertexCount = mesh.vertexCount;
  17600. this._batchElements.push(sprite);
  17601. var render = sprite._render;
  17602. render._isPartOfStaticBatch = true;
  17603. render._staticBatch = this;
  17604. var renderElements = render._renderElements;
  17605. for (var i = 0, n = renderElements.length; i < n; i++)
  17606. renderElements[i].staticBatch = this;
  17607. this._currentBatchIndexCount += mesh._indexBuffer.indexCount;
  17608. this._currentBatchVertexCount += subMeshVertexCount;
  17609. }
  17610. remove(sprite) {
  17611. var mesh = sprite.meshFilter.sharedMesh;
  17612. var index = this._batchElements.indexOf(sprite);
  17613. if (index !== -1) {
  17614. this._batchElements.splice(index, 1);
  17615. var renderElements = sprite._render._renderElements;
  17616. for (var i = 0, n = renderElements.length; i < n; i++)
  17617. renderElements[i].staticBatch = null;
  17618. this._currentBatchIndexCount = this._currentBatchIndexCount - mesh._indexBuffer.indexCount;
  17619. this._currentBatchVertexCount = this._currentBatchVertexCount - mesh.vertexCount;
  17620. sprite._render._isPartOfStaticBatch = false;
  17621. }
  17622. }
  17623. finishInit() {
  17624. if (this._vertexBuffer) {
  17625. this._vertexBuffer.destroy();
  17626. this._indexBuffer.destroy();
  17627. Laya.Resource._addGPUMemory(-(this._vertexBuffer._byteLength + this._indexBuffer._byteLength));
  17628. }
  17629. var gl = Laya.LayaGL.instance;
  17630. var batchVertexCount = 0;
  17631. var batchIndexCount = 0;
  17632. var rootOwner = this.batchOwner;
  17633. var floatStride = this._vertexDeclaration.vertexStride / 4;
  17634. var vertexDatas = new Float32Array(floatStride * this._currentBatchVertexCount);
  17635. var indexDatas = new Uint16Array(this._currentBatchIndexCount);
  17636. this._vertexBuffer = new VertexBuffer3D(this._vertexDeclaration.vertexStride * this._currentBatchVertexCount, gl.STATIC_DRAW);
  17637. this._vertexBuffer.vertexDeclaration = this._vertexDeclaration;
  17638. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._currentBatchIndexCount, gl.STATIC_DRAW);
  17639. for (var i = 0, n = this._batchElements.length; i < n; i++) {
  17640. var sprite = this._batchElements[i];
  17641. var mesh = sprite.meshFilter.sharedMesh;
  17642. var meshVerCount = this._getStaticBatchBakedVertexs(vertexDatas, batchVertexCount, rootOwner ? rootOwner._transform : null, sprite._transform, sprite._render, mesh);
  17643. var indices = mesh._indexBuffer.getData();
  17644. var indexOffset = batchVertexCount;
  17645. var indexEnd = batchIndexCount + indices.length;
  17646. var elements = sprite._render._renderElements;
  17647. for (var j = 0, m = mesh.subMeshCount; j < m; j++) {
  17648. var subMesh = mesh._subMeshes[j];
  17649. var start = batchIndexCount + subMesh._indexStart;
  17650. var element = elements[j];
  17651. element.staticBatchIndexStart = start;
  17652. element.staticBatchIndexEnd = start + subMesh._indexCount;
  17653. }
  17654. indexDatas.set(indices, batchIndexCount);
  17655. var k;
  17656. var isInvert = rootOwner ? (sprite._transform._isFrontFaceInvert !== rootOwner.transform._isFrontFaceInvert) : sprite._transform._isFrontFaceInvert;
  17657. if (isInvert) {
  17658. for (k = batchIndexCount; k < indexEnd; k += 3) {
  17659. indexDatas[k] = indexOffset + indexDatas[k];
  17660. var index1 = indexDatas[k + 1];
  17661. var index2 = indexDatas[k + 2];
  17662. indexDatas[k + 1] = indexOffset + index2;
  17663. indexDatas[k + 2] = indexOffset + index1;
  17664. }
  17665. }
  17666. else {
  17667. for (k = batchIndexCount; k < indexEnd; k += 3) {
  17668. indexDatas[k] = indexOffset + indexDatas[k];
  17669. indexDatas[k + 1] = indexOffset + indexDatas[k + 1];
  17670. indexDatas[k + 2] = indexOffset + indexDatas[k + 2];
  17671. }
  17672. }
  17673. batchIndexCount += indices.length;
  17674. batchVertexCount += meshVerCount;
  17675. }
  17676. this._vertexBuffer.setData(vertexDatas.buffer);
  17677. this._indexBuffer.setData(indexDatas);
  17678. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  17679. Laya.Resource._addGPUMemory(memorySize);
  17680. this._bufferState.bind();
  17681. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  17682. this._bufferState.applyIndexBuffer(this._indexBuffer);
  17683. this._bufferState.unBind();
  17684. }
  17685. _render(state) {
  17686. this._bufferState.bind();
  17687. var gl = Laya.LayaGL.instance;
  17688. var element = state.renderElement;
  17689. var staticBatchElementList = element.staticBatchElementList;
  17690. var batchElementList = staticBatchElementList.elements;
  17691. var from = 0;
  17692. var end = 0;
  17693. var count = staticBatchElementList.length;
  17694. for (var i = 1; i < count; i++) {
  17695. var lastElement = batchElementList[i - 1];
  17696. if (lastElement.staticBatchIndexEnd === batchElementList[i].staticBatchIndexStart) {
  17697. end++;
  17698. continue;
  17699. }
  17700. else {
  17701. var start = batchElementList[from].staticBatchIndexStart;
  17702. var indexCount = batchElementList[end].staticBatchIndexEnd - start;
  17703. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, start * 2);
  17704. from = ++end;
  17705. Laya.Stat.trianglesFaces += indexCount / 3;
  17706. }
  17707. }
  17708. start = batchElementList[from].staticBatchIndexStart;
  17709. indexCount = batchElementList[end].staticBatchIndexEnd - start;
  17710. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, start * 2);
  17711. Laya.Stat.renderBatches++;
  17712. Laya.Stat.savedRenderBatches += count - 1;
  17713. Laya.Stat.trianglesFaces += indexCount / 3;
  17714. }
  17715. dispose() {
  17716. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  17717. Laya.Resource._addGPUMemory(-memorySize);
  17718. this._batchElements = null;
  17719. this.batchOwner = null;
  17720. this._vertexDeclaration = null;
  17721. this._bufferState.destroy();
  17722. this._vertexBuffer.destroy();
  17723. this._indexBuffer.destroy();
  17724. this._vertexBuffer = null;
  17725. this._indexBuffer = null;
  17726. this._bufferState = null;
  17727. }
  17728. }
  17729. SubMeshStaticBatch._tempVector30 = new Vector3();
  17730. SubMeshStaticBatch._tempVector31 = new Vector3();
  17731. SubMeshStaticBatch._tempQuaternion0 = new Quaternion();
  17732. SubMeshStaticBatch._tempMatrix4x40 = new Matrix4x4();
  17733. SubMeshStaticBatch._tempMatrix4x41 = new Matrix4x4();
  17734. SubMeshStaticBatch._tempMatrix4x42 = new Matrix4x4();
  17735. SubMeshStaticBatch.maxBatchVertexCount = 65535;
  17736. SubMeshStaticBatch._batchIDCounter = 0;
  17737. class MeshRenderStaticBatchManager extends StaticBatchManager {
  17738. constructor() {
  17739. super();
  17740. this._opaqueBatchMarks = [];
  17741. this._updateCountMark = 0;
  17742. }
  17743. static __init__() {
  17744. MeshRenderStaticBatchManager._verDec = VertexMesh.getVertexDeclaration("POSITION,NORMAL,COLOR,UV,UV1,TANGENT");
  17745. }
  17746. _compare(left, right) {
  17747. var lRender = left._render, rRender = right._render;
  17748. var leftGeo = left.meshFilter.sharedMesh, rightGeo = right.meshFilter.sharedMesh;
  17749. var lightOffset = lRender.lightmapIndex - rRender.lightmapIndex;
  17750. if (lightOffset === 0) {
  17751. var receiveShadowOffset = (lRender.receiveShadow ? 1 : 0) - (rRender.receiveShadow ? 1 : 0);
  17752. if (receiveShadowOffset === 0) {
  17753. var materialOffset = (lRender.sharedMaterial && rRender.sharedMaterial) ? lRender.sharedMaterial.id - rRender.sharedMaterial.id : 0;
  17754. if (materialOffset === 0) {
  17755. var verDec = leftGeo._vertexBuffer.vertexDeclaration.id - rightGeo._vertexBuffer.vertexDeclaration.id;
  17756. if (verDec === 0) {
  17757. return rightGeo._indexBuffer.indexCount - leftGeo._indexBuffer.indexCount;
  17758. }
  17759. else {
  17760. return verDec;
  17761. }
  17762. }
  17763. else {
  17764. return materialOffset;
  17765. }
  17766. }
  17767. else {
  17768. return receiveShadowOffset;
  17769. }
  17770. }
  17771. else {
  17772. return lightOffset;
  17773. }
  17774. }
  17775. _getBatchRenderElementFromPool() {
  17776. var renderElement = this._batchRenderElementPool[this._batchRenderElementPoolIndex++];
  17777. if (!renderElement) {
  17778. renderElement = new SubMeshRenderElement();
  17779. this._batchRenderElementPool[this._batchRenderElementPoolIndex - 1] = renderElement;
  17780. renderElement.staticBatchElementList = new SingletonList();
  17781. }
  17782. return renderElement;
  17783. }
  17784. _getStaticBatch(staticBatches, rootOwner, number) {
  17785. var subMeshStaticBatch = staticBatches[number];
  17786. if (!subMeshStaticBatch) {
  17787. subMeshStaticBatch = staticBatches[number] = new SubMeshStaticBatch(rootOwner, MeshRenderStaticBatchManager._verDec);
  17788. this._staticBatches[subMeshStaticBatch._batchID] = subMeshStaticBatch;
  17789. }
  17790. return subMeshStaticBatch;
  17791. }
  17792. _initStaticBatchs(rootOwner) {
  17793. var initBatchSprites = this._initBatchSprites;
  17794. this._quickSort(initBatchSprites, 0, initBatchSprites.length - 1);
  17795. var staticBatches = [];
  17796. var lastCanMerage = false;
  17797. var curStaticBatch;
  17798. var batchNumber = 0;
  17799. for (var i = 0, n = initBatchSprites.length; i < n; i++) {
  17800. var sprite = initBatchSprites[i];
  17801. if (lastCanMerage) {
  17802. if (curStaticBatch.addTest(sprite)) {
  17803. curStaticBatch.add(sprite);
  17804. }
  17805. else {
  17806. lastCanMerage = false;
  17807. batchNumber++;
  17808. }
  17809. }
  17810. else {
  17811. var lastIndex = n - 1;
  17812. if (i !== lastIndex) {
  17813. curStaticBatch = this._getStaticBatch(staticBatches, rootOwner, batchNumber);
  17814. curStaticBatch.add(sprite);
  17815. lastCanMerage = true;
  17816. }
  17817. }
  17818. }
  17819. for (i = 0, n = staticBatches.length; i < n; i++) {
  17820. var staticBatch = staticBatches[i];
  17821. staticBatch && staticBatch.finishInit();
  17822. }
  17823. this._initBatchSprites.length = 0;
  17824. }
  17825. _removeRenderSprite(sprite) {
  17826. var render = sprite._render;
  17827. var staticBatch = render._staticBatch;
  17828. var batchElements = staticBatch._batchElements;
  17829. var index = batchElements.indexOf(sprite);
  17830. if (index !== -1) {
  17831. batchElements.splice(index, 1);
  17832. render._staticBatch = null;
  17833. var renderElements = render._renderElements;
  17834. for (var i = 0, n = renderElements.length; i < n; i++)
  17835. renderElements[i].staticBatch = null;
  17836. }
  17837. if (batchElements.length === 0) {
  17838. delete this._staticBatches[staticBatch._batchID];
  17839. staticBatch.dispose();
  17840. }
  17841. }
  17842. _clear() {
  17843. super._clear();
  17844. this._updateCountMark++;
  17845. }
  17846. _garbageCollection() {
  17847. for (var key in this._staticBatches) {
  17848. var staticBatch = this._staticBatches[key];
  17849. if (staticBatch._batchElements.length === 0) {
  17850. staticBatch.dispose();
  17851. delete this._staticBatches[key];
  17852. }
  17853. }
  17854. }
  17855. getBatchOpaquaMark(lightMapIndex, receiveShadow, materialID, staticBatchID) {
  17856. var receiveShadowIndex = receiveShadow ? 1 : 0;
  17857. var staLightMapMarks = (this._opaqueBatchMarks[lightMapIndex]) || (this._opaqueBatchMarks[lightMapIndex] = []);
  17858. var staReceiveShadowMarks = (staLightMapMarks[receiveShadowIndex]) || (staLightMapMarks[receiveShadowIndex] = []);
  17859. var staMaterialMarks = (staReceiveShadowMarks[materialID]) || (staReceiveShadowMarks[materialID] = []);
  17860. return (staMaterialMarks[staticBatchID]) || (staMaterialMarks[staticBatchID] = new BatchMark);
  17861. }
  17862. }
  17863. MeshRenderStaticBatchManager.instance = new MeshRenderStaticBatchManager();
  17864. class BaseRender extends Laya.EventDispatcher {
  17865. constructor(owner) {
  17866. super();
  17867. this._lightmapScaleOffset = new Vector4(1, 1, 0, 0);
  17868. this._indexInList = -1;
  17869. this._indexInCastShadowList = -1;
  17870. this._boundsChange = true;
  17871. this._castShadow = false;
  17872. this._supportOctree = true;
  17873. this._sharedMaterials = [];
  17874. this._renderMark = -1;
  17875. this._indexInOctreeMotionList = -1;
  17876. this._updateMark = -1;
  17877. this._updateRenderType = -1;
  17878. this._isPartOfStaticBatch = false;
  17879. this._staticBatch = null;
  17880. this._id = ++BaseRender._uniqueIDCounter;
  17881. this._indexInCastShadowList = -1;
  17882. this._bounds = new Bounds(Vector3._ZERO, Vector3._ZERO);
  17883. if (Laya.Render.supportWebGLPlusCulling) {
  17884. var length = FrustumCulling._cullingBufferLength;
  17885. this._cullingBufferIndex = length;
  17886. var cullingBuffer = FrustumCulling._cullingBuffer;
  17887. var resizeLength = length + 7;
  17888. if (resizeLength >= cullingBuffer.length) {
  17889. var temp = cullingBuffer;
  17890. cullingBuffer = FrustumCulling._cullingBuffer = new Float32Array(cullingBuffer.length + 4096);
  17891. cullingBuffer.set(temp, 0);
  17892. }
  17893. cullingBuffer[length] = 2;
  17894. FrustumCulling._cullingBufferLength = resizeLength;
  17895. }
  17896. this._renderElements = [];
  17897. this._owner = owner;
  17898. this._enable = true;
  17899. this._materialsInstance = [];
  17900. this._shaderValues = new ShaderData(null);
  17901. this.lightmapIndex = -1;
  17902. this.receiveShadow = false;
  17903. this.sortingFudge = 0.0;
  17904. (owner) && (this._owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  17905. }
  17906. get id() {
  17907. return this._id;
  17908. }
  17909. get lightmapIndex() {
  17910. return this._lightmapIndex;
  17911. }
  17912. set lightmapIndex(value) {
  17913. this._lightmapIndex = value;
  17914. }
  17915. get lightmapScaleOffset() {
  17916. return this._lightmapScaleOffset;
  17917. }
  17918. set lightmapScaleOffset(value) {
  17919. if (!value)
  17920. throw "BaseRender: lightmapScaleOffset can't be null.";
  17921. this._lightmapScaleOffset = value;
  17922. this._shaderValues.setVector(RenderableSprite3D.LIGHTMAPSCALEOFFSET, value);
  17923. }
  17924. get enable() {
  17925. return this._enable;
  17926. }
  17927. set enable(value) {
  17928. this._enable = !!value;
  17929. }
  17930. get material() {
  17931. var material = this._sharedMaterials[0];
  17932. if (material && !this._materialsInstance[0]) {
  17933. var insMat = this._getInstanceMaterial(material, 0);
  17934. var renderElement = this._renderElements[0];
  17935. (renderElement) && (renderElement.material = insMat);
  17936. }
  17937. return this._sharedMaterials[0];
  17938. }
  17939. set material(value) {
  17940. this.sharedMaterial = value;
  17941. }
  17942. get materials() {
  17943. for (var i = 0, n = this._sharedMaterials.length; i < n; i++) {
  17944. if (!this._materialsInstance[i]) {
  17945. var insMat = this._getInstanceMaterial(this._sharedMaterials[i], i);
  17946. var renderElement = this._renderElements[i];
  17947. (renderElement) && (renderElement.material = insMat);
  17948. }
  17949. }
  17950. return this._sharedMaterials.slice();
  17951. }
  17952. set materials(value) {
  17953. this.sharedMaterials = value;
  17954. }
  17955. get sharedMaterial() {
  17956. return this._sharedMaterials[0];
  17957. }
  17958. set sharedMaterial(value) {
  17959. var lastValue = this._sharedMaterials[0];
  17960. if (lastValue !== value) {
  17961. this._sharedMaterials[0] = value;
  17962. this._materialsInstance[0] = false;
  17963. this._changeMaterialReference(lastValue, value);
  17964. var renderElement = this._renderElements[0];
  17965. (renderElement) && (renderElement.material = value);
  17966. }
  17967. }
  17968. get sharedMaterials() {
  17969. return this._sharedMaterials.slice();
  17970. }
  17971. set sharedMaterials(value) {
  17972. var materialsInstance = this._materialsInstance;
  17973. var sharedMats = this._sharedMaterials;
  17974. for (var i = 0, n = sharedMats.length; i < n; i++) {
  17975. var lastMat = sharedMats[i];
  17976. (lastMat) && (lastMat._removeReference());
  17977. }
  17978. if (value) {
  17979. var count = value.length;
  17980. materialsInstance.length = count;
  17981. sharedMats.length = count;
  17982. for (i = 0; i < count; i++) {
  17983. lastMat = sharedMats[i];
  17984. var mat = value[i];
  17985. if (lastMat !== mat) {
  17986. materialsInstance[i] = false;
  17987. var renderElement = this._renderElements[i];
  17988. (renderElement) && (renderElement.material = mat);
  17989. }
  17990. if (mat) {
  17991. mat._addReference();
  17992. }
  17993. sharedMats[i] = mat;
  17994. }
  17995. }
  17996. else {
  17997. throw new Error("BaseRender: shadredMaterials value can't be null.");
  17998. }
  17999. }
  18000. get bounds() {
  18001. if (this._boundsChange) {
  18002. this._calculateBoundingBox();
  18003. this._boundsChange = false;
  18004. }
  18005. return this._bounds;
  18006. }
  18007. set receiveShadow(value) {
  18008. if (this._receiveShadow !== value) {
  18009. this._receiveShadow = value;
  18010. if (value)
  18011. this._shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW);
  18012. else
  18013. this._shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW);
  18014. }
  18015. }
  18016. get receiveShadow() {
  18017. return this._receiveShadow;
  18018. }
  18019. get castShadow() {
  18020. return this._castShadow;
  18021. }
  18022. set castShadow(value) {
  18023. this._castShadow = value;
  18024. }
  18025. get isPartOfStaticBatch() {
  18026. return this._isPartOfStaticBatch;
  18027. }
  18028. get isRender() {
  18029. return this._renderMark == -1 || this._renderMark == (Laya.Stat.loopCount - 1);
  18030. }
  18031. _getOctreeNode() {
  18032. return this._octreeNode;
  18033. }
  18034. _setOctreeNode(value) {
  18035. this._octreeNode = value;
  18036. }
  18037. _getIndexInMotionList() {
  18038. return this._indexInOctreeMotionList;
  18039. }
  18040. _setIndexInMotionList(value) {
  18041. this._indexInOctreeMotionList = value;
  18042. }
  18043. _changeMaterialReference(lastValue, value) {
  18044. (lastValue) && (lastValue._removeReference());
  18045. value._addReference();
  18046. }
  18047. _getInstanceMaterial(material, index) {
  18048. var insMat = material.clone();
  18049. insMat.name = insMat.name + "(Instance)";
  18050. this._materialsInstance[index] = true;
  18051. this._changeMaterialReference(this._sharedMaterials[index], insMat);
  18052. this._sharedMaterials[index] = insMat;
  18053. return insMat;
  18054. }
  18055. _applyLightMapParams() {
  18056. var lightMaps = this._scene.lightmaps;
  18057. var shaderValues = this._shaderValues;
  18058. var lightmapIndex = this._lightmapIndex;
  18059. if (lightmapIndex >= 0 && lightmapIndex < lightMaps.length) {
  18060. var lightMap = lightMaps[lightmapIndex];
  18061. shaderValues.setTexture(RenderableSprite3D.LIGHTMAP, lightMap.lightmapColor);
  18062. shaderValues.addDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  18063. if (lightMap.lightmapDirection) {
  18064. shaderValues.setTexture(RenderableSprite3D.LIGHTMAP_DIRECTION, lightMap.lightmapDirection);
  18065. shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_LIGHTMAP_DIRECTIONAL);
  18066. }
  18067. else {
  18068. shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_LIGHTMAP_DIRECTIONAL);
  18069. }
  18070. }
  18071. else {
  18072. shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  18073. shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_LIGHTMAP_DIRECTIONAL);
  18074. }
  18075. }
  18076. _onWorldMatNeedChange(flag) {
  18077. this._boundsChange = true;
  18078. if (this._octreeNode) {
  18079. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  18080. if (flag) {
  18081. if (this._indexInOctreeMotionList === -1)
  18082. this._octreeNode._octree.addMotionObject(this);
  18083. }
  18084. }
  18085. }
  18086. _calculateBoundingBox() {
  18087. throw ("BaseRender: must override it.");
  18088. }
  18089. _getIndexInList() {
  18090. return this._indexInList;
  18091. }
  18092. _setIndexInList(index) {
  18093. this._indexInList = index;
  18094. }
  18095. _setBelongScene(scene) {
  18096. this._scene = scene;
  18097. }
  18098. _needRender(boundFrustum, context) {
  18099. return true;
  18100. }
  18101. _renderUpdate(context, transform) {
  18102. }
  18103. _renderUpdateWithCamera(context, transform) {
  18104. }
  18105. _revertBatchRenderUpdate(context) {
  18106. }
  18107. _destroy() {
  18108. (this._indexInOctreeMotionList !== -1) && (this._octreeNode._octree.removeMotionObject(this));
  18109. this.offAll();
  18110. var i = 0, n = 0;
  18111. for (i = 0, n = this._renderElements.length; i < n; i++)
  18112. this._renderElements[i].destroy();
  18113. for (i = 0, n = this._sharedMaterials.length; i < n; i++)
  18114. (this._sharedMaterials[i].destroyed) || (this._sharedMaterials[i]._removeReference());
  18115. this._renderElements = null;
  18116. this._owner = null;
  18117. this._sharedMaterials = null;
  18118. this._bounds = null;
  18119. this._lightmapScaleOffset = null;
  18120. }
  18121. markAsUnStatic() {
  18122. if (this._isPartOfStaticBatch) {
  18123. MeshRenderStaticBatchManager.instance._removeRenderSprite(this._owner);
  18124. this._isPartOfStaticBatch = false;
  18125. }
  18126. }
  18127. }
  18128. BaseRender._tempBoundBoxCorners = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  18129. BaseRender._uniqueIDCounter = 0;
  18130. BaseRender._defaultLightmapScaleOffset = new Vector4(1.0, 1.0, 0.0, 0.0);
  18131. class PixelLineRenderer extends BaseRender {
  18132. constructor(owner) {
  18133. super(owner);
  18134. this._projectionViewWorldMatrix = new Matrix4x4();
  18135. }
  18136. _calculateBoundingBox() {
  18137. var worldMat = this._owner.transform.worldMatrix;
  18138. var lineFilter = this._owner._geometryFilter;
  18139. lineFilter._reCalculateBound();
  18140. lineFilter._bounds._tranform(worldMat, this._bounds);
  18141. if (Laya.Render.supportWebGLPlusCulling) {
  18142. var min = this._bounds.getMin();
  18143. var max = this._bounds.getMax();
  18144. var buffer = FrustumCulling._cullingBuffer;
  18145. buffer[this._cullingBufferIndex + 1] = min.x;
  18146. buffer[this._cullingBufferIndex + 2] = min.y;
  18147. buffer[this._cullingBufferIndex + 3] = min.z;
  18148. buffer[this._cullingBufferIndex + 4] = max.x;
  18149. buffer[this._cullingBufferIndex + 5] = max.y;
  18150. buffer[this._cullingBufferIndex + 6] = max.z;
  18151. }
  18152. }
  18153. _renderUpdateWithCamera(context, transform) {
  18154. var projectionView = context.projectionViewMatrix;
  18155. var sv = this._shaderValues;
  18156. if (transform) {
  18157. var worldMat = transform.worldMatrix;
  18158. sv.setMatrix4x4(Sprite3D.WORLDMATRIX, worldMat);
  18159. Matrix4x4.multiply(projectionView, worldMat, this._projectionViewWorldMatrix);
  18160. sv.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  18161. }
  18162. else {
  18163. sv.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  18164. sv.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  18165. }
  18166. }
  18167. }
  18168. class PixelLineSprite3D extends RenderableSprite3D {
  18169. constructor(maxCount = 2, name = null) {
  18170. super(name);
  18171. this._geometryFilter = new PixelLineFilter(this, maxCount);
  18172. this._render = new PixelLineRenderer(this);
  18173. this._changeRenderObjects(this._render, 0, PixelLineMaterial.defaultMaterial);
  18174. }
  18175. get maxLineCount() {
  18176. return this._geometryFilter._maxLineCount;
  18177. }
  18178. set maxLineCount(value) {
  18179. this._geometryFilter._resizeLineData(value);
  18180. this._geometryFilter._lineCount = Math.min(this._geometryFilter._lineCount, value);
  18181. }
  18182. get lineCount() {
  18183. return this._geometryFilter._lineCount;
  18184. }
  18185. set lineCount(value) {
  18186. if (value > this.maxLineCount)
  18187. throw "PixelLineSprite3D: lineCount can't large than maxLineCount";
  18188. else
  18189. this._geometryFilter._lineCount = value;
  18190. }
  18191. get pixelLineRenderer() {
  18192. return this._render;
  18193. }
  18194. _changeRenderObjects(sender, index, material) {
  18195. var renderObjects = this._render._renderElements;
  18196. (material) || (material = PixelLineMaterial.defaultMaterial);
  18197. var renderElement = renderObjects[index];
  18198. (renderElement) || (renderElement = renderObjects[index] = new RenderElement());
  18199. renderElement.setTransform(this._transform);
  18200. renderElement.setGeometry(this._geometryFilter);
  18201. renderElement.render = this._render;
  18202. renderElement.material = material;
  18203. }
  18204. addLine(startPosition, endPosition, startColor, endColor) {
  18205. if (this._geometryFilter._lineCount !== this._geometryFilter._maxLineCount)
  18206. this._geometryFilter._updateLineData(this._geometryFilter._lineCount++, startPosition, endPosition, startColor, endColor);
  18207. else
  18208. throw "PixelLineSprite3D: lineCount has equal with maxLineCount.";
  18209. }
  18210. addLines(lines) {
  18211. var lineCount = this._geometryFilter._lineCount;
  18212. var addCount = lines.length;
  18213. if (lineCount + addCount > this._geometryFilter._maxLineCount) {
  18214. throw "PixelLineSprite3D: lineCount plus lines count must less than maxLineCount.";
  18215. }
  18216. else {
  18217. this._geometryFilter._updateLineDatas(lineCount, lines);
  18218. this._geometryFilter._lineCount += addCount;
  18219. }
  18220. }
  18221. removeLine(index) {
  18222. if (index < this._geometryFilter._lineCount)
  18223. this._geometryFilter._removeLineData(index);
  18224. else
  18225. throw "PixelLineSprite3D: index must less than lineCount.";
  18226. }
  18227. setLine(index, startPosition, endPosition, startColor, endColor) {
  18228. if (index < this._geometryFilter._lineCount)
  18229. this._geometryFilter._updateLineData(index, startPosition, endPosition, startColor, endColor);
  18230. else
  18231. throw "PixelLineSprite3D: index must less than lineCount.";
  18232. }
  18233. getLine(index, out) {
  18234. if (index < this.lineCount)
  18235. this._geometryFilter._getLineData(index, out);
  18236. else
  18237. throw "PixelLineSprite3D: index must less than lineCount.";
  18238. }
  18239. clear() {
  18240. this._geometryFilter._lineCount = 0;
  18241. }
  18242. _create() {
  18243. return new PixelLineSprite3D();
  18244. }
  18245. }
  18246. class RenderQueue {
  18247. constructor(isTransparent = false) {
  18248. this.isTransparent = false;
  18249. this.elements = new SingletonList();
  18250. this.lastTransparentRenderElement = null;
  18251. this.lastTransparentBatched = false;
  18252. this.isTransparent = isTransparent;
  18253. }
  18254. _compare(left, right) {
  18255. var renderQueue = left.material.renderQueue - right.material.renderQueue;
  18256. if (renderQueue === 0) {
  18257. var sort = this.isTransparent ? right.render._distanceForSort - left.render._distanceForSort : left.render._distanceForSort - right.render._distanceForSort;
  18258. return sort + right.render.sortingFudge - left.render.sortingFudge;
  18259. }
  18260. else {
  18261. return renderQueue;
  18262. }
  18263. }
  18264. _partitionRenderObject(left, right) {
  18265. var elements = this.elements.elements;
  18266. var pivot = elements[Math.floor((right + left) / 2)];
  18267. while (left <= right) {
  18268. while (this._compare(elements[left], pivot) < 0)
  18269. left++;
  18270. while (this._compare(elements[right], pivot) > 0)
  18271. right--;
  18272. if (left < right) {
  18273. var temp = elements[left];
  18274. elements[left] = elements[right];
  18275. elements[right] = temp;
  18276. left++;
  18277. right--;
  18278. }
  18279. else if (left === right) {
  18280. left++;
  18281. break;
  18282. }
  18283. }
  18284. return left;
  18285. }
  18286. _quickSort(left, right) {
  18287. if (this.elements.length > 1) {
  18288. var index = this._partitionRenderObject(left, right);
  18289. var leftIndex = index - 1;
  18290. if (left < leftIndex)
  18291. this._quickSort(left, leftIndex);
  18292. if (index < right)
  18293. this._quickSort(index, right);
  18294. }
  18295. }
  18296. _render(context) {
  18297. var elements = this.elements.elements;
  18298. for (var i = 0, n = this.elements.length; i < n; i++)
  18299. elements[i]._render(context);
  18300. }
  18301. clear() {
  18302. this.elements.length = 0;
  18303. this.lastTransparentRenderElement = null;
  18304. this.lastTransparentBatched = false;
  18305. }
  18306. }
  18307. class BoundsOctreeNode {
  18308. constructor(octree, parent, baseLength, center) {
  18309. this._bounds = new BoundBox(new Vector3(), new Vector3());
  18310. this._objects = [];
  18311. this._isContaion = false;
  18312. this.center = new Vector3();
  18313. this.baseLength = 0.0;
  18314. this._setValues(octree, parent, baseLength, center);
  18315. }
  18316. static _encapsulates(outerBound, innerBound) {
  18317. return CollisionUtils.boxContainsBox(outerBound, innerBound) == ContainmentType.Contains;
  18318. }
  18319. _setValues(octree, parent, baseLength, center) {
  18320. this._octree = octree;
  18321. this._parent = parent;
  18322. this.baseLength = baseLength;
  18323. center.cloneTo(this.center);
  18324. var min = this._bounds.min;
  18325. var max = this._bounds.max;
  18326. var halfSize = (octree._looseness * baseLength) / 2;
  18327. min.setValue(center.x - halfSize, center.y - halfSize, center.z - halfSize);
  18328. max.setValue(center.x + halfSize, center.y + halfSize, center.z + halfSize);
  18329. }
  18330. _getChildBound(index) {
  18331. if (this._children != null && this._children[index]) {
  18332. return this._children[index]._bounds;
  18333. }
  18334. else {
  18335. var quarter = this.baseLength / 4;
  18336. var halfChildSize = ((this.baseLength / 2) * this._octree._looseness) / 2;
  18337. var bounds = BoundsOctreeNode._tempBoundBox;
  18338. var min = bounds.min;
  18339. var max = bounds.max;
  18340. switch (index) {
  18341. case 0:
  18342. min.x = this.center.x - quarter - halfChildSize;
  18343. min.y = this.center.y + quarter - halfChildSize;
  18344. min.z = this.center.z - quarter - halfChildSize;
  18345. max.x = this.center.x - quarter + halfChildSize;
  18346. max.y = this.center.y + quarter + halfChildSize;
  18347. max.z = this.center.z - quarter + halfChildSize;
  18348. break;
  18349. case 1:
  18350. min.x = this.center.x + quarter - halfChildSize;
  18351. min.y = this.center.y + quarter - halfChildSize;
  18352. min.z = this.center.z - quarter - halfChildSize;
  18353. max.x = this.center.x + quarter + halfChildSize;
  18354. max.y = this.center.y + quarter + halfChildSize;
  18355. max.z = this.center.z - quarter + halfChildSize;
  18356. break;
  18357. case 2:
  18358. min.x = this.center.x - quarter - halfChildSize;
  18359. min.y = this.center.y + quarter - halfChildSize;
  18360. min.z = this.center.z + quarter - halfChildSize;
  18361. max.x = this.center.x - quarter + halfChildSize;
  18362. max.y = this.center.y + quarter + halfChildSize;
  18363. max.z = this.center.z + quarter + halfChildSize;
  18364. break;
  18365. case 3:
  18366. min.x = this.center.x + quarter - halfChildSize;
  18367. min.y = this.center.y + quarter - halfChildSize;
  18368. min.z = this.center.z + quarter - halfChildSize;
  18369. max.x = this.center.x + quarter + halfChildSize;
  18370. max.y = this.center.y + quarter + halfChildSize;
  18371. max.z = this.center.z + quarter + halfChildSize;
  18372. break;
  18373. case 4:
  18374. min.x = this.center.x - quarter - halfChildSize;
  18375. min.y = this.center.y - quarter - halfChildSize;
  18376. min.z = this.center.z - quarter - halfChildSize;
  18377. max.x = this.center.x - quarter + halfChildSize;
  18378. max.y = this.center.y - quarter + halfChildSize;
  18379. max.z = this.center.z - quarter + halfChildSize;
  18380. break;
  18381. case 5:
  18382. min.x = this.center.x + quarter - halfChildSize;
  18383. min.y = this.center.y - quarter - halfChildSize;
  18384. min.z = this.center.z - quarter - halfChildSize;
  18385. max.x = this.center.x + quarter + halfChildSize;
  18386. max.y = this.center.y - quarter + halfChildSize;
  18387. max.z = this.center.z - quarter + halfChildSize;
  18388. break;
  18389. case 6:
  18390. min.x = this.center.x - quarter - halfChildSize;
  18391. min.y = this.center.y - quarter - halfChildSize;
  18392. min.z = this.center.z + quarter - halfChildSize;
  18393. max.x = this.center.x - quarter + halfChildSize;
  18394. max.y = this.center.y - quarter + halfChildSize;
  18395. max.z = this.center.z + quarter + halfChildSize;
  18396. break;
  18397. case 7:
  18398. min.x = this.center.x + quarter - halfChildSize;
  18399. min.y = this.center.y - quarter - halfChildSize;
  18400. min.z = this.center.z + quarter - halfChildSize;
  18401. max.x = this.center.x + quarter + halfChildSize;
  18402. max.y = this.center.y - quarter + halfChildSize;
  18403. max.z = this.center.z + quarter + halfChildSize;
  18404. break;
  18405. default:
  18406. }
  18407. return bounds;
  18408. }
  18409. }
  18410. _getChildCenter(index) {
  18411. if (this._children != null) {
  18412. return this._children[index].center;
  18413. }
  18414. else {
  18415. var quarter = this.baseLength / 4;
  18416. var childCenter = BoundsOctreeNode._tempVector30;
  18417. switch (index) {
  18418. case 0:
  18419. childCenter.x = this.center.x - quarter;
  18420. childCenter.y = this.center.y + quarter;
  18421. childCenter.z = this.center.z - quarter;
  18422. break;
  18423. case 1:
  18424. childCenter.x = this.center.x + quarter;
  18425. childCenter.y = this.center.y + quarter;
  18426. childCenter.z = this.center.z - quarter;
  18427. break;
  18428. case 2:
  18429. childCenter.x = this.center.x - quarter;
  18430. childCenter.y = this.center.y + quarter;
  18431. childCenter.z = this.center.z + quarter;
  18432. break;
  18433. case 3:
  18434. childCenter.x = this.center.x + quarter;
  18435. childCenter.y = this.center.y + quarter;
  18436. childCenter.z = this.center.z + quarter;
  18437. break;
  18438. case 4:
  18439. childCenter.x = this.center.x - quarter;
  18440. childCenter.y = this.center.y - quarter;
  18441. childCenter.z = this.center.z - quarter;
  18442. break;
  18443. case 5:
  18444. childCenter.x = this.center.x + quarter;
  18445. childCenter.y = this.center.y - quarter;
  18446. childCenter.z = this.center.z - quarter;
  18447. break;
  18448. case 6:
  18449. childCenter.x = this.center.x - quarter;
  18450. childCenter.y = this.center.y - quarter;
  18451. childCenter.z = this.center.z + quarter;
  18452. break;
  18453. case 7:
  18454. childCenter.x = this.center.x + quarter;
  18455. childCenter.y = this.center.y - quarter;
  18456. childCenter.z = this.center.z + quarter;
  18457. break;
  18458. default:
  18459. }
  18460. return childCenter;
  18461. }
  18462. }
  18463. _getChild(index) {
  18464. var quarter = this.baseLength / 4;
  18465. this._children || (this._children = []);
  18466. switch (index) {
  18467. case 0:
  18468. 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)));
  18469. case 1:
  18470. 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)));
  18471. case 2:
  18472. 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)));
  18473. case 3:
  18474. 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)));
  18475. case 4:
  18476. 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)));
  18477. case 5:
  18478. 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)));
  18479. case 6:
  18480. 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)));
  18481. case 7:
  18482. 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)));
  18483. default:
  18484. throw "BoundsOctreeNode: unknown index.";
  18485. }
  18486. }
  18487. _shouldMerge() {
  18488. var objectCount = this._objects.length;
  18489. for (var i = 0; i < 8; i++) {
  18490. var child = this._children[i];
  18491. if (child) {
  18492. if (child._children != null)
  18493. return false;
  18494. objectCount += child._objects.length;
  18495. }
  18496. }
  18497. return objectCount <= BoundsOctreeNode._NUM_OBJECTS_ALLOWED;
  18498. }
  18499. _mergeChildren() {
  18500. for (var i = 0; i < 8; i++) {
  18501. var child = this._children[i];
  18502. if (child) {
  18503. child._parent = null;
  18504. var childObjects = child._objects;
  18505. for (var j = childObjects.length - 1; j >= 0; j--) {
  18506. var childObject = childObjects[j];
  18507. this._objects.push(childObject);
  18508. childObject._setOctreeNode(this);
  18509. }
  18510. }
  18511. }
  18512. this._children = null;
  18513. }
  18514. _merge() {
  18515. if (this._children === null) {
  18516. var parent = this._parent;
  18517. if (parent && parent._shouldMerge()) {
  18518. parent._mergeChildren();
  18519. parent._merge();
  18520. }
  18521. }
  18522. }
  18523. _checkAddNode(object) {
  18524. if (this._children == null) {
  18525. if (this._objects.length < BoundsOctreeNode._NUM_OBJECTS_ALLOWED || (this.baseLength / 2) < this._octree._minSize) {
  18526. return this;
  18527. }
  18528. for (var i = this._objects.length - 1; i >= 0; i--) {
  18529. var existObject = this._objects[i];
  18530. var fitChildIndex = this._bestFitChild(existObject.bounds.getCenter());
  18531. if (BoundsOctreeNode._encapsulates(this._getChildBound(fitChildIndex), existObject.bounds._getBoundBox())) {
  18532. this._objects.splice(this._objects.indexOf(existObject), 1);
  18533. this._getChild(fitChildIndex)._add(existObject);
  18534. }
  18535. }
  18536. }
  18537. var newFitChildIndex = this._bestFitChild(object.bounds.getCenter());
  18538. if (BoundsOctreeNode._encapsulates(this._getChildBound(newFitChildIndex), object.bounds._getBoundBox()))
  18539. return this._getChild(newFitChildIndex)._checkAddNode(object);
  18540. else
  18541. return this;
  18542. }
  18543. _add(object) {
  18544. var addNode = this._checkAddNode(object);
  18545. addNode._objects.push(object);
  18546. object._setOctreeNode(addNode);
  18547. }
  18548. _remove(object) {
  18549. var index = this._objects.indexOf(object);
  18550. this._objects.splice(index, 1);
  18551. object._setOctreeNode(null);
  18552. this._merge();
  18553. }
  18554. _addUp(object) {
  18555. if ((CollisionUtils.boxContainsBox(this._bounds, object.bounds._getBoundBox()) === ContainmentType.Contains)) {
  18556. this._add(object);
  18557. return true;
  18558. }
  18559. else {
  18560. if (this._parent)
  18561. return this._parent._addUp(object);
  18562. else
  18563. return false;
  18564. }
  18565. }
  18566. _getCollidingWithFrustum(cameraCullInfo, context, testVisible, customShader, replacementTag, isShadowCasterCull) {
  18567. var frustum = cameraCullInfo.boundFrustum;
  18568. var camPos = cameraCullInfo.position;
  18569. var cullMask = cameraCullInfo.cullingMask;
  18570. if (testVisible) {
  18571. var type = frustum.containsBoundBox(this._bounds);
  18572. Laya.Stat.octreeNodeCulling++;
  18573. if (type === ContainmentType.Disjoint)
  18574. return;
  18575. testVisible = (type === ContainmentType.Intersects);
  18576. }
  18577. this._isContaion = !testVisible;
  18578. var scene = context.scene;
  18579. var loopCount = Laya.Stat.loopCount;
  18580. for (var i = 0, n = this._objects.length; i < n; i++) {
  18581. var render = this._objects[i];
  18582. var canPass;
  18583. if (isShadowCasterCull)
  18584. canPass = render._castShadow && render._enable;
  18585. else
  18586. canPass = (((Math.pow(2, render._owner._layer) & cullMask) != 0)) && render._enable;
  18587. if (canPass) {
  18588. if (testVisible) {
  18589. Laya.Stat.frustumCulling++;
  18590. if (!render._needRender(frustum, context))
  18591. continue;
  18592. }
  18593. render._renderMark = loopCount;
  18594. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  18595. var elements = render._renderElements;
  18596. for (var j = 0, m = elements.length; j < m; j++) {
  18597. var element = elements[j];
  18598. element._update(scene, context, customShader, replacementTag);
  18599. }
  18600. }
  18601. }
  18602. if (this._children != null) {
  18603. for (i = 0; i < 8; i++) {
  18604. var child = this._children[i];
  18605. child && child._getCollidingWithFrustum(cameraCullInfo, context, testVisible, customShader, replacementTag, isShadowCasterCull);
  18606. }
  18607. }
  18608. }
  18609. _getCollidingWithBoundBox(checkBound, testVisible, result) {
  18610. if (testVisible) {
  18611. var type = CollisionUtils.boxContainsBox(this._bounds, checkBound);
  18612. if (type === ContainmentType.Disjoint)
  18613. return;
  18614. testVisible = (type === ContainmentType.Intersects);
  18615. }
  18616. if (testVisible) {
  18617. for (var i = 0, n = this._objects.length; i < n; i++) {
  18618. var object = this._objects[i];
  18619. if (CollisionUtils.intersectsBoxAndBox(object.bounds._getBoundBox(), checkBound)) {
  18620. result.push(object);
  18621. }
  18622. }
  18623. }
  18624. if (this._children != null) {
  18625. for (i = 0; i < 8; i++) {
  18626. var child = this._children[i];
  18627. child._getCollidingWithBoundBox(checkBound, testVisible, result);
  18628. }
  18629. }
  18630. }
  18631. _bestFitChild(boundCenter) {
  18632. return (boundCenter.x <= this.center.x ? 0 : 1) + (boundCenter.y >= this.center.y ? 0 : 4) + (boundCenter.z <= this.center.z ? 0 : 2);
  18633. }
  18634. _update(object) {
  18635. if (CollisionUtils.boxContainsBox(this._bounds, object.bounds._getBoundBox()) === ContainmentType.Contains) {
  18636. var addNode = this._checkAddNode(object);
  18637. if (addNode !== object._getOctreeNode()) {
  18638. addNode._objects.push(object);
  18639. object._setOctreeNode(addNode);
  18640. var index = this._objects.indexOf(object);
  18641. this._objects.splice(index, 1);
  18642. this._merge();
  18643. }
  18644. return true;
  18645. }
  18646. else {
  18647. if (this._parent) {
  18648. var sucess = this._parent._addUp(object);
  18649. if (sucess) {
  18650. index = this._objects.indexOf(object);
  18651. this._objects.splice(index, 1);
  18652. this._merge();
  18653. }
  18654. return sucess;
  18655. }
  18656. else {
  18657. return false;
  18658. }
  18659. }
  18660. }
  18661. add(object) {
  18662. if (!BoundsOctreeNode._encapsulates(this._bounds, object.bounds._getBoundBox()))
  18663. return false;
  18664. this._add(object);
  18665. return true;
  18666. }
  18667. remove(object) {
  18668. if (object._getOctreeNode() !== this)
  18669. return false;
  18670. this._remove(object);
  18671. return true;
  18672. }
  18673. update(object) {
  18674. if (object._getOctreeNode() !== this)
  18675. return false;
  18676. return this._update(object);
  18677. }
  18678. shrinkIfPossible(minLength) {
  18679. if (this.baseLength < minLength * 2)
  18680. return this;
  18681. var bestFit = -1;
  18682. for (var i = 0, n = this._objects.length; i < n; i++) {
  18683. var object = this._objects[i];
  18684. var newBestFit = this._bestFitChild(object.bounds.getCenter());
  18685. if (i == 0 || newBestFit == bestFit) {
  18686. var childBounds = this._getChildBound(newBestFit);
  18687. if (BoundsOctreeNode._encapsulates(childBounds, object.bounds._getBoundBox()))
  18688. (i == 0) && (bestFit = newBestFit);
  18689. else
  18690. return this;
  18691. }
  18692. else {
  18693. return this;
  18694. }
  18695. }
  18696. if (this._children != null) {
  18697. var childHadContent = false;
  18698. for (i = 0, n = this._children.length; i < n; i++) {
  18699. var child = this._children[i];
  18700. if (child && child.hasAnyObjects()) {
  18701. if (childHadContent)
  18702. return this;
  18703. if (bestFit >= 0 && bestFit != i)
  18704. return this;
  18705. childHadContent = true;
  18706. bestFit = i;
  18707. }
  18708. }
  18709. }
  18710. else {
  18711. if (bestFit != -1) {
  18712. var childCenter = this._getChildCenter(bestFit);
  18713. this._setValues(this._octree, null, this.baseLength / 2, childCenter);
  18714. }
  18715. return this;
  18716. }
  18717. if (bestFit != -1) {
  18718. var newRoot = this._children[bestFit];
  18719. newRoot._parent = null;
  18720. return newRoot;
  18721. }
  18722. else {
  18723. return this;
  18724. }
  18725. }
  18726. hasAnyObjects() {
  18727. if (this._objects.length > 0)
  18728. return true;
  18729. if (this._children != null) {
  18730. for (var i = 0; i < 8; i++) {
  18731. var child = this._children[i];
  18732. if (child && child.hasAnyObjects())
  18733. return true;
  18734. }
  18735. }
  18736. return false;
  18737. }
  18738. getCollidingWithBoundBox(checkBound, result) {
  18739. this._getCollidingWithBoundBox(checkBound, true, result);
  18740. }
  18741. getCollidingWithRay(ray, result, maxDistance = Number.MAX_VALUE) {
  18742. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, this._bounds);
  18743. if (distance == -1 || distance > maxDistance)
  18744. return;
  18745. for (var i = 0, n = this._objects.length; i < n; i++) {
  18746. var object = this._objects[i];
  18747. distance = CollisionUtils.intersectsRayAndBoxRD(ray, object.bounds._getBoundBox());
  18748. if (distance !== -1 && distance <= maxDistance)
  18749. result.push(object);
  18750. }
  18751. if (this._children != null) {
  18752. for (i = 0; i < 8; i++) {
  18753. var child = this._children[i];
  18754. child.getCollidingWithRay(ray, result, maxDistance);
  18755. }
  18756. }
  18757. }
  18758. getCollidingWithFrustum(cameraCullInfo, context, customShader, replacementTag, isShadowCasterCull) {
  18759. this._getCollidingWithFrustum(cameraCullInfo, context, true, customShader, replacementTag, isShadowCasterCull);
  18760. }
  18761. isCollidingWithBoundBox(checkBound) {
  18762. if (!(CollisionUtils.intersectsBoxAndBox(this._bounds, checkBound)))
  18763. return false;
  18764. for (var i = 0, n = this._objects.length; i < n; i++) {
  18765. var object = this._objects[i];
  18766. if (CollisionUtils.intersectsBoxAndBox(object.bounds._getBoundBox(), checkBound))
  18767. return true;
  18768. }
  18769. if (this._children != null) {
  18770. for (i = 0; i < 8; i++) {
  18771. var child = this._children[i];
  18772. if (child.isCollidingWithBoundBox(checkBound))
  18773. return true;
  18774. }
  18775. }
  18776. return false;
  18777. }
  18778. isCollidingWithRay(ray, maxDistance = Number.MAX_VALUE) {
  18779. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, this._bounds);
  18780. if (distance == -1 || distance > maxDistance)
  18781. return false;
  18782. for (var i = 0, n = this._objects.length; i < n; i++) {
  18783. var object = this._objects[i];
  18784. distance = CollisionUtils.intersectsRayAndBoxRD(ray, object.bounds._getBoundBox());
  18785. if (distance !== -1 && distance <= maxDistance)
  18786. return true;
  18787. }
  18788. if (this._children != null) {
  18789. for (i = 0; i < 8; i++) {
  18790. var child = this._children[i];
  18791. if (child.isCollidingWithRay(ray, maxDistance))
  18792. return true;
  18793. }
  18794. }
  18795. return false;
  18796. }
  18797. getBound() {
  18798. return this._bounds;
  18799. }
  18800. drawAllBounds(debugLine, currentDepth, maxDepth) {
  18801. if (this._children === null && this._objects.length == 0)
  18802. return;
  18803. currentDepth++;
  18804. var color = BoundsOctreeNode._tempColor0;
  18805. if (this._isContaion) {
  18806. color.r = 0.0;
  18807. color.g = 0.0;
  18808. color.b = 1.0;
  18809. }
  18810. else {
  18811. var tint = maxDepth ? currentDepth / maxDepth : 0;
  18812. color.r = 1.0 - tint;
  18813. color.g = tint;
  18814. color.b = 0.0;
  18815. }
  18816. color.a = 0.3;
  18817. Utils3D._drawBound(debugLine, this._bounds, color);
  18818. if (this._children != null) {
  18819. for (var i = 0; i < 8; i++) {
  18820. var child = this._children[i];
  18821. child && child.drawAllBounds(debugLine, currentDepth, maxDepth);
  18822. }
  18823. }
  18824. }
  18825. drawAllObjects(debugLine, currentDepth, maxDepth) {
  18826. currentDepth++;
  18827. var color = BoundsOctreeNode._tempColor0;
  18828. if (this._isContaion) {
  18829. color.r = 0.0;
  18830. color.g = 0.0;
  18831. color.b = 1.0;
  18832. }
  18833. else {
  18834. var tint = maxDepth ? currentDepth / maxDepth : 0;
  18835. color.r = 1.0 - tint;
  18836. color.g = tint;
  18837. color.b = 0.0;
  18838. }
  18839. color.a = 1.0;
  18840. for (var i = 0, n = this._objects.length; i < n; i++)
  18841. Utils3D._drawBound(debugLine, this._objects[i].bounds._getBoundBox(), color);
  18842. if (this._children != null) {
  18843. for (i = 0; i < 8; i++) {
  18844. var child = this._children[i];
  18845. child && child.drawAllObjects(debugLine, currentDepth, maxDepth);
  18846. }
  18847. }
  18848. }
  18849. }
  18850. BoundsOctreeNode._tempVector3 = new Vector3();
  18851. BoundsOctreeNode._tempVector30 = new Vector3();
  18852. BoundsOctreeNode._tempVector31 = new Vector3();
  18853. BoundsOctreeNode._tempColor0 = new Color();
  18854. BoundsOctreeNode._tempBoundBox = new BoundBox(new Vector3(), new Vector3());
  18855. BoundsOctreeNode._NUM_OBJECTS_ALLOWED = 8;
  18856. class OctreeMotionList extends SingletonList {
  18857. constructor() {
  18858. super();
  18859. }
  18860. add(element) {
  18861. var index = element._getIndexInMotionList();
  18862. if (index !== -1)
  18863. throw "OctreeMotionList:element has in PhysicsUpdateList.";
  18864. this._add(element);
  18865. element._setIndexInMotionList(this.length++);
  18866. }
  18867. remove(element) {
  18868. var index = element._getIndexInMotionList();
  18869. this.length--;
  18870. if (index !== this.length) {
  18871. var end = this.elements[this.length];
  18872. this.elements[index] = end;
  18873. end._setIndexInMotionList(index);
  18874. }
  18875. element._setIndexInMotionList(-1);
  18876. }
  18877. }
  18878. class BoundsOctree {
  18879. constructor(initialWorldSize, initialWorldPos, minNodeSize, looseness) {
  18880. this._motionObjects = new OctreeMotionList();
  18881. this.count = 0;
  18882. if (minNodeSize > initialWorldSize) {
  18883. console.warn("Minimum node size must be at least as big as the initial world size. Was: " + minNodeSize + " Adjusted to: " + initialWorldSize);
  18884. minNodeSize = initialWorldSize;
  18885. }
  18886. this._initialSize = initialWorldSize;
  18887. this._minSize = minNodeSize;
  18888. this._looseness = Math.min(Math.max(looseness, 1.0), 2.0);
  18889. this._rootNode = new BoundsOctreeNode(this, null, initialWorldSize, initialWorldPos);
  18890. }
  18891. _getMaxDepth(node, depth) {
  18892. depth++;
  18893. var children = node._children;
  18894. if (children != null) {
  18895. var curDepth = depth;
  18896. for (var i = 0, n = children.length; i < n; i++) {
  18897. var child = children[i];
  18898. child && (depth = Math.max(this._getMaxDepth(child, curDepth), depth));
  18899. }
  18900. }
  18901. return depth;
  18902. }
  18903. _grow(growObjectCenter) {
  18904. var xDirection = growObjectCenter.x >= 0 ? 1 : -1;
  18905. var yDirection = growObjectCenter.y >= 0 ? 1 : -1;
  18906. var zDirection = growObjectCenter.z >= 0 ? 1 : -1;
  18907. var oldRoot = this._rootNode;
  18908. var half = this._rootNode.baseLength / 2;
  18909. var newLength = this._rootNode.baseLength * 2;
  18910. var rootCenter = this._rootNode.center;
  18911. var newCenter = new Vector3(rootCenter.x + xDirection * half, rootCenter.y + yDirection * half, rootCenter.z + zDirection * half);
  18912. this._rootNode = new BoundsOctreeNode(this, null, newLength, newCenter);
  18913. if (oldRoot.hasAnyObjects()) {
  18914. var rootPos = this._rootNode._bestFitChild(oldRoot.center);
  18915. var children = [];
  18916. for (var i = 0; i < 8; i++) {
  18917. if (i == rootPos) {
  18918. oldRoot._parent = this._rootNode;
  18919. children[i] = oldRoot;
  18920. }
  18921. }
  18922. this._rootNode._children = children;
  18923. }
  18924. }
  18925. add(object) {
  18926. var count = 0;
  18927. while (!this._rootNode.add(object)) {
  18928. var growCenter = BoundsOctree._tempVector30;
  18929. Vector3.subtract(object.bounds.getCenter(), this._rootNode.center, growCenter);
  18930. this._grow(growCenter);
  18931. if (++count > 20) {
  18932. throw "Aborted Add operation as it seemed to be going on forever (" + (count - 1) + ") attempts at growing the octree.";
  18933. }
  18934. }
  18935. this.count++;
  18936. }
  18937. remove(object) {
  18938. var removed = object._getOctreeNode().remove(object);
  18939. if (removed) {
  18940. this.count--;
  18941. }
  18942. return removed;
  18943. }
  18944. update(object) {
  18945. var count = 0;
  18946. var octreeNode = object._getOctreeNode();
  18947. if (octreeNode) {
  18948. while (!octreeNode._update(object)) {
  18949. var growCenter = BoundsOctree._tempVector30;
  18950. Vector3.subtract(object.bounds.getCenter(), this._rootNode.center, growCenter);
  18951. this._grow(growCenter);
  18952. if (++count > 20) {
  18953. throw "Aborted Add operation as it seemed to be going on forever (" + (count - 1) + ") attempts at growing the octree.";
  18954. }
  18955. }
  18956. return true;
  18957. }
  18958. else {
  18959. return false;
  18960. }
  18961. }
  18962. shrinkRootIfPossible() {
  18963. this._rootNode = this._rootNode.shrinkIfPossible(this._initialSize);
  18964. }
  18965. addMotionObject(object) {
  18966. this._motionObjects.add(object);
  18967. }
  18968. removeMotionObject(object) {
  18969. this._motionObjects.remove(object);
  18970. }
  18971. updateMotionObjects() {
  18972. var elements = this._motionObjects.elements;
  18973. for (var i = 0, n = this._motionObjects.length; i < n; i++) {
  18974. var object = elements[i];
  18975. this.update(object);
  18976. object._setIndexInMotionList(-1);
  18977. }
  18978. this._motionObjects.length = 0;
  18979. }
  18980. isCollidingWithBoundBox(checkBounds) {
  18981. return this._rootNode.isCollidingWithBoundBox(checkBounds);
  18982. }
  18983. isCollidingWithRay(ray, maxDistance = Number.MAX_VALUE) {
  18984. return this._rootNode.isCollidingWithRay(ray, maxDistance);
  18985. }
  18986. getCollidingWithBoundBox(checkBound, result) {
  18987. this._rootNode.getCollidingWithBoundBox(checkBound, result);
  18988. }
  18989. getCollidingWithRay(ray, result, maxDistance = Number.MAX_VALUE) {
  18990. this._rootNode.getCollidingWithRay(ray, result, maxDistance);
  18991. }
  18992. getCollidingWithFrustum(cameraCullInfo, context, shader, replacementTag, isShadowCasterCull) {
  18993. this._rootNode.getCollidingWithFrustum(cameraCullInfo, context, shader, replacementTag, isShadowCasterCull);
  18994. }
  18995. getMaxBounds() {
  18996. return this._rootNode.getBound();
  18997. }
  18998. drawAllBounds(pixelLine) {
  18999. var maxDepth = this._getMaxDepth(this._rootNode, -1);
  19000. this._rootNode.drawAllBounds(pixelLine, -1, maxDepth);
  19001. }
  19002. drawAllObjects(pixelLine) {
  19003. var maxDepth = this._getMaxDepth(this._rootNode, -1);
  19004. this._rootNode.drawAllObjects(pixelLine, -1, maxDepth);
  19005. }
  19006. }
  19007. BoundsOctree._tempVector30 = new Vector3();
  19008. class Lightmap {
  19009. }
  19010. class BoundSphere {
  19011. constructor(center, radius) {
  19012. this.center = center;
  19013. this.radius = radius;
  19014. }
  19015. toDefault() {
  19016. this.center.toDefault();
  19017. this.radius = 0;
  19018. }
  19019. static createFromSubPoints(points, start, count, out) {
  19020. if (points == null) {
  19021. throw new Error("points");
  19022. }
  19023. if (start < 0 || start >= points.length) {
  19024. throw new Error("start" + start + "Must be in the range [0, " + (points.length - 1) + "]");
  19025. }
  19026. if (count < 0 || (start + count) > points.length) {
  19027. throw new Error("count" + count + "Must be in the range <= " + points.length + "}");
  19028. }
  19029. var upperEnd = start + count;
  19030. var center = BoundSphere._tempVector3;
  19031. center.x = 0;
  19032. center.y = 0;
  19033. center.z = 0;
  19034. for (var i = start; i < upperEnd; ++i) {
  19035. Vector3.add(points[i], center, center);
  19036. }
  19037. var outCenter = out.center;
  19038. Vector3.scale(center, 1 / count, outCenter);
  19039. var radius = 0.0;
  19040. for (i = start; i < upperEnd; ++i) {
  19041. var distance = Vector3.distanceSquared(outCenter, points[i]);
  19042. if (distance > radius)
  19043. radius = distance;
  19044. }
  19045. out.radius = Math.sqrt(radius);
  19046. }
  19047. static createfromPoints(points, out) {
  19048. if (points == null) {
  19049. throw new Error("points");
  19050. }
  19051. BoundSphere.createFromSubPoints(points, 0, points.length, out);
  19052. }
  19053. intersectsRayDistance(ray) {
  19054. return CollisionUtils.intersectsRayAndSphereRD(ray, this);
  19055. }
  19056. intersectsRayPoint(ray, outPoint) {
  19057. return CollisionUtils.intersectsRayAndSphereRP(ray, this, outPoint);
  19058. }
  19059. cloneTo(destObject) {
  19060. var dest = destObject;
  19061. this.center.cloneTo(dest.center);
  19062. dest.radius = this.radius;
  19063. }
  19064. clone() {
  19065. var dest = new BoundSphere(new Vector3(), 0);
  19066. this.cloneTo(dest);
  19067. return dest;
  19068. }
  19069. }
  19070. BoundSphere._tempVector3 = new Vector3();
  19071. class ShadowSliceData {
  19072. constructor() {
  19073. this.cameraShaderValue = new ShaderData();
  19074. this.position = new Vector3();
  19075. this.viewMatrix = new Matrix4x4();
  19076. this.projectionMatrix = new Matrix4x4();
  19077. this.viewProjectMatrix = new Matrix4x4();
  19078. this.cullPlanes = [new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3())];
  19079. this.splitBoundSphere = new BoundSphere(new Vector3(), 0.0);
  19080. }
  19081. }
  19082. class ShadowSpotData {
  19083. constructor() {
  19084. this.cameraShaderValue = new ShaderData();
  19085. this.position = new Vector3;
  19086. this.viewMatrix = new Matrix4x4();
  19087. this.projectionMatrix = new Matrix4x4();
  19088. this.viewProjectMatrix = new Matrix4x4();
  19089. this.cameraCullInfo = new CameraCullInfo();
  19090. }
  19091. }
  19092. (function (ShadowLightType) {
  19093. ShadowLightType[ShadowLightType["DirectionLight"] = 0] = "DirectionLight";
  19094. ShadowLightType[ShadowLightType["SpotLight"] = 1] = "SpotLight";
  19095. ShadowLightType[ShadowLightType["PointLight"] = 2] = "PointLight";
  19096. })(exports.ShadowLightType || (exports.ShadowLightType = {}));
  19097. class ShadowCasterPass {
  19098. constructor() {
  19099. this._shadowBias = new Vector4();
  19100. this._shadowParams = new Vector4();
  19101. this._shadowMapSize = new Vector4();
  19102. this._shadowMatrices = new Float32Array(16 * (ShadowCasterPass._maxCascades));
  19103. this._shadowSpotMatrices = new Matrix4x4();
  19104. this._splitBoundSpheres = new Float32Array(ShadowCasterPass._maxCascades * 4);
  19105. this._cascadeCount = 0;
  19106. this._shadowMapWidth = 0;
  19107. this._shadowMapHeight = 0;
  19108. this._shadowSliceDatas = [new ShadowSliceData(), new ShadowSliceData(), new ShadowSliceData(), new ShadowSliceData()];
  19109. this._shadowSpotData = new ShadowSpotData();
  19110. this._lightUp = new Vector3();
  19111. this._lightSide = new Vector3();
  19112. this._lightForward = new Vector3();
  19113. this._shadowSpotData.cameraCullInfo.boundFrustum = new BoundFrustum(new Matrix4x4());
  19114. }
  19115. _setupShadowCasterShaderValues(context, shaderValues, shadowSliceData, LightParam, shadowparams, shadowBias, lightType) {
  19116. shaderValues.setVector(ShadowCasterPass.SHADOW_BIAS, shadowBias);
  19117. switch (lightType) {
  19118. case exports.LightType.Directional:
  19119. shaderValues.setVector3(ShadowCasterPass.SHADOW_LIGHT_DIRECTION, LightParam);
  19120. break;
  19121. case exports.LightType.Spot:
  19122. shaderValues.setVector(ShadowCasterPass.SHADOW_PARAMS, shadowparams);
  19123. break;
  19124. case exports.LightType.Point:
  19125. break;
  19126. }
  19127. var cameraSV = shadowSliceData.cameraShaderValue;
  19128. cameraSV.setMatrix4x4(BaseCamera.VIEWMATRIX, shadowSliceData.viewMatrix);
  19129. cameraSV.setMatrix4x4(BaseCamera.PROJECTMATRIX, shadowSliceData.projectionMatrix);
  19130. cameraSV.setMatrix4x4(BaseCamera.VIEWPROJECTMATRIX, shadowSliceData.viewProjectMatrix);
  19131. context.viewMatrix = shadowSliceData.viewMatrix;
  19132. context.projectionMatrix = shadowSliceData.projectionMatrix;
  19133. context.projectionViewMatrix = shadowSliceData.viewProjectMatrix;
  19134. }
  19135. _setupShadowReceiverShaderValues(shaderValues) {
  19136. var light = this._light;
  19137. if (light.shadowCascadesMode !== exports.ShadowCascadesMode.NoCascades)
  19138. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_CASCADE);
  19139. else
  19140. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_CASCADE);
  19141. switch (light.shadowMode) {
  19142. case exports.ShadowMode.Hard:
  19143. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_LOW);
  19144. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_HIGH);
  19145. break;
  19146. case exports.ShadowMode.SoftLow:
  19147. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_LOW);
  19148. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_HIGH);
  19149. break;
  19150. case exports.ShadowMode.SoftHigh:
  19151. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_HIGH);
  19152. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_LOW);
  19153. break;
  19154. }
  19155. shaderValues.setTexture(ShadowCasterPass.SHADOW_MAP, this._shadowDirectLightMap);
  19156. shaderValues.setBuffer(ShadowCasterPass.SHADOW_MATRICES, this._shadowMatrices);
  19157. shaderValues.setVector(ShadowCasterPass.SHADOW_MAP_SIZE, this._shadowMapSize);
  19158. shaderValues.setVector(ShadowCasterPass.SHADOW_PARAMS, this._shadowParams);
  19159. shaderValues.setBuffer(ShadowCasterPass.SHADOW_SPLIT_SPHERES, this._splitBoundSpheres);
  19160. }
  19161. _setupSpotShadowReceiverShaderValues(shaderValues) {
  19162. var spotLight = this._light;
  19163. switch (spotLight.shadowMode) {
  19164. case exports.ShadowMode.Hard:
  19165. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_HIGH);
  19166. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_LOW);
  19167. break;
  19168. case exports.ShadowMode.SoftLow:
  19169. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_LOW);
  19170. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_HIGH);
  19171. break;
  19172. case exports.ShadowMode.SoftHigh:
  19173. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_HIGH);
  19174. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_LOW);
  19175. break;
  19176. }
  19177. shaderValues.setTexture(ShadowCasterPass.SHADOW_SPOTMAP, this._shadowSpotLightMap);
  19178. shaderValues.setMatrix4x4(ShadowCasterPass.SHADOW_SPOTMATRICES, this._shadowSpotMatrices);
  19179. shaderValues.setVector(ShadowCasterPass.SHADOW_MAP_SIZE, this._shadowMapSize);
  19180. shaderValues.setVector(ShadowCasterPass.SHADOW_PARAMS, this._shadowParams);
  19181. }
  19182. update(camera, light, lightType) {
  19183. switch (lightType) {
  19184. case exports.ShadowLightType.DirectionLight:
  19185. this._light = light;
  19186. var lightWorld = ShadowCasterPass._tempMatrix0;
  19187. var lightWorldE = lightWorld.elements;
  19188. var lightUp = this._lightUp;
  19189. var lightSide = this._lightSide;
  19190. var lightForward = this._lightForward;
  19191. Matrix4x4.createFromQuaternion(light._transform.rotation, lightWorld);
  19192. lightSide.setValue(lightWorldE[0], lightWorldE[1], lightWorldE[2]);
  19193. lightUp.setValue(lightWorldE[4], lightWorldE[5], lightWorldE[6]);
  19194. lightForward.setValue(-lightWorldE[8], -lightWorldE[9], -lightWorldE[10]);
  19195. var atlasResolution = light._shadowResolution;
  19196. var cascadesMode = light._shadowCascadesMode;
  19197. var cascadesCount;
  19198. var shadowTileResolution;
  19199. var shadowMapWidth, shadowMapHeight;
  19200. if (cascadesMode == exports.ShadowCascadesMode.NoCascades) {
  19201. cascadesCount = 1;
  19202. shadowTileResolution = atlasResolution;
  19203. shadowMapWidth = atlasResolution;
  19204. shadowMapHeight = atlasResolution;
  19205. }
  19206. else {
  19207. cascadesCount = cascadesMode == exports.ShadowCascadesMode.TwoCascades ? 2 : 4;
  19208. shadowTileResolution = ShadowUtils.getMaxTileResolutionInAtlas(atlasResolution, atlasResolution, cascadesCount);
  19209. shadowMapWidth = shadowTileResolution * 2;
  19210. shadowMapHeight = cascadesMode == exports.ShadowCascadesMode.TwoCascades ? shadowTileResolution : shadowTileResolution * 2;
  19211. }
  19212. this._cascadeCount = cascadesCount;
  19213. this._shadowMapWidth = shadowMapWidth;
  19214. this._shadowMapHeight = shadowMapHeight;
  19215. var splitDistance = ShadowCasterPass._cascadesSplitDistance;
  19216. var frustumPlanes = ShadowCasterPass._frustumPlanes;
  19217. var cameraNear = camera.nearPlane;
  19218. var shadowFar = Math.min(camera.farPlane, light._shadowDistance);
  19219. var shadowMatrices = this._shadowMatrices;
  19220. var boundSpheres = this._splitBoundSpheres;
  19221. ShadowUtils.getCascadesSplitDistance(light._shadowTwoCascadeSplits, light._shadowFourCascadeSplits, cameraNear, shadowFar, camera.fieldOfView * MathUtils3D.Deg2Rad, camera.aspectRatio, cascadesMode, splitDistance);
  19222. ShadowUtils.getCameraFrustumPlanes(camera.projectionViewMatrix, frustumPlanes);
  19223. var forward = ShadowCasterPass._tempVector30;
  19224. camera._transform.getForward(forward);
  19225. Vector3.normalize(forward, forward);
  19226. for (var i = 0; i < cascadesCount; i++) {
  19227. var sliceData = this._shadowSliceDatas[i];
  19228. sliceData.sphereCenterZ = ShadowUtils.getBoundSphereByFrustum(splitDistance[i], splitDistance[i + 1], camera.fieldOfView * MathUtils3D.Deg2Rad, camera.aspectRatio, camera._transform.position, forward, sliceData.splitBoundSphere);
  19229. ShadowUtils.getDirectionLightShadowCullPlanes(frustumPlanes, i, splitDistance, cameraNear, lightForward, sliceData);
  19230. ShadowUtils.getDirectionalLightMatrices(lightUp, lightSide, lightForward, i, light._shadowNearPlane, shadowTileResolution, sliceData, shadowMatrices);
  19231. if (cascadesCount > 1)
  19232. ShadowUtils.applySliceTransform(sliceData, shadowMapWidth, shadowMapHeight, i, shadowMatrices);
  19233. }
  19234. ShadowUtils.prepareShadowReceiverShaderValues(light, shadowMapWidth, shadowMapHeight, this._shadowSliceDatas, cascadesCount, this._shadowMapSize, this._shadowParams, shadowMatrices, boundSpheres);
  19235. break;
  19236. case exports.ShadowLightType.SpotLight:
  19237. this._light = light;
  19238. var lightWorld = ShadowCasterPass._tempMatrix0;
  19239. var lightForward = this._lightForward;
  19240. var shadowResolution = this._light._shadowResolution;
  19241. this._shadowMapWidth = shadowResolution;
  19242. this._shadowMapHeight = shadowResolution;
  19243. var shadowSpotData = this._shadowSpotData;
  19244. ShadowUtils.getSpotLightShadowData(shadowSpotData, this._light, shadowResolution, this._shadowParams, this._shadowSpotMatrices, this._shadowMapSize);
  19245. break;
  19246. case exports.ShadowLightType.PointLight:
  19247. break;
  19248. default:
  19249. throw ("There is no shadow of this type");
  19250. break;
  19251. }
  19252. }
  19253. render(context, scene, lightType) {
  19254. switch (lightType) {
  19255. case exports.ShadowLightType.DirectionLight:
  19256. var shaderValues = scene._shaderValues;
  19257. context.pipelineMode = "ShadowCaster";
  19258. ShaderData.setRuntimeValueMode(false);
  19259. var shadowMap = this._shadowDirectLightMap = ShadowUtils.getTemporaryShadowTexture(this._shadowMapWidth, this._shadowMapHeight, Laya.RenderTextureDepthFormat.DEPTH_16);
  19260. shadowMap._start();
  19261. var light = this._light;
  19262. for (var i = 0, n = this._cascadeCount; i < n; i++) {
  19263. var sliceData = this._shadowSliceDatas[i];
  19264. ShadowUtils.getShadowBias(light, sliceData.projectionMatrix, sliceData.resolution, this._shadowBias);
  19265. this._setupShadowCasterShaderValues(context, shaderValues, sliceData, this._lightForward, this._shadowParams, this._shadowBias, exports.LightType.Directional);
  19266. var shadowCullInfo = FrustumCulling._shadowCullInfo;
  19267. shadowCullInfo.position = sliceData.position;
  19268. shadowCullInfo.cullPlanes = sliceData.cullPlanes;
  19269. shadowCullInfo.cullPlaneCount = sliceData.cullPlaneCount;
  19270. shadowCullInfo.cullSphere = sliceData.splitBoundSphere;
  19271. shadowCullInfo.direction = this._lightForward;
  19272. var needRender = FrustumCulling.cullingShadow(shadowCullInfo, scene, context);
  19273. context.cameraShaderValue = sliceData.cameraShaderValue;
  19274. Camera._updateMark++;
  19275. var gl = Laya.LayaGL.instance;
  19276. var resolution = sliceData.resolution;
  19277. var offsetX = sliceData.offsetX;
  19278. var offsetY = sliceData.offsetY;
  19279. gl.enable(gl.SCISSOR_TEST);
  19280. gl.viewport(offsetX, offsetY, resolution, resolution);
  19281. gl.scissor(offsetX, offsetY, resolution, resolution);
  19282. gl.clear(gl.DEPTH_BUFFER_BIT);
  19283. if (needRender) {
  19284. gl.scissor(offsetX + 1, offsetY + 1, resolution - 2, resolution - 2);
  19285. scene._opaqueQueue._render(context);
  19286. }
  19287. }
  19288. shadowMap._end();
  19289. this._setupShadowReceiverShaderValues(shaderValues);
  19290. ShaderData.setRuntimeValueMode(true);
  19291. context.pipelineMode = "Forward";
  19292. break;
  19293. case exports.ShadowLightType.SpotLight:
  19294. var shaderValues = scene._shaderValues;
  19295. context.pipelineMode = "ShadowCaster";
  19296. ShaderData.setRuntimeValueMode(false);
  19297. var spotlight = this._light;
  19298. var shadowMap = this._shadowSpotLightMap = ShadowUtils.getTemporaryShadowTexture(this._shadowMapWidth, this._shadowMapHeight, Laya.RenderTextureDepthFormat.DEPTH_16);
  19299. shadowMap._start();
  19300. var shadowSpotData = this._shadowSpotData;
  19301. ShadowUtils.getShadowBias(spotlight, shadowSpotData.projectionMatrix, shadowSpotData.resolution, this._shadowBias);
  19302. this._setupShadowCasterShaderValues(context, shaderValues, shadowSpotData, this._light.transform.position, this._shadowParams, this._shadowBias, exports.LightType.Spot);
  19303. var needRender = FrustumCulling.cullingSpotShadow(shadowSpotData.cameraCullInfo, scene, context);
  19304. context.cameraShaderValue = shadowSpotData.cameraShaderValue;
  19305. Camera._updateMark++;
  19306. var gl = Laya.LayaGL.instance;
  19307. gl.enable(gl.SCISSOR_TEST);
  19308. gl.viewport(shadowSpotData.offsetX, shadowSpotData.offsetY, shadowSpotData.resolution, shadowSpotData.resolution);
  19309. gl.scissor(shadowSpotData.offsetX, shadowSpotData.offsetY, shadowSpotData.resolution, shadowSpotData.resolution);
  19310. gl.clear(gl.DEPTH_BUFFER_BIT);
  19311. if (needRender) {
  19312. gl.scissor(shadowSpotData.offsetX, shadowSpotData.offsetY, shadowSpotData.resolution, shadowSpotData.resolution);
  19313. scene._opaqueQueue._render(context);
  19314. }
  19315. shadowMap._end();
  19316. this._setupSpotShadowReceiverShaderValues(shaderValues);
  19317. ShaderData.setRuntimeValueMode(true);
  19318. context.pipelineMode = "Forward";
  19319. break;
  19320. case exports.ShadowLightType.PointLight:
  19321. break;
  19322. default:
  19323. throw ("There is no shadow of this type");
  19324. break;
  19325. }
  19326. }
  19327. cleanUp() {
  19328. this._shadowDirectLightMap && RenderTexture.recoverToPool(this._shadowDirectLightMap);
  19329. this._shadowSpotLightMap && RenderTexture.recoverToPool(this._shadowSpotLightMap);
  19330. this._shadowDirectLightMap = null;
  19331. this._shadowSpotLightMap = null;
  19332. this._light = null;
  19333. }
  19334. }
  19335. ShadowCasterPass._tempVector30 = new Vector3();
  19336. ShadowCasterPass._tempMatrix0 = new Matrix4x4();
  19337. ShadowCasterPass.SHADOW_BIAS = Shader3D.propertyNameToID("u_ShadowBias");
  19338. ShadowCasterPass.SHADOW_LIGHT_DIRECTION = Shader3D.propertyNameToID("u_ShadowLightDirection");
  19339. ShadowCasterPass.SHADOW_SPLIT_SPHERES = Shader3D.propertyNameToID("u_ShadowSplitSpheres");
  19340. ShadowCasterPass.SHADOW_MATRICES = Shader3D.propertyNameToID("u_ShadowMatrices");
  19341. ShadowCasterPass.SHADOW_MAP_SIZE = Shader3D.propertyNameToID("u_ShadowMapSize");
  19342. ShadowCasterPass.SHADOW_MAP = Shader3D.propertyNameToID("u_ShadowMap");
  19343. ShadowCasterPass.SHADOW_PARAMS = Shader3D.propertyNameToID("u_ShadowParams");
  19344. ShadowCasterPass.SHADOW_SPOTMAP = Shader3D.propertyNameToID("u_SpotShadowMap");
  19345. ShadowCasterPass.SHADOW_SPOTMATRICES = Shader3D.propertyNameToID("u_SpotViewProjectMatrix");
  19346. ShadowCasterPass._maxCascades = 4;
  19347. ShadowCasterPass._cascadesSplitDistance = new Array(ShadowCasterPass._maxCascades + 1);
  19348. ShadowCasterPass._frustumPlanes = new Array(new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()));
  19349. class DynamicBatchManager {
  19350. constructor() {
  19351. this._batchRenderElementPool = [];
  19352. }
  19353. static _registerManager(manager) {
  19354. DynamicBatchManager._managers.push(manager);
  19355. }
  19356. _clear() {
  19357. this._batchRenderElementPoolIndex = 0;
  19358. }
  19359. _getBatchRenderElementFromPool() {
  19360. throw "StaticBatch:must override this function.";
  19361. }
  19362. dispose() {
  19363. }
  19364. }
  19365. DynamicBatchManager._managers = [];
  19366. (function (AmbientMode) {
  19367. AmbientMode[AmbientMode["SolidColor"] = 0] = "SolidColor";
  19368. AmbientMode[AmbientMode["SphericalHarmonics"] = 1] = "SphericalHarmonics";
  19369. })(exports.AmbientMode || (exports.AmbientMode = {}));
  19370. class Scene3D extends Laya.Sprite {
  19371. constructor() {
  19372. super();
  19373. this._lightCount = 0;
  19374. this._pointLights = new LightQueue();
  19375. this._spotLights = new LightQueue();
  19376. this._directionLights = new LightQueue();
  19377. this._alternateLights = new AlternateLightQueue();
  19378. this._lightmaps = [];
  19379. this._skyRenderer = new SkyRenderer();
  19380. this._input = new Input3D();
  19381. this._timer = Laya.ILaya.timer;
  19382. this._time = 0;
  19383. this._shCoefficients = new Array(7);
  19384. this._ambientMode = exports.AmbientMode.SolidColor;
  19385. this._ambientSphericalHarmonics = new SphericalHarmonicsL2();
  19386. this._ambientSphericalHarmonicsIntensity = 1.0;
  19387. this._reflectionDecodeFormat = Laya.TextureDecodeFormat.Normal;
  19388. this._reflectionIntensity = 1.0;
  19389. this._collsionTestList = [];
  19390. this._renders = new SimpleSingletonList();
  19391. this._opaqueQueue = new RenderQueue(false);
  19392. this._transparentQueue = new RenderQueue(true);
  19393. this._cameraPool = [];
  19394. this._animatorPool = new SimpleSingletonList();
  19395. this._scriptPool = new Array();
  19396. this._tempScriptPool = new Array();
  19397. this._needClearScriptPool = false;
  19398. this._reflectionCubeHDRParams = new Vector4();
  19399. this.currentCreationLayer = Math.pow(2, 0);
  19400. this.enableLight = true;
  19401. this._key = new Laya.SubmitKey();
  19402. this._pickIdToSprite = new Object();
  19403. this._reflectionMode = 0;
  19404. if (!Config3D._config.isUseCannonPhysicsEngine && Physics3D._bullet)
  19405. this._physicsSimulation = new PhysicsSimulation(Scene3D.physicsSettings);
  19406. else if (Physics3D._cannon) {
  19407. this._cannonPhysicsSimulation = new Laya.CannonPhysicsSimulation(Scene3D.cannonPhysicsSettings);
  19408. }
  19409. this._shaderValues = new ShaderData(null);
  19410. this.enableFog = false;
  19411. this.fogStart = 300;
  19412. this.fogRange = 1000;
  19413. this.fogColor = new Vector3(0.7, 0.7, 0.7);
  19414. this.ambientColor = new Vector3(0.212, 0.227, 0.259);
  19415. this.reflectionIntensity = 1.0;
  19416. this.reflection = TextureCube.blackTexture;
  19417. for (var i = 0; i < 7; i++)
  19418. this._shCoefficients[i] = new Vector4();
  19419. this._shaderValues.setVector(Scene3D.REFLECTIONCUBE_HDR_PARAMS, this._reflectionCubeHDRParams);
  19420. if (Laya.Render.supportWebGLPlusCulling) {
  19421. this._cullingBufferIndices = new Int32Array(1024);
  19422. this._cullingBufferResult = new Int32Array(1024);
  19423. }
  19424. this._scene = this;
  19425. this._input.__init__(Laya.Render.canvas, this);
  19426. if (Scene3D.octreeCulling)
  19427. this._octree = new BoundsOctree(Scene3D.octreeInitialSize, Scene3D.octreeInitialCenter, Scene3D.octreeMinNodeSize, Scene3D.octreeLooseness);
  19428. if (FrustumCulling.debugFrustumCulling) {
  19429. this._debugTool = new PixelLineSprite3D();
  19430. var lineMaterial = new PixelLineMaterial();
  19431. lineMaterial.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  19432. lineMaterial.alphaTest = false;
  19433. lineMaterial.depthWrite = false;
  19434. lineMaterial.cull = RenderState.CULL_BACK;
  19435. lineMaterial.blend = RenderState.BLEND_ENABLE_ALL;
  19436. lineMaterial.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  19437. lineMaterial.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  19438. lineMaterial.depthTest = RenderState.DEPTHTEST_LESS;
  19439. this._debugTool.pixelLineRenderer.sharedMaterial = lineMaterial;
  19440. }
  19441. }
  19442. static __init__() {
  19443. var con = Config3D._config;
  19444. var multiLighting = con._multiLighting;
  19445. if (multiLighting) {
  19446. const width = 4;
  19447. var maxLightCount = con.maxLightCount;
  19448. var clusterSlices = con.lightClusterCount;
  19449. Cluster.instance = new Cluster(clusterSlices.x, clusterSlices.y, clusterSlices.z, Math.min(con.maxLightCount, con._maxAreaLightCountPerClusterAverage));
  19450. Scene3D._lightTexture = Utils3D._createFloatTextureBuffer(width, maxLightCount);
  19451. Scene3D._lightTexture.lock = true;
  19452. Scene3D._lightPixles = new Float32Array(maxLightCount * width * 4);
  19453. }
  19454. Scene3DShaderDeclaration.SHADERDEFINE_FOG = Shader3D.getDefineByName("FOG");
  19455. Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT = Shader3D.getDefineByName("DIRECTIONLIGHT");
  19456. Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT = Shader3D.getDefineByName("POINTLIGHT");
  19457. Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT = Shader3D.getDefineByName("SPOTLIGHT");
  19458. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW = Shader3D.getDefineByName("SHADOW");
  19459. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_CASCADE = Shader3D.getDefineByName("SHADOW_CASCADE");
  19460. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_LOW = Shader3D.getDefineByName("SHADOW_SOFT_SHADOW_LOW");
  19461. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_HIGH = Shader3D.getDefineByName("SHADOW_SOFT_SHADOW_HIGH");
  19462. Scene3DShaderDeclaration.SHADERDEFINE_GI_AMBIENT_SH = Shader3D.getDefineByName("GI_AMBIENT_SH");
  19463. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT = Shader3D.getDefineByName("SHADOW_SPOT");
  19464. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_LOW = Shader3D.getDefineByName("SHADOW_SPOT_SOFT_SHADOW_LOW");
  19465. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_HIGH = Shader3D.getDefineByName("SHADOW_SPOT_SOFT_SHADOW_HIGH");
  19466. var config = Config3D._config;
  19467. var configShaderValue = Scene3D._configDefineValues;
  19468. (config._multiLighting) || (configShaderValue.add(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING));
  19469. if (Laya.LayaGL.layaGPUInstance._isWebGL2)
  19470. configShaderValue.add(Shader3D.SHADERDEFINE_GRAPHICS_API_GLES3);
  19471. else
  19472. configShaderValue.add(Shader3D.SHADERDEFINE_GRAPHICS_API_GLES2);
  19473. switch (config.pbrRenderQuality) {
  19474. case exports.PBRRenderQuality.High:
  19475. configShaderValue.add(PBRMaterial.SHADERDEFINE_LAYA_PBR_BRDF_HIGH);
  19476. break;
  19477. case exports.PBRRenderQuality.Low:
  19478. configShaderValue.add(PBRMaterial.SHADERDEFINE_LAYA_PBR_BRDF_LOW);
  19479. break;
  19480. default:
  19481. throw "Scene3D:unknown shader quality.";
  19482. }
  19483. if (config.isUseCannonPhysicsEngine) {
  19484. Scene3D.cannonPhysicsSettings = new Laya.CannonPhysicsSettings();
  19485. }
  19486. else {
  19487. Scene3D.physicsSettings = new PhysicsSettings();
  19488. }
  19489. }
  19490. static load(url, complete) {
  19491. Laya.ILaya.loader.create(url, complete, null, Scene3D.HIERARCHY);
  19492. }
  19493. get url() {
  19494. return this._url;
  19495. }
  19496. get enableFog() {
  19497. return this._enableFog;
  19498. }
  19499. set enableFog(value) {
  19500. if (this._enableFog !== value) {
  19501. this._enableFog = value;
  19502. if (value) {
  19503. this._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_FOG);
  19504. }
  19505. else
  19506. this._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_FOG);
  19507. }
  19508. }
  19509. get fogColor() {
  19510. return this._shaderValues.getVector3(Scene3D.FOGCOLOR);
  19511. }
  19512. set fogColor(value) {
  19513. this._shaderValues.setVector3(Scene3D.FOGCOLOR, value);
  19514. }
  19515. get fogStart() {
  19516. return this._shaderValues.getNumber(Scene3D.FOGSTART);
  19517. }
  19518. set fogStart(value) {
  19519. this._shaderValues.setNumber(Scene3D.FOGSTART, value);
  19520. }
  19521. get fogRange() {
  19522. return this._shaderValues.getNumber(Scene3D.FOGRANGE);
  19523. }
  19524. set fogRange(value) {
  19525. this._shaderValues.setNumber(Scene3D.FOGRANGE, value);
  19526. }
  19527. get ambientMode() {
  19528. return this._ambientMode;
  19529. }
  19530. set ambientMode(value) {
  19531. if (this._ambientMode !== value) {
  19532. switch (value) {
  19533. case exports.AmbientMode.SolidColor:
  19534. this._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_GI_AMBIENT_SH);
  19535. break;
  19536. case exports.AmbientMode.SphericalHarmonics:
  19537. this._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_GI_AMBIENT_SH);
  19538. break;
  19539. default:
  19540. throw "Scene3D: unknown ambientMode.";
  19541. }
  19542. this._ambientMode = value;
  19543. }
  19544. }
  19545. get ambientColor() {
  19546. return this._shaderValues.getVector3(Scene3D.AMBIENTCOLOR);
  19547. }
  19548. set ambientColor(value) {
  19549. this._shaderValues.setVector3(Scene3D.AMBIENTCOLOR, value);
  19550. }
  19551. get ambientSphericalHarmonics() {
  19552. return this._ambientSphericalHarmonics;
  19553. }
  19554. set ambientSphericalHarmonics(value) {
  19555. var originalSH = value || SphericalHarmonicsL2._default;
  19556. this._applySHCoefficients(originalSH, Math.pow(this._ambientSphericalHarmonicsIntensity, 2.2));
  19557. if (this._ambientSphericalHarmonics != value)
  19558. value.cloneTo(this._ambientSphericalHarmonics);
  19559. }
  19560. get ambientSphericalHarmonicsIntensity() {
  19561. return this._ambientSphericalHarmonicsIntensity;
  19562. }
  19563. set ambientSphericalHarmonicsIntensity(value) {
  19564. value = Math.max(Math.min(value, 8.0), 0.0);
  19565. if (this._ambientSphericalHarmonicsIntensity !== value) {
  19566. var originalSH = this._ambientSphericalHarmonics || SphericalHarmonicsL2._default;
  19567. this._applySHCoefficients(originalSH, Math.pow(value, 2.2));
  19568. this._ambientSphericalHarmonicsIntensity = value;
  19569. }
  19570. }
  19571. get reflection() {
  19572. return this._reflection;
  19573. }
  19574. set reflection(value) {
  19575. if (this._reflection != value) {
  19576. this._shaderValues.setTexture(Scene3D.REFLECTIONTEXTURE, value || TextureCube.blackTexture);
  19577. this._reflection = value;
  19578. }
  19579. }
  19580. get reflectionDecodingFormat() {
  19581. return this._reflectionDecodeFormat;
  19582. }
  19583. set reflectionDecodingFormat(value) {
  19584. if (this._reflectionDecodeFormat != value) {
  19585. this._reflectionCubeHDRParams.x = this._reflectionIntensity;
  19586. if (this._reflectionDecodeFormat == Laya.TextureDecodeFormat.RGBM)
  19587. this._reflectionCubeHDRParams.x *= 5.0;
  19588. this._reflectionDecodeFormat = value;
  19589. }
  19590. }
  19591. get reflectionIntensity() {
  19592. return this._reflectionIntensity;
  19593. }
  19594. set reflectionIntensity(value) {
  19595. value = Math.max(Math.min(value, 1.0), 0.0);
  19596. this._reflectionCubeHDRParams.x = value;
  19597. if (this._reflectionDecodeFormat == Laya.TextureDecodeFormat.RGBM)
  19598. this._reflectionCubeHDRParams.x *= 5.0;
  19599. this._reflectionIntensity = value;
  19600. }
  19601. get skyRenderer() {
  19602. return this._skyRenderer;
  19603. }
  19604. get physicsSimulation() {
  19605. return this._physicsSimulation;
  19606. }
  19607. get cannonPhysicsSimulation() {
  19608. return this._cannonPhysicsSimulation;
  19609. }
  19610. get timer() {
  19611. return this._timer;
  19612. }
  19613. set timer(value) {
  19614. this._timer = value;
  19615. }
  19616. get input() {
  19617. return this._input;
  19618. }
  19619. get lightmaps() {
  19620. return this._lightmaps.slice();
  19621. }
  19622. set lightmaps(value) {
  19623. var maps = this._lightmaps;
  19624. if (maps) {
  19625. for (var i = 0, n = maps.length; i < n; i++) {
  19626. var map = maps[i];
  19627. map.lightmapColor._removeReference();
  19628. map.lightmapDirection._removeReference();
  19629. }
  19630. }
  19631. if (value) {
  19632. var count = value.length;
  19633. maps.length = count;
  19634. for (i = 0; i < count; i++) {
  19635. var map = value[i];
  19636. map.lightmapColor && map.lightmapColor._addReference();
  19637. map.lightmapDirection && map.lightmapDirection._addReference();
  19638. maps[i] = map;
  19639. }
  19640. }
  19641. else {
  19642. maps.length = 0;
  19643. }
  19644. }
  19645. _applySHCoefficients(originalSH, intensity) {
  19646. var optSH = this._shCoefficients;
  19647. for (var i = 0; i < 3; i++) {
  19648. var shaderSHA = optSH[i];
  19649. var shaderSHB = optSH[i + 3];
  19650. shaderSHA.setValue(originalSH.getCoefficient(i, 3) * intensity, originalSH.getCoefficient(i, 1) * intensity, originalSH.getCoefficient(i, 2) * intensity, (originalSH.getCoefficient(i, 0) - originalSH.getCoefficient(i, 6)) * intensity);
  19651. shaderSHB.setValue(originalSH.getCoefficient(i, 4) * intensity, originalSH.getCoefficient(i, 5) * intensity, originalSH.getCoefficient(i, 6) * 3 * intensity, originalSH.getCoefficient(i, 7) * intensity);
  19652. }
  19653. optSH[6].setValue(originalSH.getCoefficient(0, 8) * intensity, originalSH.getCoefficient(1, 8) * intensity, originalSH.getCoefficient(2, 8) * intensity, 1);
  19654. var shaderValues = this._shaderValues;
  19655. shaderValues.setVector(Scene3D.AMBIENTSHAR, optSH[0]);
  19656. shaderValues.setVector(Scene3D.AMBIENTSHAG, optSH[1]);
  19657. shaderValues.setVector(Scene3D.AMBIENTSHAB, optSH[2]);
  19658. shaderValues.setVector(Scene3D.AMBIENTSHBR, optSH[3]);
  19659. shaderValues.setVector(Scene3D.AMBIENTSHBG, optSH[4]);
  19660. shaderValues.setVector(Scene3D.AMBIENTSHBB, optSH[5]);
  19661. shaderValues.setVector(Scene3D.AMBIENTSHC, optSH[6]);
  19662. }
  19663. _update() {
  19664. var delta = this.timer._delta / 1000;
  19665. this._time += delta;
  19666. this._shaderValues.setNumber(Scene3D.TIME, this._time);
  19667. var simulation = this._physicsSimulation;
  19668. if (Physics3D._enablePhysics && !PhysicsSimulation.disableSimulation && !Config3D._config.isUseCannonPhysicsEngine) {
  19669. simulation._updatePhysicsTransformFromRender();
  19670. PhysicsComponent._addUpdateList = false;
  19671. simulation._simulate(delta);
  19672. simulation._updateCharacters();
  19673. PhysicsComponent._addUpdateList = true;
  19674. simulation._updateCollisions();
  19675. simulation._eventScripts();
  19676. }
  19677. if (Physics3D._cannon && Config3D._config.isUseCannonPhysicsEngine) {
  19678. var cannonSimulation = this._cannonPhysicsSimulation;
  19679. cannonSimulation._updatePhysicsTransformFromRender();
  19680. Laya.CannonPhysicsComponent._addUpdateList = false;
  19681. cannonSimulation._simulate(delta);
  19682. Laya.CannonPhysicsComponent._addUpdateList = true;
  19683. cannonSimulation._updateCollisions();
  19684. cannonSimulation._eventScripts();
  19685. }
  19686. this._input._update();
  19687. this._clearScript();
  19688. this._updateScript();
  19689. Animator._update(this);
  19690. this._lateUpdateScript();
  19691. }
  19692. _binarySearchIndexInCameraPool(camera) {
  19693. var start = 0;
  19694. var end = this._cameraPool.length - 1;
  19695. var mid;
  19696. while (start <= end) {
  19697. mid = Math.floor((start + end) / 2);
  19698. var midValue = this._cameraPool[mid]._renderingOrder;
  19699. if (midValue == camera._renderingOrder)
  19700. return mid;
  19701. else if (midValue > camera._renderingOrder)
  19702. end = mid - 1;
  19703. else
  19704. start = mid + 1;
  19705. }
  19706. return start;
  19707. }
  19708. _allotPickColorByID(id, pickColor) {
  19709. var pickColorR = Math.floor(id / (255 * 255));
  19710. id -= pickColorR * 255 * 255;
  19711. var pickColorG = Math.floor(id / 255);
  19712. id -= pickColorG * 255;
  19713. var pickColorB = id;
  19714. pickColor.x = pickColorR / 255;
  19715. pickColor.y = pickColorG / 255;
  19716. pickColor.z = pickColorB / 255;
  19717. pickColor.w = 1.0;
  19718. }
  19719. _searchIDByPickColor(pickColor) {
  19720. var id = pickColor.x * 255 * 255 + pickColor.y * 255 + pickColor.z;
  19721. return id;
  19722. }
  19723. onEnable() {
  19724. this._input._onCanvasEvent(Laya.Render.canvas);
  19725. }
  19726. onDisable() {
  19727. this._input._offCanvasEvent(Laya.Render.canvas);
  19728. }
  19729. _setCreateURL(url) {
  19730. this._url = Laya.URL.formatURL(url);
  19731. }
  19732. _getGroup() {
  19733. return this._group;
  19734. }
  19735. _setGroup(value) {
  19736. this._group = value;
  19737. }
  19738. _clearScript() {
  19739. if (this._needClearScriptPool) {
  19740. var scripts = this._scriptPool;
  19741. for (var i = 0, n = scripts.length; i < n; i++) {
  19742. var script = scripts[i];
  19743. if (script) {
  19744. script._indexInPool = this._tempScriptPool.length;
  19745. this._tempScriptPool.push(script);
  19746. }
  19747. }
  19748. this._scriptPool = this._tempScriptPool;
  19749. scripts.length = 0;
  19750. this._tempScriptPool = scripts;
  19751. this._needClearScriptPool = false;
  19752. }
  19753. }
  19754. _updateScript() {
  19755. var scripts = this._scriptPool;
  19756. for (var i = 0, n = scripts.length; i < n; i++) {
  19757. var script = scripts[i];
  19758. (script && script.enabled) && (script.onUpdate());
  19759. }
  19760. }
  19761. _lateUpdateScript() {
  19762. var scripts = this._scriptPool;
  19763. for (var i = 0, n = scripts.length; i < n; i++) {
  19764. var script = scripts[i];
  19765. (script && script.enabled) && (script.onLateUpdate());
  19766. }
  19767. }
  19768. _onActive() {
  19769. super._onActive();
  19770. Laya.ILaya.stage._scene3Ds.push(this);
  19771. }
  19772. _onInActive() {
  19773. super._onInActive();
  19774. var scenes = Laya.ILaya.stage._scene3Ds;
  19775. scenes.splice(scenes.indexOf(this), 1);
  19776. }
  19777. _prepareSceneToRender() {
  19778. var shaderValues = this._shaderValues;
  19779. var multiLighting = Config3D._config._multiLighting;
  19780. if (multiLighting) {
  19781. var ligTex = Scene3D._lightTexture;
  19782. var ligPix = Scene3D._lightPixles;
  19783. const pixelWidth = ligTex.width;
  19784. const floatWidth = pixelWidth * 4;
  19785. var curCount = 0;
  19786. var dirCount = this._directionLights._length;
  19787. var dirElements = this._directionLights._elements;
  19788. if (dirCount > 0) {
  19789. var sunLightIndex = this._directionLights.getBrightestLight();
  19790. this._mainDirectionLight = dirElements[sunLightIndex];
  19791. this._directionLights.normalLightOrdering(sunLightIndex);
  19792. for (var i = 0; i < dirCount; i++, curCount++) {
  19793. var dirLight = dirElements[i];
  19794. var dir = dirLight._direction;
  19795. var intCor = dirLight._intensityColor;
  19796. var off = floatWidth * curCount;
  19797. Vector3.scale(dirLight.color, dirLight._intensity, intCor);
  19798. dirLight.transform.worldMatrix.getForward(dir);
  19799. Vector3.normalize(dir, dir);
  19800. ligPix[off] = intCor.x;
  19801. ligPix[off + 1] = intCor.y;
  19802. ligPix[off + 2] = intCor.z;
  19803. ligPix[off + 4] = dir.x;
  19804. ligPix[off + 5] = dir.y;
  19805. ligPix[off + 6] = dir.z;
  19806. if (i == 0) {
  19807. shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, intCor);
  19808. shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dir);
  19809. }
  19810. }
  19811. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  19812. }
  19813. else {
  19814. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  19815. }
  19816. var poiCount = this._pointLights._length;
  19817. if (poiCount > 0) {
  19818. var poiElements = this._pointLights._elements;
  19819. var mainPointLightIndex = this._pointLights.getBrightestLight();
  19820. this._mainPointLight = poiElements[mainPointLightIndex];
  19821. this._pointLights.normalLightOrdering(mainPointLightIndex);
  19822. for (var i = 0; i < poiCount; i++, curCount++) {
  19823. var poiLight = poiElements[i];
  19824. var pos = poiLight.transform.position;
  19825. var intCor = poiLight._intensityColor;
  19826. var off = floatWidth * curCount;
  19827. Vector3.scale(poiLight.color, poiLight._intensity, intCor);
  19828. ligPix[off] = intCor.x;
  19829. ligPix[off + 1] = intCor.y;
  19830. ligPix[off + 2] = intCor.z;
  19831. ligPix[off + 3] = poiLight.range;
  19832. ligPix[off + 4] = pos.x;
  19833. ligPix[off + 5] = pos.y;
  19834. ligPix[off + 6] = pos.z;
  19835. }
  19836. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  19837. }
  19838. else {
  19839. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  19840. }
  19841. var spoCount = this._spotLights._length;
  19842. if (spoCount > 0) {
  19843. var spoElements = this._spotLights._elements;
  19844. var mainSpotLightIndex = this._spotLights.getBrightestLight();
  19845. this._mainSpotLight = spoElements[mainSpotLightIndex];
  19846. this._spotLights.normalLightOrdering(mainSpotLightIndex);
  19847. for (var i = 0; i < spoCount; i++, curCount++) {
  19848. var spoLight = spoElements[i];
  19849. var dir = spoLight._direction;
  19850. var pos = spoLight.transform.position;
  19851. var intCor = spoLight._intensityColor;
  19852. var off = floatWidth * curCount;
  19853. Vector3.scale(spoLight.color, spoLight._intensity, intCor);
  19854. spoLight.transform.worldMatrix.getForward(dir);
  19855. Vector3.normalize(dir, dir);
  19856. ligPix[off] = intCor.x;
  19857. ligPix[off + 1] = intCor.y;
  19858. ligPix[off + 2] = intCor.z;
  19859. ligPix[off + 3] = spoLight.range;
  19860. ligPix[off + 4] = pos.x;
  19861. ligPix[off + 5] = pos.y;
  19862. ligPix[off + 6] = pos.z;
  19863. ligPix[off + 7] = spoLight.spotAngle * Math.PI / 180;
  19864. ligPix[off + 8] = dir.x;
  19865. ligPix[off + 9] = dir.y;
  19866. ligPix[off + 10] = dir.z;
  19867. }
  19868. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  19869. }
  19870. else {
  19871. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  19872. }
  19873. (curCount > 0) && (ligTex.setSubPixels(0, 0, pixelWidth, curCount, ligPix, 0));
  19874. shaderValues.setTexture(Scene3D.LIGHTBUFFER, ligTex);
  19875. shaderValues.setInt(Scene3D.DIRECTIONLIGHTCOUNT, this._directionLights._length);
  19876. shaderValues.setTexture(Scene3D.CLUSTERBUFFER, Cluster.instance._clusterTexture);
  19877. }
  19878. else {
  19879. if (this._directionLights._length > 0) {
  19880. var dirLight = this._directionLights._elements[0];
  19881. this._mainDirectionLight = dirLight;
  19882. Vector3.scale(dirLight.color, dirLight._intensity, dirLight._intensityColor);
  19883. dirLight.transform.worldMatrix.getForward(dirLight._direction);
  19884. Vector3.normalize(dirLight._direction, dirLight._direction);
  19885. shaderValues.setVector3(Scene3D.LIGHTDIRCOLOR, dirLight._intensityColor);
  19886. shaderValues.setVector3(Scene3D.LIGHTDIRECTION, dirLight._direction);
  19887. shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, dirLight._intensityColor);
  19888. shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dirLight._direction);
  19889. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  19890. }
  19891. else {
  19892. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  19893. }
  19894. if (this._pointLights._length > 0) {
  19895. var poiLight = this._pointLights._elements[0];
  19896. Vector3.scale(poiLight.color, poiLight._intensity, poiLight._intensityColor);
  19897. shaderValues.setVector3(Scene3D.POINTLIGHTCOLOR, poiLight._intensityColor);
  19898. shaderValues.setVector3(Scene3D.POINTLIGHTPOS, poiLight.transform.position);
  19899. shaderValues.setNumber(Scene3D.POINTLIGHTRANGE, poiLight.range);
  19900. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  19901. }
  19902. else {
  19903. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  19904. }
  19905. if (this._spotLights._length > 0) {
  19906. var spotLight = this._spotLights._elements[0];
  19907. Vector3.scale(spotLight.color, spotLight._intensity, spotLight._intensityColor);
  19908. shaderValues.setVector3(Scene3D.SPOTLIGHTCOLOR, spotLight._intensityColor);
  19909. shaderValues.setVector3(Scene3D.SPOTLIGHTPOS, spotLight.transform.position);
  19910. spotLight.transform.worldMatrix.getForward(spotLight._direction);
  19911. Vector3.normalize(spotLight._direction, spotLight._direction);
  19912. shaderValues.setVector3(Scene3D.SPOTLIGHTDIRECTION, spotLight._direction);
  19913. shaderValues.setNumber(Scene3D.SPOTLIGHTRANGE, spotLight.range);
  19914. shaderValues.setNumber(Scene3D.SPOTLIGHTSPOTANGLE, spotLight.spotAngle * Math.PI / 180);
  19915. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  19916. }
  19917. else {
  19918. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  19919. }
  19920. }
  19921. }
  19922. _addScript(script) {
  19923. var scripts = this._scriptPool;
  19924. script._indexInPool = scripts.length;
  19925. scripts.push(script);
  19926. }
  19927. _removeScript(script) {
  19928. this._scriptPool[script._indexInPool] = null;
  19929. script._indexInPool = -1;
  19930. this._needClearScriptPool = true;
  19931. }
  19932. _preRenderScript() {
  19933. var scripts = this._scriptPool;
  19934. for (var i = 0, n = scripts.length; i < n; i++) {
  19935. var script = scripts[i];
  19936. (script && script.enabled) && (script.onPreRender());
  19937. }
  19938. }
  19939. _postRenderScript() {
  19940. var scripts = this._scriptPool;
  19941. for (var i = 0, n = scripts.length; i < n; i++) {
  19942. var script = scripts[i];
  19943. (script && script.enabled) && (script.onPostRender());
  19944. }
  19945. }
  19946. _addCamera(camera) {
  19947. var index = this._binarySearchIndexInCameraPool(camera);
  19948. var order = camera._renderingOrder;
  19949. var count = this._cameraPool.length;
  19950. while (index < count && this._cameraPool[index]._renderingOrder <= order)
  19951. index++;
  19952. this._cameraPool.splice(index, 0, camera);
  19953. }
  19954. _removeCamera(camera) {
  19955. this._cameraPool.splice(this._cameraPool.indexOf(camera), 1);
  19956. }
  19957. _preCulling(context, camera, shader, replacementTag) {
  19958. var cameraCullInfo = FrustumCulling._cameraCullInfo;
  19959. cameraCullInfo.position = camera._transform.position;
  19960. cameraCullInfo.cullingMask = camera.cullingMask;
  19961. cameraCullInfo.boundFrustum = camera.boundFrustum;
  19962. cameraCullInfo.useOcclusionCulling = camera.useOcclusionCulling;
  19963. FrustumCulling.renderObjectCulling(cameraCullInfo, this, context, shader, replacementTag, false);
  19964. }
  19965. _clear(gl, state) {
  19966. var viewport = state.viewport;
  19967. var camera = state.camera;
  19968. var renderTex = camera._getRenderTexture();
  19969. var vpX, vpY;
  19970. var vpW = viewport.width;
  19971. var vpH = viewport.height;
  19972. if (camera._needInternalRenderTexture()) {
  19973. vpX = 0;
  19974. vpY = 0;
  19975. }
  19976. else {
  19977. vpX = viewport.x;
  19978. vpY = camera._getCanvasHeight() - viewport.y - vpH;
  19979. }
  19980. gl.viewport(vpX, vpY, vpW, vpH);
  19981. var flag;
  19982. var clearFlag = camera.clearFlag;
  19983. if (clearFlag === exports.CameraClearFlags.Sky && !(camera.skyRenderer._isAvailable() || this._skyRenderer._isAvailable()))
  19984. clearFlag = exports.CameraClearFlags.SolidColor;
  19985. switch (clearFlag) {
  19986. case exports.CameraClearFlags.SolidColor:
  19987. var clearColor = camera.clearColor;
  19988. gl.enable(gl.SCISSOR_TEST);
  19989. gl.scissor(vpX, vpY, vpW, vpH);
  19990. if (clearColor)
  19991. gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  19992. else
  19993. gl.clearColor(0, 0, 0, 0);
  19994. if (renderTex) {
  19995. flag = gl.COLOR_BUFFER_BIT;
  19996. switch (renderTex.depthStencilFormat) {
  19997. case Laya.RenderTextureDepthFormat.DEPTH_16:
  19998. flag |= gl.DEPTH_BUFFER_BIT;
  19999. break;
  20000. case Laya.RenderTextureDepthFormat.STENCIL_8:
  20001. flag |= gl.STENCIL_BUFFER_BIT;
  20002. break;
  20003. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_24_8:
  20004. flag |= gl.DEPTH_BUFFER_BIT;
  20005. flag |= gl.STENCIL_BUFFER_BIT;
  20006. break;
  20007. }
  20008. }
  20009. else {
  20010. flag = gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;
  20011. }
  20012. Laya.WebGLContext.setDepthMask(gl, true);
  20013. gl.clear(flag);
  20014. gl.disable(gl.SCISSOR_TEST);
  20015. break;
  20016. case exports.CameraClearFlags.Sky:
  20017. case exports.CameraClearFlags.DepthOnly:
  20018. gl.enable(gl.SCISSOR_TEST);
  20019. gl.scissor(vpX, vpY, vpW, vpH);
  20020. if (renderTex) {
  20021. switch (renderTex.depthStencilFormat) {
  20022. case Laya.RenderTextureDepthFormat.DEPTH_16:
  20023. flag = gl.DEPTH_BUFFER_BIT;
  20024. break;
  20025. case Laya.RenderTextureDepthFormat.STENCIL_8:
  20026. flag = gl.STENCIL_BUFFER_BIT;
  20027. break;
  20028. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_24_8:
  20029. flag = gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT;
  20030. break;
  20031. }
  20032. }
  20033. else {
  20034. flag = gl.DEPTH_BUFFER_BIT;
  20035. }
  20036. Laya.WebGLContext.setDepthMask(gl, true);
  20037. gl.clear(flag);
  20038. gl.disable(gl.SCISSOR_TEST);
  20039. break;
  20040. case exports.CameraClearFlags.Nothing:
  20041. break;
  20042. default:
  20043. throw new Error("Scene3D:camera clearFlag invalid.");
  20044. }
  20045. }
  20046. _renderScene(context) {
  20047. var camera = context.camera;
  20048. this._opaqueQueue._render(context);
  20049. if (camera.clearFlag === exports.CameraClearFlags.Sky) {
  20050. if (camera.skyRenderer._isAvailable())
  20051. camera.skyRenderer._render(context);
  20052. else if (this._skyRenderer._isAvailable())
  20053. this._skyRenderer._render(context);
  20054. }
  20055. this._transparentQueue._render(context);
  20056. if (FrustumCulling.debugFrustumCulling) {
  20057. var renderElements = this._debugTool._render._renderElements;
  20058. for (var i = 0, n = renderElements.length; i < n; i++) {
  20059. renderElements[i]._update(this, context, null, null);
  20060. renderElements[i]._render(context);
  20061. }
  20062. }
  20063. }
  20064. _parse(data, spriteMap) {
  20065. var lightMapsData = data.lightmaps;
  20066. if (lightMapsData) {
  20067. var lightMapCount = lightMapsData.length;
  20068. var lightmaps = new Array(lightMapCount);
  20069. for (var i = 0; i < lightMapCount; i++) {
  20070. var lightMap = new Lightmap();
  20071. var lightMapData = lightMapsData[i];
  20072. if (lightMapData.path) {
  20073. lightMap.lightmapColor = Laya.Loader.getRes(lightMapData.path);
  20074. }
  20075. else {
  20076. lightMap.lightmapColor = Laya.Loader.getRes(lightMapData.color.path);
  20077. if (lightMapData.direction)
  20078. lightMap.lightmapDirection = Laya.Loader.getRes(lightMapData.direction.path);
  20079. }
  20080. lightmaps[i] = lightMap;
  20081. }
  20082. this.lightmaps = lightmaps;
  20083. }
  20084. var ambientColorData = data.ambientColor;
  20085. if (ambientColorData) {
  20086. var ambCol = this.ambientColor;
  20087. ambCol.fromArray(ambientColorData);
  20088. this.ambientColor = ambCol;
  20089. }
  20090. var skyData = data.sky;
  20091. if (skyData) {
  20092. this._skyRenderer.material = Laya.Loader.getRes(skyData.material.path);
  20093. switch (skyData.mesh) {
  20094. case "SkyBox":
  20095. this._skyRenderer.mesh = SkyBox.instance;
  20096. break;
  20097. case "SkyDome":
  20098. this._skyRenderer.mesh = SkyDome.instance;
  20099. break;
  20100. default:
  20101. this.skyRenderer.mesh = SkyBox.instance;
  20102. }
  20103. }
  20104. this.enableFog = data.enableFog;
  20105. this.fogStart = data.fogStart;
  20106. this.fogRange = data.fogRange;
  20107. var fogColorData = data.fogColor;
  20108. if (fogColorData) {
  20109. var fogCol = this.fogColor;
  20110. fogCol.fromArray(fogColorData);
  20111. this.fogColor = fogCol;
  20112. }
  20113. var ambientSphericalHarmonicsData = data.ambientSphericalHarmonics;
  20114. if (ambientSphericalHarmonicsData) {
  20115. var ambientSH = this.ambientSphericalHarmonics;
  20116. for (var i = 0; i < 3; i++) {
  20117. var off = i * 9;
  20118. ambientSH.setCoefficients(i, ambientSphericalHarmonicsData[off], ambientSphericalHarmonicsData[off + 1], ambientSphericalHarmonicsData[off + 2], ambientSphericalHarmonicsData[off + 3], ambientSphericalHarmonicsData[off + 4], ambientSphericalHarmonicsData[off + 5], ambientSphericalHarmonicsData[off + 6], ambientSphericalHarmonicsData[off + 7], ambientSphericalHarmonicsData[off + 8]);
  20119. }
  20120. this.ambientSphericalHarmonics = ambientSH;
  20121. }
  20122. var reflectionData = data.reflection;
  20123. (reflectionData != undefined) && (this.reflection = Laya.Loader.getRes(reflectionData));
  20124. var reflectionDecodingFormatData = data.reflectionDecodingFormat;
  20125. (reflectionDecodingFormatData != undefined) && (this.reflectionDecodingFormat = reflectionDecodingFormatData);
  20126. var ambientModeData = data.ambientMode;
  20127. (ambientModeData != undefined) && (this.ambientMode = ambientModeData);
  20128. var ambientSphericalHarmonicsIntensityData = data.ambientSphericalHarmonicsIntensity;
  20129. (ambientSphericalHarmonicsIntensityData != undefined) && (this.ambientSphericalHarmonicsIntensity = ambientSphericalHarmonicsIntensityData);
  20130. var reflectionIntensityData = data.reflectionIntensity;
  20131. (reflectionIntensityData != undefined) && (this.reflectionIntensity = reflectionIntensityData);
  20132. }
  20133. _addRenderObject(render) {
  20134. if (this._octree && render._supportOctree) {
  20135. this._octree.add(render);
  20136. }
  20137. else {
  20138. this._renders.add(render);
  20139. if (Laya.Render.supportWebGLPlusCulling) {
  20140. var indexInList = render._getIndexInList();
  20141. var length = this._cullingBufferIndices.length;
  20142. if (indexInList >= length) {
  20143. var tempIndices = this._cullingBufferIndices;
  20144. var tempResult = this._cullingBufferResult;
  20145. this._cullingBufferIndices = new Int32Array(length + 1024);
  20146. this._cullingBufferResult = new Int32Array(length + 1024);
  20147. this._cullingBufferIndices.set(tempIndices, 0);
  20148. this._cullingBufferResult.set(tempResult, 0);
  20149. }
  20150. this._cullingBufferIndices[indexInList] = render._cullingBufferIndex;
  20151. }
  20152. }
  20153. }
  20154. _removeRenderObject(render) {
  20155. if (this._octree && render._supportOctree) {
  20156. this._octree.remove(render);
  20157. }
  20158. else {
  20159. var endRender;
  20160. if (Laya.Render.supportWebGLPlusCulling) {
  20161. endRender = this._renders.elements[this._renders.length - 1];
  20162. }
  20163. this._renders.remove(render);
  20164. if (Laya.Render.supportWebGLPlusCulling) {
  20165. this._cullingBufferIndices[endRender._getIndexInList()] = endRender._cullingBufferIndex;
  20166. }
  20167. }
  20168. }
  20169. _getRenderQueue(index) {
  20170. if (index <= 2500)
  20171. return this._opaqueQueue;
  20172. else
  20173. return this._transparentQueue;
  20174. }
  20175. _clearRenderQueue() {
  20176. this._opaqueQueue.clear();
  20177. this._transparentQueue.clear();
  20178. var staticBatchManagers = StaticBatchManager._managers;
  20179. for (var i = 0, n = staticBatchManagers.length; i < n; i++)
  20180. staticBatchManagers[i]._clear();
  20181. var dynamicBatchManagers = DynamicBatchManager._managers;
  20182. for (var i = 0, n = dynamicBatchManagers.length; i < n; i++)
  20183. dynamicBatchManagers[i]._clear();
  20184. }
  20185. destroy(destroyChild = true) {
  20186. if (this.destroyed)
  20187. return;
  20188. super.destroy(destroyChild);
  20189. this._skyRenderer.destroy();
  20190. this._skyRenderer = null;
  20191. this._directionLights = null;
  20192. this._pointLights = null;
  20193. this._spotLights = null;
  20194. this._alternateLights = null;
  20195. this._lightmaps = null;
  20196. this._shaderValues = null;
  20197. this._renders = null;
  20198. this._cameraPool = null;
  20199. this._octree = null;
  20200. this._physicsSimulation && this._physicsSimulation._destroy();
  20201. Laya.Loader.clearRes(this.url);
  20202. }
  20203. render(ctx, x, y) {
  20204. ctx._curSubmit = Laya.SubmitBase.RENDERBASE;
  20205. this._children.length > 0 && ctx.addRenderObject(this);
  20206. }
  20207. renderSubmit() {
  20208. var gl = Laya.LayaGL.instance;
  20209. this._prepareSceneToRender();
  20210. var i, n, n1;
  20211. for (i = 0, n = this._cameraPool.length, n1 = n - 1; i < n; i++) {
  20212. if (Laya.Render.supportWebGLPlusRendering)
  20213. ShaderData.setRuntimeValueMode((i == n1) ? true : false);
  20214. var camera = this._cameraPool[i];
  20215. camera.enableRender && camera.render();
  20216. }
  20217. Laya.Context.set2DRenderConfig();
  20218. return 1;
  20219. }
  20220. getRenderType() {
  20221. return 0;
  20222. }
  20223. releaseRender() {
  20224. }
  20225. reUse(context, pos) {
  20226. return 0;
  20227. }
  20228. get customReflection() {
  20229. return this._reflection;
  20230. }
  20231. set customReflection(value) {
  20232. if (this._reflection != value) {
  20233. this._shaderValues.setTexture(Scene3D.REFLECTIONTEXTURE, value || TextureCube.blackTexture);
  20234. this._reflection = value;
  20235. }
  20236. }
  20237. get reflectionMode() {
  20238. return this._reflectionMode;
  20239. }
  20240. set reflectionMode(value) {
  20241. this._reflectionMode = value;
  20242. }
  20243. setlightmaps(value) {
  20244. var maps = this._lightmaps;
  20245. for (var i = 0, n = maps.length; i < n; i++)
  20246. maps[i].lightmapColor._removeReference();
  20247. if (value) {
  20248. var count = value.length;
  20249. maps.length = count;
  20250. for (i = 0; i < count; i++) {
  20251. var lightMap = value[i];
  20252. lightMap._addReference();
  20253. (maps[i]) || (maps[i] = new Lightmap());
  20254. maps[i].lightmapColor = lightMap;
  20255. }
  20256. }
  20257. else {
  20258. throw new Error("Scene3D: value value can't be null.");
  20259. }
  20260. }
  20261. getlightmaps() {
  20262. var lightmapColors = new Array(this._lightmaps.length);
  20263. for (var i = 0; i < this._lightmaps.length; i++) {
  20264. lightmapColors[i] = this._lightmaps[i].lightmapColor;
  20265. }
  20266. return lightmapColors;
  20267. }
  20268. }
  20269. Scene3D._shadowCasterPass = new ShadowCasterPass();
  20270. Scene3D.HIERARCHY = "HIERARCHY";
  20271. Scene3D.octreeCulling = false;
  20272. Scene3D.octreeInitialSize = 64.0;
  20273. Scene3D.octreeInitialCenter = new Vector3(0, 0, 0);
  20274. Scene3D.octreeMinNodeSize = 2.0;
  20275. Scene3D.octreeLooseness = 1.25;
  20276. Scene3D.REFLECTIONMODE_SKYBOX = 0;
  20277. Scene3D.REFLECTIONMODE_CUSTOM = 1;
  20278. Scene3D.FOGCOLOR = Shader3D.propertyNameToID("u_FogColor");
  20279. Scene3D.FOGSTART = Shader3D.propertyNameToID("u_FogStart");
  20280. Scene3D.FOGRANGE = Shader3D.propertyNameToID("u_FogRange");
  20281. Scene3D.DIRECTIONLIGHTCOUNT = Shader3D.propertyNameToID("u_DirationLightCount");
  20282. Scene3D.LIGHTBUFFER = Shader3D.propertyNameToID("u_LightBuffer");
  20283. Scene3D.CLUSTERBUFFER = Shader3D.propertyNameToID("u_LightClusterBuffer");
  20284. Scene3D.SUNLIGHTDIRECTION = Shader3D.propertyNameToID("u_SunLight.direction");
  20285. Scene3D.SUNLIGHTDIRCOLOR = Shader3D.propertyNameToID("u_SunLight.color");
  20286. Scene3D.AMBIENTSHAR = Shader3D.propertyNameToID("u_AmbientSHAr");
  20287. Scene3D.AMBIENTSHAG = Shader3D.propertyNameToID("u_AmbientSHAg");
  20288. Scene3D.AMBIENTSHAB = Shader3D.propertyNameToID("u_AmbientSHAb");
  20289. Scene3D.AMBIENTSHBR = Shader3D.propertyNameToID("u_AmbientSHBr");
  20290. Scene3D.AMBIENTSHBG = Shader3D.propertyNameToID("u_AmbientSHBg");
  20291. Scene3D.AMBIENTSHBB = Shader3D.propertyNameToID("u_AmbientSHBb");
  20292. Scene3D.AMBIENTSHC = Shader3D.propertyNameToID("u_AmbientSHC");
  20293. Scene3D.REFLECTIONPROBE = Shader3D.propertyNameToID("u_ReflectionProbe");
  20294. Scene3D.REFLECTIONCUBE_HDR_PARAMS = Shader3D.propertyNameToID("u_ReflectCubeHDRParams");
  20295. Scene3D.LIGHTDIRECTION = Shader3D.propertyNameToID("u_DirectionLight.direction");
  20296. Scene3D.LIGHTDIRCOLOR = Shader3D.propertyNameToID("u_DirectionLight.color");
  20297. Scene3D.POINTLIGHTPOS = Shader3D.propertyNameToID("u_PointLight.position");
  20298. Scene3D.POINTLIGHTRANGE = Shader3D.propertyNameToID("u_PointLight.range");
  20299. Scene3D.POINTLIGHTATTENUATION = Shader3D.propertyNameToID("u_PointLight.attenuation");
  20300. Scene3D.POINTLIGHTCOLOR = Shader3D.propertyNameToID("u_PointLight.color");
  20301. Scene3D.SPOTLIGHTPOS = Shader3D.propertyNameToID("u_SpotLight.position");
  20302. Scene3D.SPOTLIGHTDIRECTION = Shader3D.propertyNameToID("u_SpotLight.direction");
  20303. Scene3D.SPOTLIGHTSPOTANGLE = Shader3D.propertyNameToID("u_SpotLight.spot");
  20304. Scene3D.SPOTLIGHTRANGE = Shader3D.propertyNameToID("u_SpotLight.range");
  20305. Scene3D.SPOTLIGHTCOLOR = Shader3D.propertyNameToID("u_SpotLight.color");
  20306. Scene3D.AMBIENTCOLOR = Shader3D.propertyNameToID("u_AmbientColor");
  20307. Scene3D.REFLECTIONTEXTURE = Shader3D.propertyNameToID("u_ReflectTexture");
  20308. Scene3D.TIME = Shader3D.propertyNameToID("u_Time");
  20309. Scene3D._configDefineValues = new DefineDatas();
  20310. class ShaderPass extends Laya.ShaderCompile {
  20311. constructor(owner, vs, ps, stateMap) {
  20312. super(vs, ps, null);
  20313. this._cacheSharders = {};
  20314. this._cacheShaderHierarchy = 1;
  20315. this._renderState = new RenderState();
  20316. this._validDefine = new DefineDatas();
  20317. this._tags = {};
  20318. this._owner = owner;
  20319. this._stateMap = stateMap;
  20320. for (var k in this.defs)
  20321. this._validDefine.add(Shader3D.getDefineByName(k));
  20322. }
  20323. get renderState() {
  20324. return this._renderState;
  20325. }
  20326. _compileToTree(parent, lines, start, includefiles, defs) {
  20327. var node, preNode;
  20328. var text, name, fname;
  20329. var ofs, words, noUseNode;
  20330. var i, n, j;
  20331. for (i = start; i < lines.length; i++) {
  20332. text = lines[i];
  20333. if (text.length < 1)
  20334. continue;
  20335. ofs = text.indexOf("//");
  20336. if (ofs === 0)
  20337. continue;
  20338. if (ofs >= 0)
  20339. text = text.substr(0, ofs);
  20340. node = noUseNode || new Laya.ShaderNode(includefiles);
  20341. noUseNode = null;
  20342. node.text = text;
  20343. if ((ofs = text.indexOf("#")) >= 0) {
  20344. name = "#";
  20345. for (j = ofs + 1, n = text.length; j < n; j++) {
  20346. var c = text.charAt(j);
  20347. if (c === ' ' || c === '\t' || c === '?')
  20348. break;
  20349. name += c;
  20350. }
  20351. node.name = name;
  20352. switch (name) {
  20353. case "#ifdef":
  20354. case "#ifndef":
  20355. node.setParent(parent);
  20356. parent = node;
  20357. if (defs) {
  20358. words = text.substr(j).split(Laya.ShaderCompile._splitToWordExps3);
  20359. for (j = 0; j < words.length; j++) {
  20360. text = words[j];
  20361. text.length && (defs[text] = true);
  20362. }
  20363. }
  20364. continue;
  20365. case "#if":
  20366. case "#elif":
  20367. node.setParent(parent);
  20368. parent = node;
  20369. if (defs) {
  20370. words = text.substr(j).split(Laya.ShaderCompile._splitToWordExps3);
  20371. for (j = 0; j < words.length; j++) {
  20372. text = words[j];
  20373. text.length && text != "defined" && (defs[text] = true);
  20374. }
  20375. }
  20376. continue;
  20377. case "#else":
  20378. parent = parent.parent;
  20379. preNode = parent.childs[parent.childs.length - 1];
  20380. node.setParent(parent);
  20381. parent = node;
  20382. continue;
  20383. case "#endif":
  20384. parent = parent.parent;
  20385. preNode = parent.childs[parent.childs.length - 1];
  20386. node.setParent(parent);
  20387. continue;
  20388. case "#include":
  20389. words = Laya.ShaderCompile.splitToWords(text, null);
  20390. var inlcudeFile = Laya.ShaderCompile.includes[words[1]];
  20391. if (!inlcudeFile) {
  20392. throw "ShaderCompile error no this include file:" + words[1];
  20393. }
  20394. if ((ofs = words[0].indexOf("?")) < 0) {
  20395. node.setParent(parent);
  20396. text = inlcudeFile.getWith(words[2] == 'with' ? words[3] : null);
  20397. this._compileToTree(node, text.split('\n'), 0, includefiles, defs);
  20398. node.text = "";
  20399. continue;
  20400. }
  20401. node.setCondition(words[0].substr(ofs + 1), Laya.ShaderCompile.IFDEF_YES);
  20402. node.text = inlcudeFile.getWith(words[2] == 'with' ? words[3] : null);
  20403. break;
  20404. case "#import":
  20405. words = Laya.ShaderCompile.splitToWords(text, null);
  20406. fname = words[1];
  20407. includefiles.push({ node: node, file: Laya.ShaderCompile.includes[fname], ofs: node.text.length });
  20408. continue;
  20409. }
  20410. }
  20411. else {
  20412. preNode = parent.childs[parent.childs.length - 1];
  20413. if (preNode && !preNode.name) {
  20414. includefiles.length > 0 && Laya.ShaderCompile.splitToWords(text, preNode);
  20415. noUseNode = node;
  20416. preNode.text += "\n" + text;
  20417. continue;
  20418. }
  20419. includefiles.length > 0 && Laya.ShaderCompile.splitToWords(text, node);
  20420. }
  20421. node.setParent(parent);
  20422. }
  20423. }
  20424. _resizeCacheShaderMap(cacheMap, hierarchy, resizeLength) {
  20425. var end = this._cacheShaderHierarchy - 1;
  20426. if (hierarchy == end) {
  20427. for (var k in cacheMap) {
  20428. var shader = cacheMap[k];
  20429. for (var i = 0, n = resizeLength - end; i < n; i++) {
  20430. if (i == n - 1)
  20431. cacheMap[0] = shader;
  20432. else
  20433. cacheMap = cacheMap[i == 0 ? k : 0] = {};
  20434. }
  20435. }
  20436. this._cacheShaderHierarchy = resizeLength;
  20437. }
  20438. else {
  20439. for (var k in cacheMap)
  20440. this._resizeCacheShaderMap(cacheMap[k], ++hierarchy, resizeLength);
  20441. }
  20442. }
  20443. _addDebugShaderVariantCollection(compileDefine, outDebugDefines, outDebugDefineMask) {
  20444. var dbugShaderVariantInfo = Shader3D._debugShaderVariantInfo;
  20445. var debugSubShader = this._owner;
  20446. var debugShader = debugSubShader._owner;
  20447. var mask = compileDefine._mask;
  20448. Shader3D._getNamesByDefineData(compileDefine, outDebugDefines);
  20449. outDebugDefineMask.length = mask.length;
  20450. for (var i = 0, n = mask.length; i < n; i++)
  20451. outDebugDefineMask[i] = mask[i];
  20452. if (dbugShaderVariantInfo)
  20453. dbugShaderVariantInfo.setValue(debugShader, debugShader._subShaders.indexOf(debugSubShader), debugSubShader._passes.indexOf(this), outDebugDefines);
  20454. else
  20455. Shader3D._debugShaderVariantInfo = dbugShaderVariantInfo = new ShaderVariant(debugShader, debugShader._subShaders.indexOf(debugSubShader), debugSubShader._passes.indexOf(this), outDebugDefines);
  20456. Shader3D.debugShaderVariantCollection.add(dbugShaderVariantInfo);
  20457. }
  20458. withCompile(compileDefine) {
  20459. var debugDefineString = ShaderPass._debugDefineString;
  20460. var debugDefineMask = ShaderPass._debugDefineMask;
  20461. var debugMaskLength;
  20462. compileDefine._intersectionDefineDatas(this._validDefine);
  20463. if (Shader3D.debugMode) {
  20464. debugMaskLength = compileDefine._length;
  20465. this._addDebugShaderVariantCollection(compileDefine, debugDefineString, debugDefineMask);
  20466. }
  20467. compileDefine.addDefineDatas(Scene3D._configDefineValues);
  20468. var cacheShaders = this._cacheSharders;
  20469. var maskLength = compileDefine._length;
  20470. if (maskLength > this._cacheShaderHierarchy) {
  20471. this._resizeCacheShaderMap(cacheShaders, 0, maskLength);
  20472. this._cacheShaderHierarchy = maskLength;
  20473. }
  20474. var mask = compileDefine._mask;
  20475. var endIndex = compileDefine._length - 1;
  20476. var maxEndIndex = this._cacheShaderHierarchy - 1;
  20477. for (var i = 0; i < maxEndIndex; i++) {
  20478. var subMask = endIndex < i ? 0 : mask[i];
  20479. var subCacheShaders = cacheShaders[subMask];
  20480. (subCacheShaders) || (cacheShaders[subMask] = subCacheShaders = {});
  20481. cacheShaders = subCacheShaders;
  20482. }
  20483. var cacheKey = endIndex < maxEndIndex ? 0 : mask[maxEndIndex];
  20484. var shader = cacheShaders[cacheKey];
  20485. if (shader)
  20486. return shader;
  20487. var defineString = ShaderPass._defineString;
  20488. Shader3D._getNamesByDefineData(compileDefine, defineString);
  20489. var config = Config3D._config;
  20490. var clusterSlices = config.lightClusterCount;
  20491. var defMap = {};
  20492. var vertexHead;
  20493. var fragmentHead;
  20494. var defineStr = "";
  20495. if (Laya.WebGL._isWebGL2) {
  20496. vertexHead =
  20497. `#version 300 es\n
  20498. #define attribute in
  20499. #define varying out
  20500. #define texture2D texture\n`;
  20501. fragmentHead =
  20502. `#version 300 es\n
  20503. #define varying in
  20504. out highp vec4 pc_fragColor;
  20505. #define gl_FragColor pc_fragColor
  20506. #define gl_FragDepthEXT gl_FragDepth
  20507. #define texture2D texture
  20508. #define textureCube texture
  20509. #define texture2DProj textureProj
  20510. #define texture2DLodEXT textureLod
  20511. #define texture2DProjLodEXT textureProjLod
  20512. #define textureCubeLodEXT textureLod
  20513. #define texture2DGradEXT textureGrad
  20514. #define texture2DProjGradEXT textureProjGrad
  20515. #define textureCubeGradEXT textureGrad\n`;
  20516. }
  20517. else {
  20518. vertexHead = "";
  20519. fragmentHead =
  20520. `#ifdef GL_EXT_shader_texture_lod
  20521. #extension GL_EXT_shader_texture_lod : enable
  20522. #endif
  20523. #if !defined(GL_EXT_shader_texture_lod)
  20524. #define texture1DLodEXT texture1D
  20525. #define texture2DLodEXT texture2D
  20526. #define texture2DProjLodEXT texture2DProj
  20527. #define texture3DLodEXT texture3D
  20528. #define textureCubeLodEXT textureCube
  20529. #endif\n`;
  20530. }
  20531. defineStr += "#define MAX_LIGHT_COUNT " + config.maxLightCount + "\n";
  20532. defineStr += "#define MAX_LIGHT_COUNT_PER_CLUSTER " + config._maxAreaLightCountPerClusterAverage + "\n";
  20533. defineStr += "#define CLUSTER_X_COUNT " + clusterSlices.x + "\n";
  20534. defineStr += "#define CLUSTER_Y_COUNT " + clusterSlices.y + "\n";
  20535. defineStr += "#define CLUSTER_Z_COUNT " + clusterSlices.z + "\n";
  20536. defineStr += "#define SHADER_CAPAILITY_LEVEL " + Laya.SystemUtils._shaderCapailityLevel + "\n";
  20537. for (var i = 0, n = defineString.length; i < n; i++) {
  20538. var def = defineString[i];
  20539. defineStr += "#define " + def + "\n";
  20540. defMap[def] = true;
  20541. }
  20542. var vs = this._VS.toscript(defMap, []);
  20543. var vsVersion = '';
  20544. if (vs[0].indexOf('#version') == 0) {
  20545. vsVersion = vs[0] + '\n';
  20546. vs.shift();
  20547. }
  20548. var ps = this._PS.toscript(defMap, []);
  20549. var psVersion = '';
  20550. if (ps[0].indexOf('#version') == 0) {
  20551. psVersion = ps[0] + '\n';
  20552. ps.shift();
  20553. }
  20554. shader = new ShaderInstance(vsVersion + vertexHead + defineStr + vs.join('\n'), psVersion + fragmentHead + defineStr + ps.join('\n'), this._owner._attributeMap || this._owner._owner._attributeMap, this._owner._uniformMap || this._owner._owner._uniformMap, this);
  20555. cacheShaders[cacheKey] = shader;
  20556. if (Shader3D.debugMode) {
  20557. var defStr = "";
  20558. var defMask = "";
  20559. for (var i = 0, n = debugMaskLength; i < n; i++)
  20560. (i == n - 1) ? defMask += debugDefineMask[i] : defMask += debugDefineMask[i] + ",";
  20561. for (var i = 0, n = debugDefineString.length; i < n; i++)
  20562. (i == n - 1) ? defStr += debugDefineString[i] : defStr += debugDefineString[i] + ",";
  20563. 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");
  20564. }
  20565. return shader;
  20566. }
  20567. setTag(key, value) {
  20568. if (value)
  20569. this._tags[key] = value;
  20570. else
  20571. delete this._tags[key];
  20572. }
  20573. getTag(key) {
  20574. return this._tags[key];
  20575. }
  20576. }
  20577. ShaderPass._defineString = [];
  20578. ShaderPass._debugDefineString = [];
  20579. ShaderPass._debugDefineMask = [];
  20580. class SubShader {
  20581. constructor(attributeMap, uniformMap) {
  20582. this._flags = {};
  20583. this._passes = [];
  20584. this._attributeMap = attributeMap;
  20585. this._uniformMap = uniformMap;
  20586. }
  20587. setFlag(key, value) {
  20588. if (value)
  20589. this._flags[key] = value;
  20590. else
  20591. delete this._flags[key];
  20592. }
  20593. getFlag(key) {
  20594. return this._flags[key];
  20595. }
  20596. addShaderPass(vs, ps, stateMap = null, pipelineMode = "Forward") {
  20597. var shaderPass = new ShaderPass(this, vs, ps, stateMap);
  20598. shaderPass._pipelineMode = pipelineMode;
  20599. this._passes.push(shaderPass);
  20600. return shaderPass;
  20601. }
  20602. }
  20603. (function (PBRSpecularSmoothnessSource) {
  20604. PBRSpecularSmoothnessSource[PBRSpecularSmoothnessSource["SpecularTextureAlpha"] = 0] = "SpecularTextureAlpha";
  20605. PBRSpecularSmoothnessSource[PBRSpecularSmoothnessSource["AlbedoTextureAlpha"] = 1] = "AlbedoTextureAlpha";
  20606. })(exports.PBRSpecularSmoothnessSource || (exports.PBRSpecularSmoothnessSource = {}));
  20607. class PBRSpecularMaterial extends PBRMaterial {
  20608. constructor() {
  20609. super();
  20610. this.setShaderName("PBRSpecular");
  20611. this._shaderValues.setVector(PBRSpecularMaterial.SPECULARCOLOR, new Vector4(0.2, 0.2, 0.2, 1.0));
  20612. }
  20613. static __init__() {
  20614. PBRSpecularMaterial.SHADERDEFINE_SPECULARGLOSSTEXTURE = Shader3D.getDefineByName("SPECULARGLOSSTEXTURE");
  20615. PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA = Shader3D.getDefineByName("SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA");
  20616. var attributeMap = {
  20617. 'a_Position': VertexMesh.MESH_POSITION0,
  20618. 'a_Normal': VertexMesh.MESH_NORMAL0,
  20619. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  20620. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  20621. 'a_Texcoord1': VertexMesh.MESH_TEXTURECOORDINATE1,
  20622. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  20623. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  20624. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  20625. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  20626. };
  20627. var uniformMap = {
  20628. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  20629. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  20630. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  20631. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  20632. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  20633. 'u_LightMapDirection': Shader3D.PERIOD_SPRITE,
  20634. 'u_SimpleAnimatorTexture': Shader3D.PERIOD_SPRITE,
  20635. 'u_SimpleAnimatorParams': Shader3D.PERIOD_SPRITE,
  20636. 'u_SimpleAnimatorTextureSize': Shader3D.PERIOD_SPRITE,
  20637. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  20638. 'u_View': Shader3D.PERIOD_CAMERA,
  20639. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  20640. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  20641. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  20642. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  20643. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  20644. 'u_EmissionColor': Shader3D.PERIOD_MATERIAL,
  20645. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  20646. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  20647. 'u_ParallaxTexture': Shader3D.PERIOD_MATERIAL,
  20648. 'u_OcclusionTexture': Shader3D.PERIOD_MATERIAL,
  20649. 'u_EmissionTexture': Shader3D.PERIOD_MATERIAL,
  20650. 'u_Smoothness': Shader3D.PERIOD_MATERIAL,
  20651. 'u_SmoothnessScale': Shader3D.PERIOD_MATERIAL,
  20652. 'u_occlusionStrength': Shader3D.PERIOD_MATERIAL,
  20653. 'u_NormalScale': Shader3D.PERIOD_MATERIAL,
  20654. 'u_ParallaxScale': Shader3D.PERIOD_MATERIAL,
  20655. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  20656. 'u_SpecGlossTexture': Shader3D.PERIOD_MATERIAL,
  20657. 'u_SpecularColor': Shader3D.PERIOD_MATERIAL,
  20658. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  20659. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  20660. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  20661. 'u_FogStart': Shader3D.PERIOD_SCENE,
  20662. 'u_FogRange': Shader3D.PERIOD_SCENE,
  20663. 'u_FogColor': Shader3D.PERIOD_SCENE,
  20664. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  20665. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  20666. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  20667. 'u_ShadowBias': Shader3D.PERIOD_SCENE,
  20668. 'u_ShadowLightDirection': Shader3D.PERIOD_SCENE,
  20669. 'u_ShadowMap': Shader3D.PERIOD_SCENE,
  20670. 'u_ShadowParams': Shader3D.PERIOD_SCENE,
  20671. 'u_ShadowSplitSpheres': Shader3D.PERIOD_SCENE,
  20672. 'u_ShadowMatrices': Shader3D.PERIOD_SCENE,
  20673. 'u_ShadowMapSize': Shader3D.PERIOD_SCENE,
  20674. 'u_SpotShadowMap': Shader3D.PERIOD_SCENE,
  20675. 'u_SpotViewProjectMatrix': Shader3D.PERIOD_SCENE,
  20676. 'u_ShadowLightPosition': Shader3D.PERIOD_SCENE,
  20677. 'u_AmbientSHAr': Shader3D.PERIOD_SCENE,
  20678. 'u_AmbientSHAg': Shader3D.PERIOD_SCENE,
  20679. 'u_AmbientSHAb': Shader3D.PERIOD_SCENE,
  20680. 'u_AmbientSHBr': Shader3D.PERIOD_SCENE,
  20681. 'u_AmbientSHBg': Shader3D.PERIOD_SCENE,
  20682. 'u_AmbientSHBb': Shader3D.PERIOD_SCENE,
  20683. 'u_AmbientSHC': Shader3D.PERIOD_SCENE,
  20684. 'u_ReflectionProbe': Shader3D.PERIOD_SCENE,
  20685. 'u_ReflectCubeHDRParams': Shader3D.PERIOD_SCENE,
  20686. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  20687. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  20688. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  20689. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  20690. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  20691. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  20692. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  20693. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  20694. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  20695. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  20696. };
  20697. var stateMap = {
  20698. 's_Cull': Shader3D.RENDER_STATE_CULL,
  20699. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  20700. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  20701. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  20702. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  20703. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  20704. };
  20705. var shader = Shader3D.add("PBRSpecular", attributeMap, uniformMap, true);
  20706. var subShader = new SubShader(attributeMap, uniformMap);
  20707. shader.addSubShader(subShader);
  20708. subShader.addShaderPass(PBRVS, PBRPS, stateMap, "Forward");
  20709. subShader.addShaderPass(PBRShadowCasterVS, PBRShadowCasterPS, stateMap, "ShadowCaster");
  20710. }
  20711. get specularTexture() {
  20712. return this._shaderValues.getTexture(PBRSpecularMaterial.SPECULARTEXTURE);
  20713. }
  20714. set specularTexture(value) {
  20715. if (value)
  20716. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_SPECULARGLOSSTEXTURE);
  20717. else
  20718. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_SPECULARGLOSSTEXTURE);
  20719. this._shaderValues.setTexture(PBRSpecularMaterial.SPECULARTEXTURE, value);
  20720. }
  20721. get specularColor() {
  20722. return this._shaderValues.getVector(PBRSpecularMaterial.SPECULARCOLOR);
  20723. }
  20724. set specularColor(value) {
  20725. this._shaderValues.setVector(PBRSpecularMaterial.SPECULARCOLOR, value);
  20726. }
  20727. clone() {
  20728. var dest = new PBRSpecularMaterial();
  20729. this.cloneTo(dest);
  20730. return dest;
  20731. }
  20732. }
  20733. PBRSpecularMaterial.SPECULARTEXTURE = Shader3D.propertyNameToID("u_SpecGlossTexture");
  20734. PBRSpecularMaterial.SPECULARCOLOR = Shader3D.propertyNameToID("u_SpecularColor");
  20735. var PBRPS$1 = "#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#include \"Shadow.glsl\"\r\n#include \"PBRFSInput.glsl\";\r\n#include \"LayaPBRBRDF.glsl\";\r\n#include \"GlobalIllumination.glsl\";\r\n#include \"PBRCore.glsl\";\r\n\r\nvoid main()\r\n{\r\n\tfragmentForward();\r\n}";
  20736. var PBRVS$1 = "#include \"Lighting.glsl\";\r\n#include \"Shadow.glsl\"\r\n#include \"PBRVSInput.glsl\";\r\n#include \"PBRVertex.glsl\";\r\n\r\nvoid main()\r\n{\r\n\tvertexForward();\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  20737. var PBRShadowCasterPS$1 = "#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 \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
  20738. var PBRShadowCasterVS$1 = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS = shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
  20739. (function (PBRMetallicSmoothnessSource) {
  20740. PBRMetallicSmoothnessSource[PBRMetallicSmoothnessSource["MetallicGlossTextureAlpha"] = 0] = "MetallicGlossTextureAlpha";
  20741. PBRMetallicSmoothnessSource[PBRMetallicSmoothnessSource["AlbedoTextureAlpha"] = 1] = "AlbedoTextureAlpha";
  20742. })(exports.PBRMetallicSmoothnessSource || (exports.PBRMetallicSmoothnessSource = {}));
  20743. class PBRStandardMaterial extends PBRMaterial {
  20744. constructor() {
  20745. super();
  20746. this._smoothnessSource = 0;
  20747. this.setShaderName("PBR");
  20748. this._shaderValues.setNumber(PBRStandardMaterial.METALLIC, 0.0);
  20749. }
  20750. static __init__() {
  20751. PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE = Shader3D.getDefineByName("METALLICGLOSSTEXTURE");
  20752. PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA = Shader3D.getDefineByName("SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA");
  20753. var attributeMap = {
  20754. 'a_Position': VertexMesh.MESH_POSITION0,
  20755. 'a_Normal': VertexMesh.MESH_NORMAL0,
  20756. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  20757. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  20758. 'a_Texcoord1': VertexMesh.MESH_TEXTURECOORDINATE1,
  20759. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  20760. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  20761. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  20762. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  20763. };
  20764. var uniformMap = {
  20765. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  20766. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  20767. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  20768. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  20769. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  20770. 'u_LightMapDirection': Shader3D.PERIOD_SPRITE,
  20771. 'u_SimpleAnimatorTexture': Shader3D.PERIOD_SPRITE,
  20772. 'u_SimpleAnimatorParams': Shader3D.PERIOD_SPRITE,
  20773. 'u_SimpleAnimatorTextureSize': Shader3D.PERIOD_SPRITE,
  20774. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  20775. 'u_View': Shader3D.PERIOD_CAMERA,
  20776. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  20777. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  20778. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  20779. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  20780. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  20781. 'u_EmissionColor': Shader3D.PERIOD_MATERIAL,
  20782. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  20783. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  20784. 'u_ParallaxTexture': Shader3D.PERIOD_MATERIAL,
  20785. 'u_OcclusionTexture': Shader3D.PERIOD_MATERIAL,
  20786. 'u_EmissionTexture': Shader3D.PERIOD_MATERIAL,
  20787. 'u_Smoothness': Shader3D.PERIOD_MATERIAL,
  20788. 'u_SmoothnessScale': Shader3D.PERIOD_MATERIAL,
  20789. 'u_occlusionStrength': Shader3D.PERIOD_MATERIAL,
  20790. 'u_NormalScale': Shader3D.PERIOD_MATERIAL,
  20791. 'u_ParallaxScale': Shader3D.PERIOD_MATERIAL,
  20792. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  20793. 'u_MetallicGlossTexture': Shader3D.PERIOD_MATERIAL,
  20794. 'u_Metallic': Shader3D.PERIOD_MATERIAL,
  20795. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  20796. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  20797. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  20798. 'u_FogStart': Shader3D.PERIOD_SCENE,
  20799. 'u_FogRange': Shader3D.PERIOD_SCENE,
  20800. 'u_FogColor': Shader3D.PERIOD_SCENE,
  20801. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  20802. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  20803. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  20804. 'u_ShadowBias': Shader3D.PERIOD_SCENE,
  20805. 'u_ShadowLightDirection': Shader3D.PERIOD_SCENE,
  20806. 'u_ShadowMap': Shader3D.PERIOD_SCENE,
  20807. 'u_ShadowParams': Shader3D.PERIOD_SCENE,
  20808. 'u_ShadowSplitSpheres': Shader3D.PERIOD_SCENE,
  20809. 'u_ShadowMatrices': Shader3D.PERIOD_SCENE,
  20810. 'u_ShadowMapSize': Shader3D.PERIOD_SCENE,
  20811. 'u_SpotShadowMap': Shader3D.PERIOD_SCENE,
  20812. 'u_SpotViewProjectMatrix': Shader3D.PERIOD_SCENE,
  20813. 'u_ShadowLightPosition': Shader3D.PERIOD_SCENE,
  20814. 'u_AmbientSHAr': Shader3D.PERIOD_SCENE,
  20815. 'u_AmbientSHAg': Shader3D.PERIOD_SCENE,
  20816. 'u_AmbientSHAb': Shader3D.PERIOD_SCENE,
  20817. 'u_AmbientSHBr': Shader3D.PERIOD_SCENE,
  20818. 'u_AmbientSHBg': Shader3D.PERIOD_SCENE,
  20819. 'u_AmbientSHBb': Shader3D.PERIOD_SCENE,
  20820. 'u_AmbientSHC': Shader3D.PERIOD_SCENE,
  20821. 'u_ReflectionProbe': Shader3D.PERIOD_SCENE,
  20822. 'u_ReflectCubeHDRParams': Shader3D.PERIOD_SCENE,
  20823. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  20824. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  20825. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  20826. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  20827. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  20828. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  20829. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  20830. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  20831. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  20832. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  20833. };
  20834. var stateMap = {
  20835. 's_Cull': Shader3D.RENDER_STATE_CULL,
  20836. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  20837. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  20838. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  20839. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  20840. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  20841. };
  20842. var shader = Shader3D.add("PBR", attributeMap, uniformMap, true);
  20843. var subShader = new SubShader(attributeMap, uniformMap);
  20844. shader.addSubShader(subShader);
  20845. subShader.addShaderPass(PBRVS$1, PBRPS$1, stateMap, "Forward");
  20846. subShader.addShaderPass(PBRShadowCasterVS$1, PBRShadowCasterPS$1, stateMap, "ShadowCaster");
  20847. }
  20848. get metallicGlossTexture() {
  20849. return this._shaderValues.getTexture(PBRStandardMaterial.METALLICGLOSSTEXTURE);
  20850. }
  20851. set metallicGlossTexture(value) {
  20852. if (value)
  20853. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE);
  20854. else
  20855. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE);
  20856. this._shaderValues.setTexture(PBRStandardMaterial.METALLICGLOSSTEXTURE, value);
  20857. }
  20858. get metallic() {
  20859. return this._shaderValues.getNumber(PBRStandardMaterial.METALLIC);
  20860. }
  20861. set metallic(value) {
  20862. this._shaderValues.setNumber(PBRStandardMaterial.METALLIC, Math.max(0.0, Math.min(1.0, value)));
  20863. }
  20864. get smoothnessSource() {
  20865. return this._smoothnessSource;
  20866. }
  20867. set smoothnessSource(value) {
  20868. if (value)
  20869. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  20870. else
  20871. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  20872. this._smoothnessSource = value;
  20873. }
  20874. clone() {
  20875. var dest = new PBRStandardMaterial();
  20876. this.cloneTo(dest);
  20877. return dest;
  20878. }
  20879. }
  20880. PBRStandardMaterial.METALLICGLOSSTEXTURE = Shader3D.propertyNameToID("u_MetallicGlossTexture");
  20881. PBRStandardMaterial.METALLIC = Shader3D.propertyNameToID("u_Metallic");
  20882. class SkyBoxMaterial extends Material {
  20883. constructor() {
  20884. super();
  20885. this.setShaderName("SkyBox");
  20886. this.tintColor = new Vector4(0.5, 0.5, 0.5, 0.5);
  20887. this.exposure = 1.0;
  20888. this.rotation = 0;
  20889. }
  20890. static __initDefine__() {
  20891. }
  20892. get tintColor() {
  20893. return this._shaderValues.getVector(SkyBoxMaterial.TINTCOLOR);
  20894. }
  20895. set tintColor(value) {
  20896. this._shaderValues.setVector(SkyBoxMaterial.TINTCOLOR, value);
  20897. }
  20898. get exposure() {
  20899. return this._shaderValues.getNumber(SkyBoxMaterial.EXPOSURE);
  20900. }
  20901. set exposure(value) {
  20902. this._shaderValues.setNumber(SkyBoxMaterial.EXPOSURE, value);
  20903. }
  20904. get rotation() {
  20905. return this._shaderValues.getNumber(SkyBoxMaterial.ROTATION);
  20906. }
  20907. set rotation(value) {
  20908. this._shaderValues.setNumber(SkyBoxMaterial.ROTATION, value);
  20909. }
  20910. get textureCube() {
  20911. return this._shaderValues.getTexture(SkyBoxMaterial.TEXTURECUBE);
  20912. }
  20913. set textureCube(value) {
  20914. this._shaderValues.setTexture(SkyBoxMaterial.TEXTURECUBE, value);
  20915. }
  20916. clone() {
  20917. var dest = new SkyBoxMaterial();
  20918. this.cloneTo(dest);
  20919. return dest;
  20920. }
  20921. }
  20922. SkyBoxMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_TintColor");
  20923. SkyBoxMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  20924. SkyBoxMaterial.ROTATION = Shader3D.propertyNameToID("u_Rotation");
  20925. SkyBoxMaterial.TEXTURECUBE = Shader3D.propertyNameToID("u_CubeTexture");
  20926. class SkyProceduralMaterial extends Material {
  20927. constructor() {
  20928. super();
  20929. this.setShaderName("SkyBoxProcedural");
  20930. this.sunDisk = SkyProceduralMaterial.SUN_HIGH_QUALITY;
  20931. this.sunSize = 0.04;
  20932. this.sunSizeConvergence = 5;
  20933. this.atmosphereThickness = 1.0;
  20934. this.skyTint = new Vector4(0.5, 0.5, 0.5, 1.0);
  20935. this.groundTint = new Vector4(0.369, 0.349, 0.341, 1.0);
  20936. this.exposure = 1.3;
  20937. }
  20938. static __initDefine__() {
  20939. SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY = Shader3D.getDefineByName("SUN_HIGH_QUALITY");
  20940. SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE = Shader3D.getDefineByName("SUN_SIMPLE");
  20941. }
  20942. get sunDisk() {
  20943. return this._sunDisk;
  20944. }
  20945. set sunDisk(value) {
  20946. switch (value) {
  20947. case SkyProceduralMaterial.SUN_HIGH_QUALITY:
  20948. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  20949. this._shaderValues.addDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  20950. break;
  20951. case SkyProceduralMaterial.SUN_SIMPLE:
  20952. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  20953. this._shaderValues.addDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  20954. break;
  20955. case SkyProceduralMaterial.SUN_NODE:
  20956. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  20957. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  20958. break;
  20959. default:
  20960. throw "SkyBoxProceduralMaterial: unknown sun value.";
  20961. }
  20962. this._sunDisk = value;
  20963. }
  20964. get sunSize() {
  20965. return this._shaderValues.getNumber(SkyProceduralMaterial.SUNSIZE);
  20966. }
  20967. set sunSize(value) {
  20968. value = Math.min(Math.max(0.0, value), 1.0);
  20969. this._shaderValues.setNumber(SkyProceduralMaterial.SUNSIZE, value);
  20970. }
  20971. get sunSizeConvergence() {
  20972. return this._shaderValues.getNumber(SkyProceduralMaterial.SUNSIZECONVERGENCE);
  20973. }
  20974. set sunSizeConvergence(value) {
  20975. value = Math.min(Math.max(0.0, value), 20.0);
  20976. this._shaderValues.setNumber(SkyProceduralMaterial.SUNSIZECONVERGENCE, value);
  20977. }
  20978. get atmosphereThickness() {
  20979. return this._shaderValues.getNumber(SkyProceduralMaterial.ATMOSPHERETHICKNESS);
  20980. }
  20981. set atmosphereThickness(value) {
  20982. value = Math.min(Math.max(0.0, value), 5.0);
  20983. this._shaderValues.setNumber(SkyProceduralMaterial.ATMOSPHERETHICKNESS, value);
  20984. }
  20985. get skyTint() {
  20986. return this._shaderValues.getVector(SkyProceduralMaterial.SKYTINT);
  20987. }
  20988. set skyTint(value) {
  20989. this._shaderValues.setVector(SkyProceduralMaterial.SKYTINT, value);
  20990. }
  20991. get groundTint() {
  20992. return this._shaderValues.getVector(SkyProceduralMaterial.GROUNDTINT);
  20993. }
  20994. set groundTint(value) {
  20995. this._shaderValues.setVector(SkyProceduralMaterial.GROUNDTINT, value);
  20996. }
  20997. get exposure() {
  20998. return this._shaderValues.getNumber(SkyProceduralMaterial.EXPOSURE);
  20999. }
  21000. set exposure(value) {
  21001. value = Math.min(Math.max(0.0, value), 8.0);
  21002. this._shaderValues.setNumber(SkyProceduralMaterial.EXPOSURE, value);
  21003. }
  21004. clone() {
  21005. var dest = new SkyProceduralMaterial();
  21006. this.cloneTo(dest);
  21007. return dest;
  21008. }
  21009. }
  21010. SkyProceduralMaterial.SUN_NODE = 0;
  21011. SkyProceduralMaterial.SUN_SIMPLE = 1;
  21012. SkyProceduralMaterial.SUN_HIGH_QUALITY = 2;
  21013. SkyProceduralMaterial.SUNSIZE = Shader3D.propertyNameToID("u_SunSize");
  21014. SkyProceduralMaterial.SUNSIZECONVERGENCE = Shader3D.propertyNameToID("u_SunSizeConvergence");
  21015. SkyProceduralMaterial.ATMOSPHERETHICKNESS = Shader3D.propertyNameToID("u_AtmosphereThickness");
  21016. SkyProceduralMaterial.SKYTINT = Shader3D.propertyNameToID("u_SkyTint");
  21017. SkyProceduralMaterial.GROUNDTINT = Shader3D.propertyNameToID("u_GroundTint");
  21018. SkyProceduralMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  21019. class UnlitMaterial extends Material {
  21020. constructor() {
  21021. super();
  21022. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  21023. this._albedoIntensity = 1.0;
  21024. this._enableVertexColor = false;
  21025. this.setShaderName("Unlit");
  21026. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  21027. this.renderMode = UnlitMaterial.RENDERMODE_OPAQUE;
  21028. }
  21029. static __initDefine__() {
  21030. UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  21031. UnlitMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  21032. UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR = Shader3D.getDefineByName("ENABLEVERTEXCOLOR");
  21033. }
  21034. get _ColorR() {
  21035. return this._albedoColor.x;
  21036. }
  21037. set _ColorR(value) {
  21038. this._albedoColor.x = value;
  21039. this.albedoColor = this._albedoColor;
  21040. }
  21041. get _ColorG() {
  21042. return this._albedoColor.y;
  21043. }
  21044. set _ColorG(value) {
  21045. this._albedoColor.y = value;
  21046. this.albedoColor = this._albedoColor;
  21047. }
  21048. get _ColorB() {
  21049. return this._albedoColor.z;
  21050. }
  21051. set _ColorB(value) {
  21052. this._albedoColor.z = value;
  21053. this.albedoColor = this._albedoColor;
  21054. }
  21055. get _ColorA() {
  21056. return this._albedoColor.w;
  21057. }
  21058. set _ColorA(value) {
  21059. this._albedoColor.w = value;
  21060. this.albedoColor = this._albedoColor;
  21061. }
  21062. get _AlbedoIntensity() {
  21063. return this._albedoIntensity;
  21064. }
  21065. set _AlbedoIntensity(value) {
  21066. if (this._albedoIntensity !== value) {
  21067. var finalAlbedo = this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  21068. Vector4.scale(this._albedoColor, value, finalAlbedo);
  21069. this._albedoIntensity = value;
  21070. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, finalAlbedo);
  21071. }
  21072. }
  21073. get _MainTex_STX() {
  21074. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).x;
  21075. }
  21076. set _MainTex_STX(x) {
  21077. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  21078. tilOff.x = x;
  21079. this.tilingOffset = tilOff;
  21080. }
  21081. get _MainTex_STY() {
  21082. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).y;
  21083. }
  21084. set _MainTex_STY(y) {
  21085. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  21086. tilOff.y = y;
  21087. this.tilingOffset = tilOff;
  21088. }
  21089. get _MainTex_STZ() {
  21090. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).z;
  21091. }
  21092. set _MainTex_STZ(z) {
  21093. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  21094. tilOff.z = z;
  21095. this.tilingOffset = tilOff;
  21096. }
  21097. get _MainTex_STW() {
  21098. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).w;
  21099. }
  21100. set _MainTex_STW(w) {
  21101. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  21102. tilOff.w = w;
  21103. this.tilingOffset = tilOff;
  21104. }
  21105. get _Cutoff() {
  21106. return this.alphaTestValue;
  21107. }
  21108. set _Cutoff(value) {
  21109. this.alphaTestValue = value;
  21110. }
  21111. get albedoColorR() {
  21112. return this._ColorR;
  21113. }
  21114. set albedoColorR(value) {
  21115. this._ColorR = value;
  21116. }
  21117. get albedoColorG() {
  21118. return this._ColorG;
  21119. }
  21120. set albedoColorG(value) {
  21121. this._ColorG = value;
  21122. }
  21123. get albedoColorB() {
  21124. return this._ColorB;
  21125. }
  21126. set albedoColorB(value) {
  21127. this._ColorB = value;
  21128. }
  21129. get albedoColorA() {
  21130. return this._ColorA;
  21131. }
  21132. set albedoColorA(value) {
  21133. this._ColorA = value;
  21134. }
  21135. get albedoColor() {
  21136. return this._albedoColor;
  21137. }
  21138. set albedoColor(value) {
  21139. var finalAlbedo = this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  21140. Vector4.scale(value, this._albedoIntensity, finalAlbedo);
  21141. this._albedoColor = value;
  21142. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, finalAlbedo);
  21143. }
  21144. get albedoIntensity() {
  21145. return this._albedoIntensity;
  21146. }
  21147. set albedoIntensity(value) {
  21148. this._AlbedoIntensity = value;
  21149. }
  21150. get albedoTexture() {
  21151. return this._shaderValues.getTexture(UnlitMaterial.ALBEDOTEXTURE);
  21152. }
  21153. set albedoTexture(value) {
  21154. if (value)
  21155. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  21156. else
  21157. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  21158. this._shaderValues.setTexture(UnlitMaterial.ALBEDOTEXTURE, value);
  21159. }
  21160. get tilingOffsetX() {
  21161. return this._MainTex_STX;
  21162. }
  21163. set tilingOffsetX(x) {
  21164. this._MainTex_STX = x;
  21165. }
  21166. get tilingOffsetY() {
  21167. return this._MainTex_STY;
  21168. }
  21169. set tilingOffsetY(y) {
  21170. this._MainTex_STY = y;
  21171. }
  21172. get tilingOffsetZ() {
  21173. return this._MainTex_STZ;
  21174. }
  21175. set tilingOffsetZ(z) {
  21176. this._MainTex_STZ = z;
  21177. }
  21178. get tilingOffsetW() {
  21179. return this._MainTex_STW;
  21180. }
  21181. set tilingOffsetW(w) {
  21182. this._MainTex_STW = w;
  21183. }
  21184. get tilingOffset() {
  21185. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  21186. }
  21187. set tilingOffset(value) {
  21188. if (value) {
  21189. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  21190. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  21191. else
  21192. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  21193. }
  21194. else {
  21195. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  21196. }
  21197. this._shaderValues.setVector(UnlitMaterial.TILINGOFFSET, value);
  21198. }
  21199. get enableVertexColor() {
  21200. return this._enableVertexColor;
  21201. }
  21202. set enableVertexColor(value) {
  21203. this._enableVertexColor = value;
  21204. if (value)
  21205. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  21206. else
  21207. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  21208. }
  21209. set renderMode(value) {
  21210. switch (value) {
  21211. case UnlitMaterial.RENDERMODE_OPAQUE:
  21212. this.alphaTest = false;
  21213. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  21214. this.depthWrite = true;
  21215. this.cull = RenderState.CULL_BACK;
  21216. this.blend = RenderState.BLEND_DISABLE;
  21217. this.depthTest = RenderState.DEPTHTEST_LESS;
  21218. break;
  21219. case UnlitMaterial.RENDERMODE_CUTOUT:
  21220. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  21221. this.alphaTest = true;
  21222. this.depthWrite = true;
  21223. this.cull = RenderState.CULL_BACK;
  21224. this.blend = RenderState.BLEND_DISABLE;
  21225. this.depthTest = RenderState.DEPTHTEST_LESS;
  21226. break;
  21227. case UnlitMaterial.RENDERMODE_TRANSPARENT:
  21228. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  21229. this.alphaTest = false;
  21230. this.depthWrite = false;
  21231. this.cull = RenderState.CULL_BACK;
  21232. this.blend = RenderState.BLEND_ENABLE_ALL;
  21233. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  21234. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  21235. this.depthTest = RenderState.DEPTHTEST_LESS;
  21236. break;
  21237. default:
  21238. throw new Error("UnlitMaterial : renderMode value error.");
  21239. }
  21240. }
  21241. get depthWrite() {
  21242. return this._shaderValues.getBool(UnlitMaterial.DEPTH_WRITE);
  21243. }
  21244. set depthWrite(value) {
  21245. this._shaderValues.setBool(UnlitMaterial.DEPTH_WRITE, value);
  21246. }
  21247. get cull() {
  21248. return this._shaderValues.getInt(UnlitMaterial.CULL);
  21249. }
  21250. set cull(value) {
  21251. this._shaderValues.setInt(UnlitMaterial.CULL, value);
  21252. }
  21253. get blend() {
  21254. return this._shaderValues.getInt(UnlitMaterial.BLEND);
  21255. }
  21256. set blend(value) {
  21257. this._shaderValues.setInt(UnlitMaterial.BLEND, value);
  21258. }
  21259. get blendSrc() {
  21260. return this._shaderValues.getInt(UnlitMaterial.BLEND_SRC);
  21261. }
  21262. set blendSrc(value) {
  21263. this._shaderValues.setInt(UnlitMaterial.BLEND_SRC, value);
  21264. }
  21265. get blendDst() {
  21266. return this._shaderValues.getInt(UnlitMaterial.BLEND_DST);
  21267. }
  21268. set blendDst(value) {
  21269. this._shaderValues.setInt(UnlitMaterial.BLEND_DST, value);
  21270. }
  21271. get depthTest() {
  21272. return this._shaderValues.getInt(UnlitMaterial.DEPTH_TEST);
  21273. }
  21274. set depthTest(value) {
  21275. this._shaderValues.setInt(UnlitMaterial.DEPTH_TEST, value);
  21276. }
  21277. clone() {
  21278. var dest = new UnlitMaterial();
  21279. this.cloneTo(dest);
  21280. return dest;
  21281. }
  21282. }
  21283. UnlitMaterial.RENDERMODE_OPAQUE = 0;
  21284. UnlitMaterial.RENDERMODE_CUTOUT = 1;
  21285. UnlitMaterial.RENDERMODE_TRANSPARENT = 2;
  21286. UnlitMaterial.RENDERMODE_ADDTIVE = 3;
  21287. UnlitMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  21288. UnlitMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  21289. UnlitMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  21290. UnlitMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  21291. UnlitMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  21292. UnlitMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  21293. UnlitMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  21294. UnlitMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  21295. UnlitMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  21296. class WaterPrimaryMaterial extends Material {
  21297. constructor() {
  21298. super();
  21299. this.setShaderName("WaterPrimary");
  21300. this._shaderValues.setVector(WaterPrimaryMaterial.HORIZONCOLOR, new Vector4(0.172, 0.463, 0.435, 0));
  21301. this._shaderValues.setNumber(WaterPrimaryMaterial.WAVESCALE, 0.15);
  21302. this._shaderValues.setVector(WaterPrimaryMaterial.WAVESPEED, new Vector4(19, 9, -16, -7));
  21303. }
  21304. static __initDefine__() {
  21305. WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  21306. WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  21307. }
  21308. get horizonColor() {
  21309. return this._shaderValues.getVector(WaterPrimaryMaterial.HORIZONCOLOR);
  21310. }
  21311. set horizonColor(value) {
  21312. this._shaderValues.setVector(WaterPrimaryMaterial.HORIZONCOLOR, value);
  21313. }
  21314. get mainTexture() {
  21315. return this._shaderValues.getTexture(WaterPrimaryMaterial.MAINTEXTURE);
  21316. }
  21317. set mainTexture(value) {
  21318. if (value)
  21319. this._shaderValues.addDefine(WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE);
  21320. else
  21321. this._shaderValues.removeDefine(WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE);
  21322. this._shaderValues.setTexture(WaterPrimaryMaterial.MAINTEXTURE, value);
  21323. }
  21324. get normalTexture() {
  21325. return this._shaderValues.getTexture(WaterPrimaryMaterial.NORMALTEXTURE);
  21326. }
  21327. set normalTexture(value) {
  21328. if (value)
  21329. this._shaderValues.addDefine(WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE);
  21330. else
  21331. this._shaderValues.removeDefine(WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE);
  21332. this._shaderValues.setTexture(WaterPrimaryMaterial.NORMALTEXTURE, value);
  21333. }
  21334. get waveScale() {
  21335. return this._shaderValues.getNumber(WaterPrimaryMaterial.WAVESCALE);
  21336. }
  21337. set waveScale(value) {
  21338. this._shaderValues.setNumber(WaterPrimaryMaterial.WAVESCALE, value);
  21339. }
  21340. get waveSpeed() {
  21341. return this._shaderValues.getVector(WaterPrimaryMaterial.WAVESPEED);
  21342. }
  21343. set waveSpeed(value) {
  21344. this._shaderValues.setVector(WaterPrimaryMaterial.WAVESPEED, value);
  21345. }
  21346. clone() {
  21347. var dest = new WaterPrimaryMaterial();
  21348. this.cloneTo(dest);
  21349. return dest;
  21350. }
  21351. }
  21352. WaterPrimaryMaterial.HORIZONCOLOR = Shader3D.propertyNameToID("u_HorizonColor");
  21353. WaterPrimaryMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_MainTexture");
  21354. WaterPrimaryMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  21355. WaterPrimaryMaterial.WAVESCALE = Shader3D.propertyNameToID("u_WaveScale");
  21356. WaterPrimaryMaterial.WAVESPEED = Shader3D.propertyNameToID("u_WaveSpeed");
  21357. class MeshSprite3DShaderDeclaration {
  21358. }
  21359. class MeshRenderer extends BaseRender {
  21360. constructor(owner) {
  21361. super(owner);
  21362. this._revertStaticBatchDefineUV1 = false;
  21363. this._projectionViewWorldMatrix = new Matrix4x4();
  21364. }
  21365. _createRenderElement() {
  21366. return new SubMeshRenderElement();
  21367. }
  21368. _onMeshChange(mesh) {
  21369. if (mesh) {
  21370. var count = mesh.subMeshCount;
  21371. this._renderElements.length = count;
  21372. for (var i = 0; i < count; i++) {
  21373. var renderElement = this._renderElements[i];
  21374. if (!renderElement) {
  21375. var material = this.sharedMaterials[i];
  21376. renderElement = this._renderElements[i] = this._createRenderElement();
  21377. renderElement.setTransform(this._owner._transform);
  21378. renderElement.render = this;
  21379. renderElement.material = material ? material : BlinnPhongMaterial.defaultMaterial;
  21380. }
  21381. renderElement.setGeometry(mesh.getSubMesh(i));
  21382. }
  21383. }
  21384. else {
  21385. this._renderElements.length = 0;
  21386. }
  21387. this._boundsChange = true;
  21388. }
  21389. _calculateBoundingBox() {
  21390. var sharedMesh = this._owner.meshFilter.sharedMesh;
  21391. if (sharedMesh) {
  21392. var worldMat = this._owner.transform.worldMatrix;
  21393. sharedMesh.bounds._tranform(worldMat, this._bounds);
  21394. }
  21395. if (Laya.Render.supportWebGLPlusCulling) {
  21396. var min = this._bounds.getMin();
  21397. var max = this._bounds.getMax();
  21398. var buffer = FrustumCulling._cullingBuffer;
  21399. buffer[this._cullingBufferIndex + 1] = min.x;
  21400. buffer[this._cullingBufferIndex + 2] = min.y;
  21401. buffer[this._cullingBufferIndex + 3] = min.z;
  21402. buffer[this._cullingBufferIndex + 4] = max.x;
  21403. buffer[this._cullingBufferIndex + 5] = max.y;
  21404. buffer[this._cullingBufferIndex + 6] = max.z;
  21405. }
  21406. }
  21407. _needRender(boundFrustum, context) {
  21408. if (boundFrustum)
  21409. return boundFrustum.intersects(this.bounds._getBoundBox());
  21410. else
  21411. return true;
  21412. }
  21413. _renderUpdate(context, transform) {
  21414. this._applyLightMapParams();
  21415. var element = context.renderElement;
  21416. switch (element.renderType) {
  21417. case RenderElement.RENDERTYPE_NORMAL:
  21418. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  21419. break;
  21420. case RenderElement.RENDERTYPE_STATICBATCH:
  21421. if (transform)
  21422. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  21423. else
  21424. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  21425. if (!this._shaderValues.hasDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1)) {
  21426. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  21427. this._revertStaticBatchDefineUV1 = true;
  21428. }
  21429. else {
  21430. this._revertStaticBatchDefineUV1 = false;
  21431. }
  21432. this._shaderValues.setVector(RenderableSprite3D.LIGHTMAPSCALEOFFSET, BaseRender._defaultLightmapScaleOffset);
  21433. break;
  21434. case RenderElement.RENDERTYPE_VERTEXBATCH:
  21435. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  21436. break;
  21437. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  21438. var worldMatrixData = SubMeshInstanceBatch.instance.instanceWorldMatrixData;
  21439. var insBatches = element.instanceBatchElementList;
  21440. var elements = insBatches.elements;
  21441. var count = insBatches.length;
  21442. for (var i = 0; i < count; i++)
  21443. worldMatrixData.set(elements[i]._transform.worldMatrix.elements, i * 16);
  21444. var worldBuffer = SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer;
  21445. worldBuffer.orphanStorage();
  21446. worldBuffer.setData(worldMatrixData.buffer, 0, 0, count * 16 * 4);
  21447. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  21448. break;
  21449. }
  21450. }
  21451. _renderUpdateWithCamera(context, transform) {
  21452. var projectionView = context.projectionViewMatrix;
  21453. if (projectionView) {
  21454. var element = context.renderElement;
  21455. switch (element.renderType) {
  21456. case RenderElement.RENDERTYPE_NORMAL:
  21457. case RenderElement.RENDERTYPE_STATICBATCH:
  21458. case RenderElement.RENDERTYPE_VERTEXBATCH:
  21459. if (transform) {
  21460. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  21461. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  21462. }
  21463. else {
  21464. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  21465. }
  21466. break;
  21467. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  21468. var mvpMatrixData = SubMeshInstanceBatch.instance.instanceMVPMatrixData;
  21469. var insBatches = element.instanceBatchElementList;
  21470. var elements = insBatches.elements;
  21471. var count = insBatches.length;
  21472. for (var i = 0; i < count; i++) {
  21473. var worldMat = elements[i]._transform.worldMatrix;
  21474. Utils3D.mulMatrixByArray(projectionView.elements, 0, worldMat.elements, 0, mvpMatrixData, i * 16);
  21475. }
  21476. var mvpBuffer = SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer;
  21477. mvpBuffer.orphanStorage();
  21478. mvpBuffer.setData(mvpMatrixData.buffer, 0, 0, count * 16 * 4);
  21479. break;
  21480. }
  21481. }
  21482. }
  21483. _revertBatchRenderUpdate(context) {
  21484. var element = context.renderElement;
  21485. switch (element.renderType) {
  21486. case RenderElement.RENDERTYPE_STATICBATCH:
  21487. if (this._revertStaticBatchDefineUV1)
  21488. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  21489. this._shaderValues.setVector(RenderableSprite3D.LIGHTMAPSCALEOFFSET, this.lightmapScaleOffset);
  21490. break;
  21491. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  21492. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  21493. break;
  21494. }
  21495. }
  21496. _destroy() {
  21497. (this._isPartOfStaticBatch) && (MeshRenderStaticBatchManager.instance._removeRenderSprite(this._owner));
  21498. super._destroy();
  21499. }
  21500. }
  21501. class MeshFilter {
  21502. constructor(owner) {
  21503. this._owner = owner;
  21504. }
  21505. get sharedMesh() {
  21506. return this._sharedMesh;
  21507. }
  21508. set sharedMesh(value) {
  21509. if (this._sharedMesh !== value) {
  21510. var defineDatas = this._owner._render._shaderValues;
  21511. var lastValue = this._sharedMesh;
  21512. if (lastValue) {
  21513. lastValue._removeReference();
  21514. this._getMeshDefine(lastValue, MeshFilter._meshVerticeDefine);
  21515. for (var i = 0, n = MeshFilter._meshVerticeDefine.length; i < n; i++)
  21516. defineDatas.removeDefine(MeshFilter._meshVerticeDefine[i]);
  21517. }
  21518. if (value) {
  21519. value._addReference();
  21520. this._getMeshDefine(value, MeshFilter._meshVerticeDefine);
  21521. for (var i = 0, n = MeshFilter._meshVerticeDefine.length; i < n; i++)
  21522. defineDatas.addDefine(MeshFilter._meshVerticeDefine[i]);
  21523. }
  21524. this._owner._render._onMeshChange(value);
  21525. this._sharedMesh = value;
  21526. }
  21527. }
  21528. _getMeshDefine(mesh, out) {
  21529. out.length = 0;
  21530. var define;
  21531. for (var i = 0, n = mesh._subMeshes.length; i < n; i++) {
  21532. var subMesh = mesh.getSubMesh(i);
  21533. var vertexElements = subMesh._vertexBuffer._vertexDeclaration._vertexElements;
  21534. for (var j = 0, m = vertexElements.length; j < m; j++) {
  21535. var vertexElement = vertexElements[j];
  21536. var name = vertexElement._elementUsage;
  21537. switch (name) {
  21538. case VertexMesh.MESH_COLOR0:
  21539. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_COLOR);
  21540. break;
  21541. case VertexMesh.MESH_TEXTURECOORDINATE0:
  21542. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV0);
  21543. break;
  21544. case VertexMesh.MESH_TEXTURECOORDINATE1:
  21545. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  21546. break;
  21547. }
  21548. }
  21549. }
  21550. return define;
  21551. }
  21552. destroy() {
  21553. this._owner = null;
  21554. (this._sharedMesh) && (this._sharedMesh._removeReference(), this._sharedMesh = null);
  21555. }
  21556. }
  21557. MeshFilter._meshVerticeDefine = [];
  21558. class SubMeshDynamicBatch extends GeometryElement {
  21559. constructor() {
  21560. super();
  21561. this._bufferState = new BufferState();
  21562. var gl = Laya.LayaGL.instance;
  21563. var maxVerDec = VertexMesh.getVertexDeclaration("POSITION,NORMAL,COLOR,UV,UV1,TANGENT");
  21564. var maxByteCount = maxVerDec.vertexStride * SubMeshDynamicBatch.maxIndicesCount;
  21565. this._vertices = new Float32Array(maxByteCount / 4);
  21566. this._vertexBuffer = new VertexBuffer3D(maxByteCount, gl.DYNAMIC_DRAW);
  21567. this._indices = new Int16Array(SubMeshDynamicBatch.maxIndicesCount);
  21568. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._indices.length, gl.DYNAMIC_DRAW);
  21569. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  21570. Laya.Resource._addMemory(memorySize, memorySize);
  21571. }
  21572. static __init__() {
  21573. SubMeshDynamicBatch.instance = new SubMeshDynamicBatch();
  21574. }
  21575. _getBatchVertices(vertexDeclaration, batchVertices, batchOffset, transform, element, subMesh) {
  21576. var vertexFloatCount = vertexDeclaration.vertexStride / 4;
  21577. var oriVertexes = subMesh._vertexBuffer.getFloat32Data();
  21578. var lightmapScaleOffset = element.render.lightmapScaleOffset;
  21579. var multiSubMesh = element._dynamicMultiSubMesh;
  21580. var vertexCount = element._dynamicVertexCount;
  21581. element._computeWorldPositionsAndNormals(this._positionOffset, this._normalOffset, multiSubMesh, vertexCount);
  21582. var worldPositions = element._dynamicWorldPositions;
  21583. var worldNormals = element._dynamicWorldNormals;
  21584. var indices = subMesh._indices;
  21585. for (var i = 0; i < vertexCount; i++) {
  21586. var index = multiSubMesh ? indices[i] : i;
  21587. var oriOffset = index * vertexFloatCount;
  21588. var bakeOffset = (i + batchOffset) * vertexFloatCount;
  21589. var oriOff = i * 3;
  21590. var bakOff = bakeOffset + this._positionOffset;
  21591. batchVertices[bakOff] = worldPositions[oriOff];
  21592. batchVertices[bakOff + 1] = worldPositions[oriOff + 1];
  21593. batchVertices[bakOff + 2] = worldPositions[oriOff + 2];
  21594. if (this._normalOffset !== -1) {
  21595. bakOff = bakeOffset + this._normalOffset;
  21596. batchVertices[bakOff] = worldNormals[oriOff];
  21597. batchVertices[bakOff + 1] = worldNormals[oriOff + 1];
  21598. batchVertices[bakOff + 2] = worldNormals[oriOff + 2];
  21599. }
  21600. if (this._colorOffset !== -1) {
  21601. bakOff = bakeOffset + this._colorOffset;
  21602. oriOff = oriOffset + this._colorOffset;
  21603. batchVertices[bakOff] = oriVertexes[oriOff];
  21604. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  21605. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  21606. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  21607. }
  21608. if (this._uv0Offset !== -1) {
  21609. bakOff = bakeOffset + this._uv0Offset;
  21610. oriOff = oriOffset + this._uv0Offset;
  21611. batchVertices[bakOff] = oriVertexes[oriOff];
  21612. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  21613. }
  21614. if (this._sTangentOffset !== -1) {
  21615. bakOff = bakeOffset + this._sTangentOffset;
  21616. oriOff = oriOffset + this._sTangentOffset;
  21617. batchVertices[bakOff] = oriVertexes[oriOff];
  21618. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  21619. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  21620. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  21621. bakOff = bakeOffset + this._sTangentOffset;
  21622. oriOff = oriOffset + this._sTangentOffset;
  21623. batchVertices[bakOff] = oriVertexes[oriOff];
  21624. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  21625. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  21626. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  21627. }
  21628. }
  21629. }
  21630. _getBatchIndices(batchIndices, batchIndexCount, batchVertexCount, transform, subMesh, multiSubMesh) {
  21631. var subIndices = subMesh._indices;
  21632. var k, m, batchOffset;
  21633. var isInvert = transform._isFrontFaceInvert;
  21634. if (multiSubMesh) {
  21635. if (isInvert) {
  21636. for (k = 0, m = subIndices.length; k < m; k += 3) {
  21637. batchOffset = batchIndexCount + k;
  21638. var index = batchVertexCount + k;
  21639. batchIndices[batchOffset] = index;
  21640. batchIndices[batchOffset + 1] = index + 2;
  21641. batchIndices[batchOffset + 2] = index + 1;
  21642. }
  21643. }
  21644. else {
  21645. for (k = 0, m = subIndices.length; k < m; k += 3) {
  21646. batchOffset = batchIndexCount + k;
  21647. index = batchVertexCount + k;
  21648. batchIndices[batchOffset] = index;
  21649. batchIndices[batchOffset + 1] = index + 1;
  21650. batchIndices[batchOffset + 2] = index + 2;
  21651. }
  21652. }
  21653. }
  21654. else {
  21655. if (isInvert) {
  21656. for (k = 0, m = subIndices.length; k < m; k += 3) {
  21657. batchOffset = batchIndexCount + k;
  21658. batchIndices[batchOffset] = batchVertexCount + subIndices[k];
  21659. batchIndices[batchOffset + 1] = batchVertexCount + subIndices[k + 2];
  21660. batchIndices[batchOffset + 2] = batchVertexCount + subIndices[k + 1];
  21661. }
  21662. }
  21663. else {
  21664. for (k = 0, m = subIndices.length; k < m; k += 3) {
  21665. batchOffset = batchIndexCount + k;
  21666. batchIndices[batchOffset] = batchVertexCount + subIndices[k];
  21667. batchIndices[batchOffset + 1] = batchVertexCount + subIndices[k + 1];
  21668. batchIndices[batchOffset + 2] = batchVertexCount + subIndices[k + 2];
  21669. }
  21670. }
  21671. }
  21672. }
  21673. _flush(vertexCount, indexCount) {
  21674. var gl = Laya.LayaGL.instance;
  21675. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, vertexCount * (this._bufferState.vertexDeclaration.vertexStride));
  21676. this._indexBuffer.setData(this._indices, 0, 0, indexCount);
  21677. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  21678. }
  21679. _prepareRender(state) {
  21680. var element = state.renderElement;
  21681. var vertexDeclaration = element.vertexBatchVertexDeclaration;
  21682. this._bufferState = ILaya3D.MeshRenderDynamicBatchManager.instance._getBufferState(vertexDeclaration);
  21683. this._positionOffset = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  21684. var normalElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_NORMAL0);
  21685. this._normalOffset = normalElement ? normalElement._offset / 4 : -1;
  21686. var colorElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  21687. this._colorOffset = colorElement ? colorElement._offset / 4 : -1;
  21688. var uv0Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  21689. this._uv0Offset = uv0Element ? uv0Element._offset / 4 : -1;
  21690. var uv1Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE1);
  21691. this._uv1Offset = uv1Element ? uv1Element._offset / 4 : -1;
  21692. var tangentElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TANGENT0);
  21693. this._sTangentOffset = tangentElement ? tangentElement._offset / 4 : -1;
  21694. return true;
  21695. }
  21696. _render(context) {
  21697. this._bufferState.bind();
  21698. var element = context.renderElement;
  21699. var vertexDeclaration = element.vertexBatchVertexDeclaration;
  21700. var batchElements = element.vertexBatchElementList;
  21701. var batchVertexCount = 0;
  21702. var batchIndexCount = 0;
  21703. var floatStride = vertexDeclaration.vertexStride / 4;
  21704. var renderBatchCount = 0;
  21705. var elementCount = batchElements.length;
  21706. var elements = batchElements.elements;
  21707. for (var i = 0; i < elementCount; i++) {
  21708. var subElement = elements[i];
  21709. var subMesh = subElement._geometry;
  21710. var indexCount = subMesh._indexCount;
  21711. if (batchIndexCount + indexCount > SubMeshDynamicBatch.maxIndicesCount) {
  21712. this._flush(batchVertexCount, batchIndexCount);
  21713. renderBatchCount++;
  21714. Laya.Stat.trianglesFaces += batchIndexCount / 3;
  21715. batchVertexCount = batchIndexCount = 0;
  21716. }
  21717. var transform = subElement._transform;
  21718. this._getBatchVertices(vertexDeclaration, this._vertices, batchVertexCount, transform, subElement, subMesh);
  21719. this._getBatchIndices(this._indices, batchIndexCount, batchVertexCount, transform, subMesh, subElement._dynamicMultiSubMesh);
  21720. batchVertexCount += subElement._dynamicVertexCount;
  21721. batchIndexCount += indexCount;
  21722. }
  21723. this._flush(batchVertexCount, batchIndexCount);
  21724. renderBatchCount++;
  21725. Laya.Stat.renderBatches += renderBatchCount;
  21726. Laya.Stat.savedRenderBatches += elementCount - renderBatchCount;
  21727. Laya.Stat.trianglesFaces += batchIndexCount / 3;
  21728. }
  21729. }
  21730. SubMeshDynamicBatch.maxAllowVertexCount = 10;
  21731. SubMeshDynamicBatch.maxAllowAttribueCount = 900;
  21732. SubMeshDynamicBatch.maxIndicesCount = 32000;
  21733. class MeshRenderDynamicBatchManager extends DynamicBatchManager {
  21734. constructor() {
  21735. super();
  21736. this._instanceBatchOpaqueMarks = [];
  21737. this._vertexBatchOpaqueMarks = [];
  21738. this._cacheBufferStates = [];
  21739. this._updateCountMark = 0;
  21740. }
  21741. getInstanceBatchOpaquaMark(receiveShadow, materialID, subMeshID, invertFace) {
  21742. var instanceReceiveShadowMarks = (this._instanceBatchOpaqueMarks[receiveShadow ? 0 : 1]) || (this._instanceBatchOpaqueMarks[receiveShadow ? 0 : 1] = []);
  21743. var instanceMaterialMarks = (instanceReceiveShadowMarks[materialID]) || (instanceReceiveShadowMarks[materialID] = []);
  21744. var instancSubMeshMarks = (instanceMaterialMarks[subMeshID]) || (instanceMaterialMarks[subMeshID] = []);
  21745. return instancSubMeshMarks[invertFace ? 1 : 0] || (instancSubMeshMarks[invertFace ? 1 : 0] = new BatchMark());
  21746. }
  21747. getVertexBatchOpaquaMark(lightMapIndex, receiveShadow, materialID, verDecID) {
  21748. var dynLightMapMarks = (this._vertexBatchOpaqueMarks[lightMapIndex]) || (this._vertexBatchOpaqueMarks[lightMapIndex] = []);
  21749. var dynReceiveShadowMarks = (dynLightMapMarks[receiveShadow ? 0 : 1]) || (dynLightMapMarks[receiveShadow ? 0 : 1] = []);
  21750. var dynMaterialMarks = (dynReceiveShadowMarks[materialID]) || (dynReceiveShadowMarks[materialID] = []);
  21751. return dynMaterialMarks[verDecID] || (dynMaterialMarks[verDecID] = new BatchMark());
  21752. }
  21753. _getBufferState(vertexDeclaration) {
  21754. var bufferState = this._cacheBufferStates[vertexDeclaration.id];
  21755. if (!bufferState) {
  21756. var instance = SubMeshDynamicBatch.instance;
  21757. bufferState = new BufferState();
  21758. bufferState.bind();
  21759. var vertexBuffer = instance._vertexBuffer;
  21760. vertexBuffer.vertexDeclaration = vertexDeclaration;
  21761. bufferState.applyVertexBuffer(vertexBuffer);
  21762. bufferState.applyIndexBuffer(instance._indexBuffer);
  21763. bufferState.unBind();
  21764. this._cacheBufferStates[vertexDeclaration.id] = bufferState;
  21765. }
  21766. return bufferState;
  21767. }
  21768. _getBatchRenderElementFromPool() {
  21769. var renderElement = this._batchRenderElementPool[this._batchRenderElementPoolIndex++];
  21770. if (!renderElement) {
  21771. renderElement = new SubMeshRenderElement();
  21772. this._batchRenderElementPool[this._batchRenderElementPoolIndex - 1] = renderElement;
  21773. renderElement.vertexBatchElementList = new SingletonList();
  21774. renderElement.instanceBatchElementList = new SingletonList();
  21775. }
  21776. return renderElement;
  21777. }
  21778. _clear() {
  21779. super._clear();
  21780. this._updateCountMark++;
  21781. }
  21782. }
  21783. MeshRenderDynamicBatchManager.instance = new MeshRenderDynamicBatchManager();
  21784. class MeshSprite3D extends RenderableSprite3D {
  21785. constructor(mesh = null, name = null) {
  21786. super(name);
  21787. this._meshFilter = new MeshFilter(this);
  21788. this._render = new MeshRenderer(this);
  21789. (mesh) && (this._meshFilter.sharedMesh = mesh);
  21790. }
  21791. static __init__() {
  21792. MeshSprite3DShaderDeclaration.SHADERDEFINE_UV0 = Shader3D.getDefineByName("UV");
  21793. MeshSprite3DShaderDeclaration.SHADERDEFINE_COLOR = Shader3D.getDefineByName("COLOR");
  21794. MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1 = Shader3D.getDefineByName("UV1");
  21795. MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE = Shader3D.getDefineByName("GPU_INSTANCE");
  21796. StaticBatchManager._registerManager(MeshRenderStaticBatchManager.instance);
  21797. DynamicBatchManager._registerManager(MeshRenderDynamicBatchManager.instance);
  21798. }
  21799. get meshFilter() {
  21800. return this._meshFilter;
  21801. }
  21802. get meshRenderer() {
  21803. return this._render;
  21804. }
  21805. _parse(data, spriteMap) {
  21806. super._parse(data, spriteMap);
  21807. var render = this.meshRenderer;
  21808. var lightmapIndex = data.lightmapIndex;
  21809. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  21810. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  21811. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  21812. (data.meshPath != undefined) && (this.meshFilter.sharedMesh = Laya.Loader.getRes(data.meshPath));
  21813. (data.enableRender != undefined) && (render.enable = data.enableRender);
  21814. (data.receiveShadows != undefined) && (render.receiveShadow = data.receiveShadows);
  21815. (data.castShadow != undefined) && (render.castShadow = data.castShadow);
  21816. var materials = data.materials;
  21817. if (materials) {
  21818. var sharedMaterials = render.sharedMaterials;
  21819. var materialCount = materials.length;
  21820. sharedMaterials.length = materialCount;
  21821. for (var i = 0; i < materialCount; i++) {
  21822. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  21823. }
  21824. render.sharedMaterials = sharedMaterials;
  21825. }
  21826. }
  21827. _addToInitStaticBatchManager() {
  21828. if (this.meshFilter.sharedMesh)
  21829. MeshRenderStaticBatchManager.instance._addBatchSprite(this);
  21830. }
  21831. _cloneTo(destObject, rootSprite, dstSprite) {
  21832. var meshSprite3D = destObject;
  21833. meshSprite3D._meshFilter.sharedMesh = this._meshFilter.sharedMesh;
  21834. var meshRender = this._render;
  21835. var destMeshRender = meshSprite3D._render;
  21836. destMeshRender.enable = meshRender.enable;
  21837. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  21838. destMeshRender.castShadow = meshRender.castShadow;
  21839. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  21840. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  21841. destMeshRender.lightmapIndex = meshRender.lightmapIndex;
  21842. destMeshRender.receiveShadow = meshRender.receiveShadow;
  21843. destMeshRender.sortingFudge = meshRender.sortingFudge;
  21844. super._cloneTo(destObject, rootSprite, dstSprite);
  21845. }
  21846. destroy(destroyChild = true) {
  21847. if (this.destroyed)
  21848. return;
  21849. super.destroy(destroyChild);
  21850. this._meshFilter.destroy();
  21851. }
  21852. _create() {
  21853. return new MeshSprite3D();
  21854. }
  21855. }
  21856. class GradientMode {
  21857. }
  21858. GradientMode.Blend = 0;
  21859. GradientMode.Fixed = 1;
  21860. class Gradient {
  21861. constructor(maxColorRGBKeyCount, maxColorAlphaKeyCount) {
  21862. this._mode = 0;
  21863. this._maxColorRGBKeysCount = 0;
  21864. this._maxColorAlphaKeysCount = 0;
  21865. this._colorRGBKeysCount = 0;
  21866. this._colorAlphaKeysCount = 0;
  21867. this._alphaElements = null;
  21868. this._rgbElements = null;
  21869. this._maxColorRGBKeysCount = maxColorRGBKeyCount;
  21870. this._maxColorAlphaKeysCount = maxColorAlphaKeyCount;
  21871. this._rgbElements = new Float32Array(maxColorRGBKeyCount * 4);
  21872. this._alphaElements = new Float32Array(maxColorAlphaKeyCount * 2);
  21873. }
  21874. get mode() {
  21875. return this._mode;
  21876. }
  21877. set mode(value) {
  21878. this._mode = value;
  21879. }
  21880. get colorRGBKeysCount() {
  21881. return this._colorRGBKeysCount;
  21882. }
  21883. get colorAlphaKeysCount() {
  21884. return this._colorAlphaKeysCount;
  21885. }
  21886. get maxColorRGBKeysCount() {
  21887. return this._maxColorRGBKeysCount;
  21888. }
  21889. get maxColorAlphaKeysCount() {
  21890. return this._maxColorAlphaKeysCount;
  21891. }
  21892. addColorRGB(key, value) {
  21893. if (this._colorRGBKeysCount < this._maxColorRGBKeysCount) {
  21894. var offset = this._colorRGBKeysCount * 4;
  21895. this._rgbElements[offset] = key;
  21896. this._rgbElements[offset + 1] = value.r;
  21897. this._rgbElements[offset + 2] = value.g;
  21898. this._rgbElements[offset + 3] = value.b;
  21899. this._colorRGBKeysCount++;
  21900. }
  21901. else {
  21902. console.warn("Gradient:warning:data count must lessEqual than " + this._maxColorRGBKeysCount);
  21903. }
  21904. }
  21905. addColorAlpha(key, value) {
  21906. if (this._colorAlphaKeysCount < this._maxColorAlphaKeysCount) {
  21907. var offset = this._colorAlphaKeysCount * 2;
  21908. this._alphaElements[offset] = key;
  21909. this._alphaElements[offset + 1] = value;
  21910. this._colorAlphaKeysCount++;
  21911. }
  21912. else {
  21913. console.warn("Gradient:warning:data count must lessEqual than " + this._maxColorAlphaKeysCount);
  21914. }
  21915. }
  21916. updateColorRGB(index, key, value) {
  21917. if (index < this._colorRGBKeysCount) {
  21918. var offset = index * 4;
  21919. this._rgbElements[offset] = key;
  21920. this._rgbElements[offset + 1] = value.r;
  21921. this._rgbElements[offset + 2] = value.g;
  21922. this._rgbElements[offset + 3] = value.b;
  21923. }
  21924. else {
  21925. console.warn("Gradient:warning:index must lessEqual than colorRGBKeysCount:" + this._colorRGBKeysCount);
  21926. }
  21927. }
  21928. updateColorAlpha(index, key, value) {
  21929. if (index < this._colorAlphaKeysCount) {
  21930. var offset = index * 2;
  21931. this._alphaElements[offset] = key;
  21932. this._alphaElements[offset + 1] = value;
  21933. }
  21934. else {
  21935. console.warn("Gradient:warning:index must lessEqual than colorAlphaKeysCount:" + this._colorAlphaKeysCount);
  21936. }
  21937. }
  21938. evaluateColorRGB(lerpFactor, out, startSearchIndex = 0, reverseSearch = false) {
  21939. lerpFactor = Math.min(Math.max(lerpFactor, 0.0), 1.0);
  21940. var rgbElements = this._rgbElements;
  21941. var curIndex = startSearchIndex;
  21942. if (reverseSearch) {
  21943. for (var i = curIndex; i >= 0; i--) {
  21944. var offset = i * 4;
  21945. var left = rgbElements[offset];
  21946. if (lerpFactor === left) {
  21947. out.r = rgbElements[offset + 1];
  21948. out.g = rgbElements[offset + 2];
  21949. out.b = rgbElements[offset + 3];
  21950. return curIndex;
  21951. }
  21952. switch (this._mode) {
  21953. case GradientMode.Blend:
  21954. if (lerpFactor > left) {
  21955. var right = rgbElements[offset + 4];
  21956. if (lerpFactor > right)
  21957. throw "Gradient:wrong startSearchIndex.";
  21958. var diff = right - left;
  21959. var y1 = right - lerpFactor;
  21960. var y2 = lerpFactor - left;
  21961. out.r = (y1 * rgbElements[offset + 1] + y2 * rgbElements[offset + 5]) / diff;
  21962. out.g = (y1 * rgbElements[offset + 2] + y2 * rgbElements[offset + 6]) / diff;
  21963. out.b = (y1 * rgbElements[offset + 3] + y2 * rgbElements[offset + 7]) / diff;
  21964. return curIndex;
  21965. }
  21966. else {
  21967. curIndex--;
  21968. continue;
  21969. }
  21970. case GradientMode.Fixed:
  21971. if (lerpFactor > left) {
  21972. if (lerpFactor > rgbElements[offset + 4])
  21973. throw "Gradient:wrong startSearchIndex.";
  21974. out.r = rgbElements[offset + 5];
  21975. out.g = rgbElements[offset + 6];
  21976. out.b = rgbElements[offset + 7];
  21977. return curIndex;
  21978. }
  21979. else {
  21980. curIndex--;
  21981. continue;
  21982. }
  21983. default:
  21984. throw "Gradient:unknown mode.";
  21985. }
  21986. }
  21987. }
  21988. else {
  21989. for (var i = 0, n = this._rgbElements.length; i < n; i++) {
  21990. offset = i * 4;
  21991. var right = rgbElements[offset];
  21992. if (lerpFactor === right) {
  21993. out.r = rgbElements[offset + 1];
  21994. out.g = rgbElements[offset + 2];
  21995. out.b = rgbElements[offset + 3];
  21996. return curIndex;
  21997. }
  21998. switch (this._mode) {
  21999. case GradientMode.Blend:
  22000. if (lerpFactor < right) {
  22001. var left = rgbElements[offset - 4];
  22002. if (lerpFactor < left)
  22003. throw "Gradient:wrong startSearchIndex.";
  22004. var diff = right - left;
  22005. var y1 = right - lerpFactor;
  22006. var y2 = lerpFactor - left;
  22007. out.r = (y1 * rgbElements[offset - 3] + y2 * rgbElements[offset + 1]) / diff;
  22008. out.g = (y1 * rgbElements[offset - 2] + y2 * rgbElements[offset + 2]) / diff;
  22009. out.b = (y1 * rgbElements[offset - 1] + y2 * rgbElements[offset + 3]) / diff;
  22010. return curIndex;
  22011. }
  22012. else {
  22013. curIndex++;
  22014. continue;
  22015. }
  22016. case GradientMode.Fixed:
  22017. if (lerpFactor < right) {
  22018. if (lerpFactor < rgbElements[offset - 4])
  22019. throw "Gradient:wrong startSearchIndex.";
  22020. out.r = rgbElements[offset + 1];
  22021. out.g = rgbElements[offset + 2];
  22022. out.b = rgbElements[offset + 3];
  22023. return curIndex;
  22024. }
  22025. else {
  22026. curIndex++;
  22027. continue;
  22028. }
  22029. default:
  22030. throw "Gradient:unknown mode.";
  22031. }
  22032. }
  22033. }
  22034. return curIndex;
  22035. }
  22036. evaluateColorAlpha(lerpFactor, outColor, startSearchIndex = 0, reverseSearch = false) {
  22037. lerpFactor = Math.min(Math.max(lerpFactor, 0.0), 1.0);
  22038. var alphaElements = this._alphaElements;
  22039. var curIndex = startSearchIndex;
  22040. if (reverseSearch) {
  22041. for (var i = curIndex; i >= 0; i--) {
  22042. var offset = i * 2;
  22043. var left = alphaElements[offset];
  22044. if (lerpFactor === left) {
  22045. outColor.a = alphaElements[offset + 1];
  22046. return curIndex;
  22047. }
  22048. switch (this._mode) {
  22049. case GradientMode.Blend:
  22050. if (lerpFactor > left) {
  22051. var right = alphaElements[offset + 2];
  22052. if (lerpFactor > right)
  22053. throw "Gradient:wrong startSearchIndex.";
  22054. var diff = right - left;
  22055. var x1 = right - lerpFactor;
  22056. var x2 = lerpFactor - left;
  22057. outColor.a = (x1 * alphaElements[offset + 1] + x2 * alphaElements[offset + 3]) / diff;
  22058. return curIndex;
  22059. }
  22060. else {
  22061. curIndex--;
  22062. continue;
  22063. }
  22064. case GradientMode.Fixed:
  22065. if (lerpFactor > left) {
  22066. if (lerpFactor > alphaElements[offset + 2])
  22067. throw "Gradient:wrong startSearchIndex.";
  22068. outColor.a = alphaElements[offset + 3];
  22069. return curIndex;
  22070. }
  22071. else {
  22072. curIndex--;
  22073. continue;
  22074. }
  22075. default:
  22076. throw "Gradient:unknown mode.";
  22077. }
  22078. }
  22079. }
  22080. else {
  22081. for (var i = curIndex, n = this._alphaElements.length; i < n; i++) {
  22082. var offset = i * 2;
  22083. var right = alphaElements[offset];
  22084. if (lerpFactor === right) {
  22085. outColor.a = alphaElements[offset + 1];
  22086. return curIndex;
  22087. }
  22088. switch (this._mode) {
  22089. case GradientMode.Blend:
  22090. if (lerpFactor < right) {
  22091. var left = alphaElements[offset - 2];
  22092. if (lerpFactor < left)
  22093. throw "Gradient:wrong startSearchIndex.";
  22094. var diff = right - left;
  22095. var x1 = right - lerpFactor;
  22096. var x2 = lerpFactor - left;
  22097. outColor.a = (x1 * alphaElements[offset - 1] + x2 * alphaElements[offset + 1]) / diff;
  22098. return curIndex;
  22099. }
  22100. else {
  22101. curIndex++;
  22102. continue;
  22103. }
  22104. case GradientMode.Fixed:
  22105. if (lerpFactor < right) {
  22106. if (lerpFactor < alphaElements[offset - 2])
  22107. throw "Gradient:wrong startSearchIndex.";
  22108. outColor.a = alphaElements[offset + 1];
  22109. return curIndex;
  22110. }
  22111. else {
  22112. curIndex++;
  22113. continue;
  22114. }
  22115. default:
  22116. throw "Gradient:unknown mode.";
  22117. }
  22118. }
  22119. }
  22120. return curIndex;
  22121. }
  22122. cloneTo(destObject) {
  22123. var destGradientDataColor = destObject;
  22124. var i, n;
  22125. destGradientDataColor._colorAlphaKeysCount = this._colorAlphaKeysCount;
  22126. var destAlphaElements = destGradientDataColor._alphaElements;
  22127. for (i = 0, n = this._alphaElements.length; i < n; i++)
  22128. destAlphaElements[i] = this._alphaElements[i];
  22129. destGradientDataColor._colorRGBKeysCount = this._colorRGBKeysCount;
  22130. var destRGBElements = destGradientDataColor._rgbElements;
  22131. for (i = 0, n = this._rgbElements.length; i < n; i++)
  22132. destRGBElements[i] = this._rgbElements[i];
  22133. }
  22134. clone() {
  22135. var destGradientDataColor = new Gradient(this._maxColorRGBKeysCount, this._maxColorAlphaKeysCount);
  22136. this.cloneTo(destGradientDataColor);
  22137. return destGradientDataColor;
  22138. }
  22139. }
  22140. class Burst {
  22141. constructor(time, minCount, maxCount) {
  22142. this._time = time;
  22143. this._minCount = minCount;
  22144. this._maxCount = maxCount;
  22145. }
  22146. get time() {
  22147. return this._time;
  22148. }
  22149. get minCount() {
  22150. return this._minCount;
  22151. }
  22152. get maxCount() {
  22153. return this._maxCount;
  22154. }
  22155. cloneTo(destObject) {
  22156. var destBurst = destObject;
  22157. destBurst._time = this._time;
  22158. destBurst._minCount = this._minCount;
  22159. destBurst._maxCount = this._maxCount;
  22160. }
  22161. clone() {
  22162. var destBurst = new Burst(this._time, this._minCount, this._maxCount);
  22163. this.cloneTo(destBurst);
  22164. return destBurst;
  22165. }
  22166. }
  22167. class GradientColor {
  22168. constructor() {
  22169. this._type = 0;
  22170. this._constant = null;
  22171. this._constantMin = null;
  22172. this._constantMax = null;
  22173. this._gradient = null;
  22174. this._gradientMin = null;
  22175. this._gradientMax = null;
  22176. }
  22177. static createByConstant(constant) {
  22178. var gradientColor = new GradientColor();
  22179. gradientColor._type = 0;
  22180. gradientColor._constant = constant;
  22181. return gradientColor;
  22182. }
  22183. static createByGradient(gradient) {
  22184. var gradientColor = new GradientColor();
  22185. gradientColor._type = 1;
  22186. gradientColor._gradient = gradient;
  22187. return gradientColor;
  22188. }
  22189. static createByRandomTwoConstant(minConstant, maxConstant) {
  22190. var gradientColor = new GradientColor();
  22191. gradientColor._type = 2;
  22192. gradientColor._constantMin = minConstant;
  22193. gradientColor._constantMax = maxConstant;
  22194. return gradientColor;
  22195. }
  22196. static createByRandomTwoGradient(minGradient, maxGradient) {
  22197. var gradientColor = new GradientColor();
  22198. gradientColor._type = 3;
  22199. gradientColor._gradientMin = minGradient;
  22200. gradientColor._gradientMax = maxGradient;
  22201. return gradientColor;
  22202. }
  22203. get type() {
  22204. return this._type;
  22205. }
  22206. get constant() {
  22207. return this._constant;
  22208. }
  22209. get constantMin() {
  22210. return this._constantMin;
  22211. }
  22212. get constantMax() {
  22213. return this._constantMax;
  22214. }
  22215. get gradient() {
  22216. return this._gradient;
  22217. }
  22218. get gradientMin() {
  22219. return this._gradientMin;
  22220. }
  22221. get gradientMax() {
  22222. return this._gradientMax;
  22223. }
  22224. cloneTo(destObject) {
  22225. var destGradientColor = destObject;
  22226. destGradientColor._type = this._type;
  22227. this._constant.cloneTo(destGradientColor._constant);
  22228. this._constantMin.cloneTo(destGradientColor._constantMin);
  22229. this._constantMax.cloneTo(destGradientColor._constantMax);
  22230. this._gradient.cloneTo(destGradientColor._gradient);
  22231. this._gradientMin.cloneTo(destGradientColor._gradientMin);
  22232. this._gradientMax.cloneTo(destGradientColor._gradientMax);
  22233. }
  22234. clone() {
  22235. var destGradientColor = new GradientColor();
  22236. this.cloneTo(destGradientColor);
  22237. return destGradientColor;
  22238. }
  22239. }
  22240. class ColorOverLifetime {
  22241. constructor(color) {
  22242. this._color = color;
  22243. }
  22244. get color() {
  22245. return this._color;
  22246. }
  22247. cloneTo(destObject) {
  22248. var destColorOverLifetime = destObject;
  22249. this._color.cloneTo(destColorOverLifetime._color);
  22250. destColorOverLifetime.enable = this.enable;
  22251. }
  22252. clone() {
  22253. var destColor;
  22254. switch (this._color.type) {
  22255. case 0:
  22256. destColor = GradientColor.createByConstant(this._color.constant.clone());
  22257. break;
  22258. case 1:
  22259. destColor = GradientColor.createByGradient(this._color.gradient.clone());
  22260. break;
  22261. case 2:
  22262. destColor = GradientColor.createByRandomTwoConstant(this._color.constantMin.clone(), this._color.constantMax.clone());
  22263. break;
  22264. case 3:
  22265. destColor = GradientColor.createByRandomTwoGradient(this._color.gradientMin.clone(), this._color.gradientMax.clone());
  22266. break;
  22267. }
  22268. var destColorOverLifetime = new ColorOverLifetime(destColor);
  22269. destColorOverLifetime.enable = this.enable;
  22270. return destColorOverLifetime;
  22271. }
  22272. }
  22273. class FrameOverTime {
  22274. constructor() {
  22275. this._type = 0;
  22276. this._constant = 0;
  22277. this._overTime = null;
  22278. this._constantMin = 0;
  22279. this._constantMax = 0;
  22280. this._overTimeMin = null;
  22281. this._overTimeMax = null;
  22282. }
  22283. static createByConstant(constant = 0) {
  22284. var rotationOverLifetime = new FrameOverTime();
  22285. rotationOverLifetime._type = 0;
  22286. rotationOverLifetime._constant = constant;
  22287. return rotationOverLifetime;
  22288. }
  22289. static createByOverTime(overTime) {
  22290. var rotationOverLifetime = new FrameOverTime();
  22291. rotationOverLifetime._type = 1;
  22292. rotationOverLifetime._overTime = overTime;
  22293. return rotationOverLifetime;
  22294. }
  22295. static createByRandomTwoConstant(constantMin = 0, constantMax = 0) {
  22296. var rotationOverLifetime = new FrameOverTime();
  22297. rotationOverLifetime._type = 2;
  22298. rotationOverLifetime._constantMin = constantMin;
  22299. rotationOverLifetime._constantMax = constantMax;
  22300. return rotationOverLifetime;
  22301. }
  22302. static createByRandomTwoOverTime(gradientFrameMin, gradientFrameMax) {
  22303. var rotationOverLifetime = new FrameOverTime();
  22304. rotationOverLifetime._type = 3;
  22305. rotationOverLifetime._overTimeMin = gradientFrameMin;
  22306. rotationOverLifetime._overTimeMax = gradientFrameMax;
  22307. return rotationOverLifetime;
  22308. }
  22309. get type() {
  22310. return this._type;
  22311. }
  22312. get constant() {
  22313. return this._constant;
  22314. }
  22315. get frameOverTimeData() {
  22316. return this._overTime;
  22317. }
  22318. get constantMin() {
  22319. return this._constantMin;
  22320. }
  22321. get constantMax() {
  22322. return this._constantMax;
  22323. }
  22324. get frameOverTimeDataMin() {
  22325. return this._overTimeMin;
  22326. }
  22327. get frameOverTimeDataMax() {
  22328. return this._overTimeMax;
  22329. }
  22330. cloneTo(destObject) {
  22331. var destFrameOverTime = destObject;
  22332. destFrameOverTime._type = this._type;
  22333. destFrameOverTime._constant = this._constant;
  22334. (this._overTime) && (this._overTime.cloneTo(destFrameOverTime._overTime));
  22335. destFrameOverTime._constantMin = this._constantMin;
  22336. destFrameOverTime._constantMax = this._constantMax;
  22337. (this._overTimeMin) && (this._overTimeMin.cloneTo(destFrameOverTime._overTimeMin));
  22338. (this._overTimeMax) && (this._overTimeMax.cloneTo(destFrameOverTime._overTimeMax));
  22339. }
  22340. clone() {
  22341. var destFrameOverTime = new FrameOverTime();
  22342. this.cloneTo(destFrameOverTime);
  22343. return destFrameOverTime;
  22344. }
  22345. }
  22346. class GradientAngularVelocity {
  22347. constructor() {
  22348. this._type = 0;
  22349. this._separateAxes = false;
  22350. this._constant = 0;
  22351. this._constantSeparate = null;
  22352. this._gradient = null;
  22353. this._gradientX = null;
  22354. this._gradientY = null;
  22355. this._gradientZ = null;
  22356. this._gradientW = null;
  22357. this._constantMin = 0;
  22358. this._constantMax = 0;
  22359. this._constantMinSeparate = null;
  22360. this._constantMaxSeparate = null;
  22361. this._gradientMin = null;
  22362. this._gradientMax = null;
  22363. this._gradientXMin = null;
  22364. this._gradientXMax = null;
  22365. this._gradientYMin = null;
  22366. this._gradientYMax = null;
  22367. this._gradientZMin = null;
  22368. this._gradientZMax = null;
  22369. this._gradientWMin = null;
  22370. this._gradientWMax = null;
  22371. }
  22372. static createByConstant(constant) {
  22373. var gradientAngularVelocity = new GradientAngularVelocity();
  22374. gradientAngularVelocity._type = 0;
  22375. gradientAngularVelocity._separateAxes = false;
  22376. gradientAngularVelocity._constant = constant;
  22377. return gradientAngularVelocity;
  22378. }
  22379. static createByConstantSeparate(separateConstant) {
  22380. var gradientAngularVelocity = new GradientAngularVelocity();
  22381. gradientAngularVelocity._type = 0;
  22382. gradientAngularVelocity._separateAxes = true;
  22383. gradientAngularVelocity._constantSeparate = separateConstant;
  22384. return gradientAngularVelocity;
  22385. }
  22386. static createByGradient(gradient) {
  22387. var gradientAngularVelocity = new GradientAngularVelocity();
  22388. gradientAngularVelocity._type = 1;
  22389. gradientAngularVelocity._separateAxes = false;
  22390. gradientAngularVelocity._gradient = gradient;
  22391. return gradientAngularVelocity;
  22392. }
  22393. static createByGradientSeparate(gradientX, gradientY, gradientZ) {
  22394. var gradientAngularVelocity = new GradientAngularVelocity();
  22395. gradientAngularVelocity._type = 1;
  22396. gradientAngularVelocity._separateAxes = true;
  22397. gradientAngularVelocity._gradientX = gradientX;
  22398. gradientAngularVelocity._gradientY = gradientY;
  22399. gradientAngularVelocity._gradientZ = gradientZ;
  22400. return gradientAngularVelocity;
  22401. }
  22402. static createByRandomTwoConstant(constantMin, constantMax) {
  22403. var gradientAngularVelocity = new GradientAngularVelocity();
  22404. gradientAngularVelocity._type = 2;
  22405. gradientAngularVelocity._separateAxes = false;
  22406. gradientAngularVelocity._constantMin = constantMin;
  22407. gradientAngularVelocity._constantMax = constantMax;
  22408. return gradientAngularVelocity;
  22409. }
  22410. static createByRandomTwoConstantSeparate(separateConstantMin, separateConstantMax) {
  22411. var gradientAngularVelocity = new GradientAngularVelocity();
  22412. gradientAngularVelocity._type = 2;
  22413. gradientAngularVelocity._separateAxes = true;
  22414. gradientAngularVelocity._constantMinSeparate = separateConstantMin;
  22415. gradientAngularVelocity._constantMaxSeparate = separateConstantMax;
  22416. return gradientAngularVelocity;
  22417. }
  22418. static createByRandomTwoGradient(gradientMin, gradientMax) {
  22419. var gradientAngularVelocity = new GradientAngularVelocity();
  22420. gradientAngularVelocity._type = 3;
  22421. gradientAngularVelocity._separateAxes = false;
  22422. gradientAngularVelocity._gradientMin = gradientMin;
  22423. gradientAngularVelocity._gradientMax = gradientMax;
  22424. return gradientAngularVelocity;
  22425. }
  22426. static createByRandomTwoGradientSeparate(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax, gradientWMin, gradientWMax) {
  22427. var gradientAngularVelocity = new GradientAngularVelocity();
  22428. gradientAngularVelocity._type = 3;
  22429. gradientAngularVelocity._separateAxes = true;
  22430. gradientAngularVelocity._gradientXMin = gradientXMin;
  22431. gradientAngularVelocity._gradientXMax = gradientXMax;
  22432. gradientAngularVelocity._gradientYMin = gradientYMin;
  22433. gradientAngularVelocity._gradientYMax = gradientYMax;
  22434. gradientAngularVelocity._gradientZMin = gradientZMin;
  22435. gradientAngularVelocity._gradientZMax = gradientZMax;
  22436. gradientAngularVelocity._gradientWMin = gradientWMin;
  22437. gradientAngularVelocity._gradientWMax = gradientWMax;
  22438. return gradientAngularVelocity;
  22439. }
  22440. get type() {
  22441. return this._type;
  22442. }
  22443. get separateAxes() {
  22444. return this._separateAxes;
  22445. }
  22446. get constant() {
  22447. return this._constant;
  22448. }
  22449. get constantSeparate() {
  22450. return this._constantSeparate;
  22451. }
  22452. get gradient() {
  22453. return this._gradient;
  22454. }
  22455. get gradientX() {
  22456. return this._gradientX;
  22457. }
  22458. get gradientY() {
  22459. return this._gradientY;
  22460. }
  22461. get gradientZ() {
  22462. return this._gradientZ;
  22463. }
  22464. get gradientW() {
  22465. return this._gradientW;
  22466. }
  22467. get constantMin() {
  22468. return this._constantMin;
  22469. }
  22470. get constantMax() {
  22471. return this._constantMax;
  22472. }
  22473. get constantMinSeparate() {
  22474. return this._constantMinSeparate;
  22475. }
  22476. get constantMaxSeparate() {
  22477. return this._constantMaxSeparate;
  22478. }
  22479. get gradientMin() {
  22480. return this._gradientMin;
  22481. }
  22482. get gradientMax() {
  22483. return this._gradientMax;
  22484. }
  22485. get gradientXMin() {
  22486. return this._gradientXMin;
  22487. }
  22488. get gradientXMax() {
  22489. return this._gradientXMax;
  22490. }
  22491. get gradientYMin() {
  22492. return this._gradientYMin;
  22493. }
  22494. get gradientYMax() {
  22495. return this._gradientYMax;
  22496. }
  22497. get gradientZMin() {
  22498. return this._gradientZMin;
  22499. }
  22500. get gradientZMax() {
  22501. return this._gradientZMax;
  22502. }
  22503. get gradientWMin() {
  22504. return this._gradientWMin;
  22505. }
  22506. get gradientWMax() {
  22507. return this._gradientWMax;
  22508. }
  22509. cloneTo(destObject) {
  22510. var destGradientAngularVelocity = destObject;
  22511. destGradientAngularVelocity._type = this._type;
  22512. destGradientAngularVelocity._separateAxes = this._separateAxes;
  22513. destGradientAngularVelocity._constant = this._constant;
  22514. this._constantSeparate.cloneTo(destGradientAngularVelocity._constantSeparate);
  22515. this._gradient.cloneTo(destGradientAngularVelocity._gradient);
  22516. this._gradientX.cloneTo(destGradientAngularVelocity._gradientX);
  22517. this._gradientY.cloneTo(destGradientAngularVelocity._gradientY);
  22518. this._gradientZ.cloneTo(destGradientAngularVelocity._gradientZ);
  22519. destGradientAngularVelocity._constantMin = this._constantMin;
  22520. destGradientAngularVelocity._constantMax = this._constantMax;
  22521. this._constantMinSeparate.cloneTo(destGradientAngularVelocity._constantMinSeparate);
  22522. this._constantMaxSeparate.cloneTo(destGradientAngularVelocity._constantMaxSeparate);
  22523. this._gradientMin.cloneTo(destGradientAngularVelocity._gradientMin);
  22524. this._gradientMax.cloneTo(destGradientAngularVelocity._gradientMax);
  22525. this._gradientXMin.cloneTo(destGradientAngularVelocity._gradientXMin);
  22526. this._gradientXMax.cloneTo(destGradientAngularVelocity._gradientXMax);
  22527. this._gradientYMin.cloneTo(destGradientAngularVelocity._gradientYMin);
  22528. this._gradientYMax.cloneTo(destGradientAngularVelocity._gradientYMax);
  22529. this._gradientZMin.cloneTo(destGradientAngularVelocity._gradientZMin);
  22530. this._gradientZMax.cloneTo(destGradientAngularVelocity._gradientZMax);
  22531. }
  22532. clone() {
  22533. var destGradientAngularVelocity = new GradientAngularVelocity();
  22534. this.cloneTo(destGradientAngularVelocity);
  22535. return destGradientAngularVelocity;
  22536. }
  22537. }
  22538. class GradientDataInt {
  22539. constructor() {
  22540. this._currentLength = 0;
  22541. this._elements = new Float32Array(8);
  22542. }
  22543. get gradientCount() {
  22544. return this._currentLength / 2;
  22545. }
  22546. add(key, value) {
  22547. if (this._currentLength < 8) {
  22548. if ((this._currentLength === 6) && ((key !== 1))) {
  22549. key = 1;
  22550. console.log("Warning:the forth key is be force set to 1.");
  22551. }
  22552. this._elements[this._currentLength++] = key;
  22553. this._elements[this._currentLength++] = value;
  22554. }
  22555. else {
  22556. console.log("Warning:data count must lessEqual than 4");
  22557. }
  22558. }
  22559. cloneTo(destObject) {
  22560. var destGradientDataInt = destObject;
  22561. destGradientDataInt._currentLength = this._currentLength;
  22562. var destElements = destGradientDataInt._elements;
  22563. for (var i = 0, n = this._elements.length; i < n; i++) {
  22564. destElements[i] = this._elements[i];
  22565. }
  22566. }
  22567. clone() {
  22568. var destGradientDataInt = new GradientDataInt();
  22569. this.cloneTo(destGradientDataInt);
  22570. return destGradientDataInt;
  22571. }
  22572. }
  22573. class GradientDataNumber {
  22574. constructor() {
  22575. this._currentLength = 0;
  22576. this._elements = new Float32Array(8);
  22577. }
  22578. get gradientCount() {
  22579. return this._currentLength / 2;
  22580. }
  22581. add(key, value) {
  22582. if (this._currentLength < 8) {
  22583. if ((this._currentLength === 6) && ((key !== 1))) {
  22584. key = 1;
  22585. console.log("GradientDataNumber warning:the forth key is be force set to 1.");
  22586. }
  22587. this._elements[this._currentLength++] = key;
  22588. this._elements[this._currentLength++] = value;
  22589. }
  22590. else {
  22591. console.log("GradientDataNumber warning:data count must lessEqual than 4");
  22592. }
  22593. }
  22594. getKeyByIndex(index) {
  22595. return this._elements[index * 2];
  22596. }
  22597. getValueByIndex(index) {
  22598. return this._elements[index * 2 + 1];
  22599. }
  22600. getAverageValue() {
  22601. var total = 0;
  22602. for (var i = 0, n = this._currentLength - 2; i < n; i += 2) {
  22603. var subValue = this._elements[i + 1];
  22604. subValue += this._elements[i + 3];
  22605. subValue = subValue * (this._elements[i + 2] - this._elements[i]);
  22606. }
  22607. return total / 2;
  22608. }
  22609. cloneTo(destObject) {
  22610. var destGradientDataNumber = destObject;
  22611. destGradientDataNumber._currentLength = this._currentLength;
  22612. var destElements = destGradientDataNumber._elements;
  22613. for (var i = 0, n = this._elements.length; i < n; i++)
  22614. destElements[i] = this._elements[i];
  22615. }
  22616. clone() {
  22617. var destGradientDataNumber = new GradientDataNumber();
  22618. this.cloneTo(destGradientDataNumber);
  22619. return destGradientDataNumber;
  22620. }
  22621. }
  22622. class GradientSize {
  22623. constructor() {
  22624. this._type = 0;
  22625. this._separateAxes = false;
  22626. this._gradient = null;
  22627. this._gradientX = null;
  22628. this._gradientY = null;
  22629. this._gradientZ = null;
  22630. this._constantMin = 0;
  22631. this._constantMax = 0;
  22632. this._constantMinSeparate = null;
  22633. this._constantMaxSeparate = null;
  22634. this._gradientMin = null;
  22635. this._gradientMax = null;
  22636. this._gradientXMin = null;
  22637. this._gradientXMax = null;
  22638. this._gradientYMin = null;
  22639. this._gradientYMax = null;
  22640. this._gradientZMin = null;
  22641. this._gradientZMax = null;
  22642. }
  22643. static createByGradient(gradient) {
  22644. var gradientSize = new GradientSize();
  22645. gradientSize._type = 0;
  22646. gradientSize._separateAxes = false;
  22647. gradientSize._gradient = gradient;
  22648. return gradientSize;
  22649. }
  22650. static createByGradientSeparate(gradientX, gradientY, gradientZ) {
  22651. var gradientSize = new GradientSize();
  22652. gradientSize._type = 0;
  22653. gradientSize._separateAxes = true;
  22654. gradientSize._gradientX = gradientX;
  22655. gradientSize._gradientY = gradientY;
  22656. gradientSize._gradientZ = gradientZ;
  22657. return gradientSize;
  22658. }
  22659. static createByRandomTwoConstant(constantMin, constantMax) {
  22660. var gradientSize = new GradientSize();
  22661. gradientSize._type = 1;
  22662. gradientSize._separateAxes = false;
  22663. gradientSize._constantMin = constantMin;
  22664. gradientSize._constantMax = constantMax;
  22665. return gradientSize;
  22666. }
  22667. static createByRandomTwoConstantSeparate(constantMinSeparate, constantMaxSeparate) {
  22668. var gradientSize = new GradientSize();
  22669. gradientSize._type = 1;
  22670. gradientSize._separateAxes = true;
  22671. gradientSize._constantMinSeparate = constantMinSeparate;
  22672. gradientSize._constantMaxSeparate = constantMaxSeparate;
  22673. return gradientSize;
  22674. }
  22675. static createByRandomTwoGradient(gradientMin, gradientMax) {
  22676. var gradientSize = new GradientSize();
  22677. gradientSize._type = 2;
  22678. gradientSize._separateAxes = false;
  22679. gradientSize._gradientMin = gradientMin;
  22680. gradientSize._gradientMax = gradientMax;
  22681. return gradientSize;
  22682. }
  22683. static createByRandomTwoGradientSeparate(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax) {
  22684. var gradientSize = new GradientSize();
  22685. gradientSize._type = 2;
  22686. gradientSize._separateAxes = true;
  22687. gradientSize._gradientXMin = gradientXMin;
  22688. gradientSize._gradientXMax = gradientXMax;
  22689. gradientSize._gradientYMin = gradientYMin;
  22690. gradientSize._gradientYMax = gradientYMax;
  22691. gradientSize._gradientZMin = gradientZMin;
  22692. gradientSize._gradientZMax = gradientZMax;
  22693. return gradientSize;
  22694. }
  22695. get type() {
  22696. return this._type;
  22697. }
  22698. get separateAxes() {
  22699. return this._separateAxes;
  22700. }
  22701. get gradient() {
  22702. return this._gradient;
  22703. }
  22704. get gradientX() {
  22705. return this._gradientX;
  22706. }
  22707. get gradientY() {
  22708. return this._gradientY;
  22709. }
  22710. get gradientZ() {
  22711. return this._gradientZ;
  22712. }
  22713. get constantMin() {
  22714. return this._constantMin;
  22715. }
  22716. get constantMax() {
  22717. return this._constantMax;
  22718. }
  22719. get constantMinSeparate() {
  22720. return this._constantMinSeparate;
  22721. }
  22722. get constantMaxSeparate() {
  22723. return this._constantMaxSeparate;
  22724. }
  22725. get gradientMin() {
  22726. return this._gradientMin;
  22727. }
  22728. get gradientMax() {
  22729. return this._gradientMax;
  22730. }
  22731. get gradientXMin() {
  22732. return this._gradientXMin;
  22733. }
  22734. get gradientXMax() {
  22735. return this._gradientXMax;
  22736. }
  22737. get gradientYMin() {
  22738. return this._gradientYMin;
  22739. }
  22740. get gradientYMax() {
  22741. return this._gradientYMax;
  22742. }
  22743. get gradientZMin() {
  22744. return this._gradientZMin;
  22745. }
  22746. get gradientZMax() {
  22747. return this._gradientZMax;
  22748. }
  22749. getMaxSizeInGradient() {
  22750. var i, n;
  22751. var maxSize = -Number.MAX_VALUE;
  22752. switch (this._type) {
  22753. case 0:
  22754. if (this._separateAxes) {
  22755. for (i = 0, n = this._gradientX.gradientCount; i < n; i++)
  22756. maxSize = Math.max(maxSize, this._gradientX.getValueByIndex(i));
  22757. for (i = 0, n = this._gradientY.gradientCount; i < n; i++)
  22758. maxSize = Math.max(maxSize, this._gradientY.getValueByIndex(i));
  22759. }
  22760. else {
  22761. for (i = 0, n = this._gradient.gradientCount; i < n; i++)
  22762. maxSize = Math.max(maxSize, this._gradient.getValueByIndex(i));
  22763. }
  22764. break;
  22765. case 1:
  22766. if (this._separateAxes) {
  22767. maxSize = Math.max(this._constantMinSeparate.x, this._constantMaxSeparate.x);
  22768. maxSize = Math.max(maxSize, this._constantMinSeparate.y);
  22769. maxSize = Math.max(maxSize, this._constantMaxSeparate.y);
  22770. }
  22771. else {
  22772. maxSize = Math.max(this._constantMin, this._constantMax);
  22773. }
  22774. break;
  22775. case 2:
  22776. if (this._separateAxes) {
  22777. for (i = 0, n = this._gradientXMin.gradientCount; i < n; i++)
  22778. maxSize = Math.max(maxSize, this._gradientXMin.getValueByIndex(i));
  22779. for (i = 0, n = this._gradientXMax.gradientCount; i < n; i++)
  22780. maxSize = Math.max(maxSize, this._gradientXMax.getValueByIndex(i));
  22781. for (i = 0, n = this._gradientYMin.gradientCount; i < n; i++)
  22782. maxSize = Math.max(maxSize, this._gradientYMin.getValueByIndex(i));
  22783. for (i = 0, n = this._gradientZMax.gradientCount; i < n; i++)
  22784. maxSize = Math.max(maxSize, this._gradientZMax.getValueByIndex(i));
  22785. }
  22786. else {
  22787. for (i = 0, n = this._gradientMin.gradientCount; i < n; i++)
  22788. maxSize = Math.max(maxSize, this._gradientMin.getValueByIndex(i));
  22789. for (i = 0, n = this._gradientMax.gradientCount; i < n; i++)
  22790. maxSize = Math.max(maxSize, this._gradientMax.getValueByIndex(i));
  22791. }
  22792. break;
  22793. }
  22794. return maxSize;
  22795. }
  22796. cloneTo(destObject) {
  22797. var destGradientSize = destObject;
  22798. destGradientSize._type = this._type;
  22799. destGradientSize._separateAxes = this._separateAxes;
  22800. this._gradient.cloneTo(destGradientSize._gradient);
  22801. this._gradientX.cloneTo(destGradientSize._gradientX);
  22802. this._gradientY.cloneTo(destGradientSize._gradientY);
  22803. this._gradientZ.cloneTo(destGradientSize._gradientZ);
  22804. destGradientSize._constantMin = this._constantMin;
  22805. destGradientSize._constantMax = this._constantMax;
  22806. this._constantMinSeparate.cloneTo(destGradientSize._constantMinSeparate);
  22807. this._constantMaxSeparate.cloneTo(destGradientSize._constantMaxSeparate);
  22808. this._gradientMin.cloneTo(destGradientSize._gradientMin);
  22809. this._gradientMax.cloneTo(destGradientSize._gradientMax);
  22810. this._gradientXMin.cloneTo(destGradientSize._gradientXMin);
  22811. this._gradientXMax.cloneTo(destGradientSize._gradientXMax);
  22812. this._gradientYMin.cloneTo(destGradientSize._gradientYMin);
  22813. this._gradientYMax.cloneTo(destGradientSize._gradientYMax);
  22814. this._gradientZMin.cloneTo(destGradientSize._gradientZMin);
  22815. this._gradientZMax.cloneTo(destGradientSize._gradientZMax);
  22816. }
  22817. clone() {
  22818. var destGradientSize = new GradientSize();
  22819. this.cloneTo(destGradientSize);
  22820. return destGradientSize;
  22821. }
  22822. }
  22823. class GradientVelocity {
  22824. constructor() {
  22825. this._type = 0;
  22826. this._constant = null;
  22827. this._gradientX = null;
  22828. this._gradientY = null;
  22829. this._gradientZ = null;
  22830. this._constantMin = null;
  22831. this._constantMax = null;
  22832. this._gradientXMin = null;
  22833. this._gradientXMax = null;
  22834. this._gradientYMin = null;
  22835. this._gradientYMax = null;
  22836. this._gradientZMin = null;
  22837. this._gradientZMax = null;
  22838. }
  22839. static createByConstant(constant) {
  22840. var gradientVelocity = new GradientVelocity();
  22841. gradientVelocity._type = 0;
  22842. gradientVelocity._constant = constant;
  22843. return gradientVelocity;
  22844. }
  22845. static createByGradient(gradientX, gradientY, gradientZ) {
  22846. var gradientVelocity = new GradientVelocity();
  22847. gradientVelocity._type = 1;
  22848. gradientVelocity._gradientX = gradientX;
  22849. gradientVelocity._gradientY = gradientY;
  22850. gradientVelocity._gradientZ = gradientZ;
  22851. return gradientVelocity;
  22852. }
  22853. static createByRandomTwoConstant(constantMin, constantMax) {
  22854. var gradientVelocity = new GradientVelocity();
  22855. gradientVelocity._type = 2;
  22856. gradientVelocity._constantMin = constantMin;
  22857. gradientVelocity._constantMax = constantMax;
  22858. return gradientVelocity;
  22859. }
  22860. static createByRandomTwoGradient(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax) {
  22861. var gradientVelocity = new GradientVelocity();
  22862. gradientVelocity._type = 3;
  22863. gradientVelocity._gradientXMin = gradientXMin;
  22864. gradientVelocity._gradientXMax = gradientXMax;
  22865. gradientVelocity._gradientYMin = gradientYMin;
  22866. gradientVelocity._gradientYMax = gradientYMax;
  22867. gradientVelocity._gradientZMin = gradientZMin;
  22868. gradientVelocity._gradientZMax = gradientZMax;
  22869. return gradientVelocity;
  22870. }
  22871. get type() {
  22872. return this._type;
  22873. }
  22874. get constant() {
  22875. return this._constant;
  22876. }
  22877. get gradientX() {
  22878. return this._gradientX;
  22879. }
  22880. get gradientY() {
  22881. return this._gradientY;
  22882. }
  22883. get gradientZ() {
  22884. return this._gradientZ;
  22885. }
  22886. get constantMin() {
  22887. return this._constantMin;
  22888. }
  22889. get constantMax() {
  22890. return this._constantMax;
  22891. }
  22892. get gradientXMin() {
  22893. return this._gradientXMin;
  22894. }
  22895. get gradientXMax() {
  22896. return this._gradientXMax;
  22897. }
  22898. get gradientYMin() {
  22899. return this._gradientYMin;
  22900. }
  22901. get gradientYMax() {
  22902. return this._gradientYMax;
  22903. }
  22904. get gradientZMin() {
  22905. return this._gradientZMin;
  22906. }
  22907. get gradientZMax() {
  22908. return this._gradientZMax;
  22909. }
  22910. cloneTo(destObject) {
  22911. var destGradientVelocity = destObject;
  22912. destGradientVelocity._type = this._type;
  22913. this._constant.cloneTo(destGradientVelocity._constant);
  22914. this._gradientX.cloneTo(destGradientVelocity._gradientX);
  22915. this._gradientY.cloneTo(destGradientVelocity._gradientY);
  22916. this._gradientZ.cloneTo(destGradientVelocity._gradientZ);
  22917. this._constantMin.cloneTo(destGradientVelocity._constantMin);
  22918. this._constantMax.cloneTo(destGradientVelocity._constantMax);
  22919. this._gradientXMin.cloneTo(destGradientVelocity._gradientXMin);
  22920. this._gradientXMax.cloneTo(destGradientVelocity._gradientXMax);
  22921. this._gradientYMin.cloneTo(destGradientVelocity._gradientYMin);
  22922. this._gradientYMax.cloneTo(destGradientVelocity._gradientYMax);
  22923. this._gradientZMin.cloneTo(destGradientVelocity._gradientZMin);
  22924. this._gradientZMax.cloneTo(destGradientVelocity._gradientZMax);
  22925. }
  22926. clone() {
  22927. var destGradientVelocity = new GradientVelocity();
  22928. this.cloneTo(destGradientVelocity);
  22929. return destGradientVelocity;
  22930. }
  22931. }
  22932. class RotationOverLifetime {
  22933. constructor(angularVelocity) {
  22934. this._angularVelocity = angularVelocity;
  22935. }
  22936. get angularVelocity() {
  22937. return this._angularVelocity;
  22938. }
  22939. cloneTo(destObject) {
  22940. var destRotationOverLifetime = destObject;
  22941. this._angularVelocity.cloneTo(destRotationOverLifetime._angularVelocity);
  22942. destRotationOverLifetime.enable = this.enable;
  22943. }
  22944. clone() {
  22945. var destAngularVelocity;
  22946. switch (this._angularVelocity.type) {
  22947. case 0:
  22948. if (this._angularVelocity.separateAxes)
  22949. destAngularVelocity = GradientAngularVelocity.createByConstantSeparate(this._angularVelocity.constantSeparate.clone());
  22950. else
  22951. destAngularVelocity = GradientAngularVelocity.createByConstant(this._angularVelocity.constant);
  22952. break;
  22953. case 1:
  22954. if (this._angularVelocity.separateAxes)
  22955. destAngularVelocity = GradientAngularVelocity.createByGradientSeparate(this._angularVelocity.gradientX.clone(), this._angularVelocity.gradientY.clone(), this._angularVelocity.gradientZ.clone());
  22956. else
  22957. destAngularVelocity = GradientAngularVelocity.createByGradient(this._angularVelocity.gradient.clone());
  22958. break;
  22959. case 2:
  22960. if (this._angularVelocity.separateAxes)
  22961. destAngularVelocity = GradientAngularVelocity.createByRandomTwoConstantSeparate(this._angularVelocity.constantMinSeparate.clone(), this._angularVelocity.constantMaxSeparate.clone());
  22962. else
  22963. destAngularVelocity = GradientAngularVelocity.createByRandomTwoConstant(this._angularVelocity.constantMin, this._angularVelocity.constantMax);
  22964. break;
  22965. case 3:
  22966. if (this._angularVelocity.separateAxes)
  22967. 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());
  22968. else
  22969. destAngularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._angularVelocity.gradientMin.clone(), this._angularVelocity.gradientMax.clone());
  22970. break;
  22971. }
  22972. var destRotationOverLifetime = new RotationOverLifetime(destAngularVelocity);
  22973. destRotationOverLifetime.enable = this.enable;
  22974. return destRotationOverLifetime;
  22975. }
  22976. }
  22977. class BaseShape {
  22978. constructor() {
  22979. this.enable = true;
  22980. this.randomDirection = 0;
  22981. }
  22982. _getShapeBoundBox(boundBox) {
  22983. throw new Error("BaseShape: must override it.");
  22984. }
  22985. _getSpeedBoundBox(boundBox) {
  22986. throw new Error("BaseShape: must override it.");
  22987. }
  22988. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  22989. throw new Error("BaseShape: must override it.");
  22990. }
  22991. _calculateProceduralBounds(boundBox, emitterPosScale, minMaxBounds) {
  22992. this._getShapeBoundBox(boundBox);
  22993. var min = boundBox.min;
  22994. var max = boundBox.max;
  22995. Vector3.multiply(min, emitterPosScale, min);
  22996. Vector3.multiply(max, emitterPosScale, max);
  22997. var speedBounds = new BoundBox(new Vector3(), new Vector3());
  22998. if (this.randomDirection) {
  22999. speedBounds.min = new Vector3(-1, -1, -1);
  23000. speedBounds.max = new Vector3(1, 1, 1);
  23001. }
  23002. else {
  23003. this._getSpeedBoundBox(speedBounds);
  23004. }
  23005. var maxSpeedBound = new BoundBox(new Vector3(), new Vector3());
  23006. var maxSpeedMin = maxSpeedBound.min;
  23007. var maxSpeedMax = maxSpeedBound.max;
  23008. Vector3.scale(speedBounds.min, minMaxBounds.y, maxSpeedMin);
  23009. Vector3.scale(speedBounds.max, minMaxBounds.y, maxSpeedMax);
  23010. Vector3.add(boundBox.min, maxSpeedMin, maxSpeedMin);
  23011. Vector3.add(boundBox.max, maxSpeedMax, maxSpeedMax);
  23012. Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
  23013. Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
  23014. var minSpeedBound = new BoundBox(new Vector3(), new Vector3());
  23015. var minSpeedMin = minSpeedBound.min;
  23016. var minSpeedMax = minSpeedBound.max;
  23017. Vector3.scale(speedBounds.min, minMaxBounds.x, minSpeedMin);
  23018. Vector3.scale(speedBounds.max, minMaxBounds.x, minSpeedMax);
  23019. Vector3.min(minSpeedBound.min, minSpeedMax, maxSpeedMin);
  23020. Vector3.max(minSpeedBound.min, minSpeedMax, maxSpeedMax);
  23021. Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
  23022. Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
  23023. }
  23024. cloneTo(destObject) {
  23025. var destShape = destObject;
  23026. destShape.enable = this.enable;
  23027. }
  23028. clone() {
  23029. var destShape = new BaseShape();
  23030. this.cloneTo(destShape);
  23031. return destShape;
  23032. }
  23033. }
  23034. class ShapeUtils {
  23035. static _randomPointUnitArcCircle(arc, out, rand = null) {
  23036. var angle;
  23037. if (rand)
  23038. angle = rand.getFloat() * arc;
  23039. else
  23040. angle = Math.random() * arc;
  23041. out.x = Math.cos(angle);
  23042. out.y = Math.sin(angle);
  23043. }
  23044. static _randomPointInsideUnitArcCircle(arc, out, rand = null) {
  23045. ShapeUtils._randomPointUnitArcCircle(arc, out, rand);
  23046. var range;
  23047. if (rand)
  23048. range = Math.pow(rand.getFloat(), 1.0 / 2.0);
  23049. else
  23050. range = Math.pow(Math.random(), 1.0 / 2.0);
  23051. out.x = out.x * range;
  23052. out.y = out.y * range;
  23053. }
  23054. static _randomPointUnitCircle(out, rand = null) {
  23055. var angle;
  23056. if (rand)
  23057. angle = rand.getFloat() * Math.PI * 2;
  23058. else
  23059. angle = Math.random() * Math.PI * 2;
  23060. out.x = Math.cos(angle);
  23061. out.y = Math.sin(angle);
  23062. }
  23063. static _randomPointInsideUnitCircle(out, rand = null) {
  23064. ShapeUtils._randomPointUnitCircle(out);
  23065. var range;
  23066. if (rand)
  23067. range = Math.pow(rand.getFloat(), 1.0 / 2.0);
  23068. else
  23069. range = Math.pow(Math.random(), 1.0 / 2.0);
  23070. out.x = out.x * range;
  23071. out.y = out.y * range;
  23072. }
  23073. static _randomPointUnitSphere(out, rand = null) {
  23074. var z;
  23075. var a;
  23076. if (rand) {
  23077. z = out.z = rand.getFloat() * 2 - 1.0;
  23078. a = rand.getFloat() * Math.PI * 2;
  23079. }
  23080. else {
  23081. z = out.z = Math.random() * 2 - 1.0;
  23082. a = Math.random() * Math.PI * 2;
  23083. }
  23084. var r = Math.sqrt(1.0 - z * z);
  23085. out.x = r * Math.cos(a);
  23086. out.y = r * Math.sin(a);
  23087. }
  23088. static _randomPointInsideUnitSphere(out, rand = null) {
  23089. ShapeUtils._randomPointUnitSphere(out);
  23090. var range;
  23091. if (rand)
  23092. range = Math.pow(rand.getFloat(), 1.0 / 3.0);
  23093. else
  23094. range = Math.pow(Math.random(), 1.0 / 3.0);
  23095. out.x = out.x * range;
  23096. out.y = out.y * range;
  23097. out.z = out.z * range;
  23098. }
  23099. static _randomPointInsideHalfUnitBox(out, rand = null) {
  23100. if (rand) {
  23101. out.x = (rand.getFloat() - 0.5);
  23102. out.y = (rand.getFloat() - 0.5);
  23103. out.z = (rand.getFloat() - 0.5);
  23104. }
  23105. else {
  23106. out.x = (Math.random() - 0.5);
  23107. out.y = (Math.random() - 0.5);
  23108. out.z = (Math.random() - 0.5);
  23109. }
  23110. }
  23111. constructor() {
  23112. }
  23113. }
  23114. class BoxShape extends BaseShape {
  23115. constructor() {
  23116. super();
  23117. this.x = 1.0;
  23118. this.y = 1.0;
  23119. this.z = 1.0;
  23120. }
  23121. _getShapeBoundBox(boundBox) {
  23122. var min = boundBox.min;
  23123. min.x = -this.x * 0.5;
  23124. min.y = -this.y * 0.5;
  23125. min.z = -this.z * 0.5;
  23126. var max = boundBox.max;
  23127. max.x = this.x * 0.5;
  23128. max.y = this.y * 0.5;
  23129. max.z = this.z * 0.5;
  23130. }
  23131. _getSpeedBoundBox(boundBox) {
  23132. var min = boundBox.min;
  23133. min.x = 0.0;
  23134. min.y = 0.0;
  23135. min.z = 0.0;
  23136. var max = boundBox.max;
  23137. max.x = 0.0;
  23138. max.y = 1.0;
  23139. max.z = 0.0;
  23140. }
  23141. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  23142. if (rand) {
  23143. rand.seed = randomSeeds[16];
  23144. ShapeUtils._randomPointInsideHalfUnitBox(position, rand);
  23145. randomSeeds[16] = rand.seed;
  23146. }
  23147. else {
  23148. ShapeUtils._randomPointInsideHalfUnitBox(position);
  23149. }
  23150. position.x = this.x * position.x;
  23151. position.y = this.y * position.y;
  23152. position.z = this.z * position.z;
  23153. if (this.randomDirection) {
  23154. if (rand) {
  23155. rand.seed = randomSeeds[17];
  23156. ShapeUtils._randomPointUnitSphere(direction, rand);
  23157. randomSeeds[17] = rand.seed;
  23158. }
  23159. else {
  23160. ShapeUtils._randomPointUnitSphere(direction);
  23161. }
  23162. }
  23163. else {
  23164. direction.x = 0.0;
  23165. direction.y = 0.0;
  23166. direction.z = 1.0;
  23167. }
  23168. }
  23169. cloneTo(destObject) {
  23170. super.cloneTo(destObject);
  23171. var destShape = destObject;
  23172. destShape.x = this.x;
  23173. destShape.y = this.y;
  23174. destShape.z = this.z;
  23175. destShape.randomDirection = this.randomDirection;
  23176. }
  23177. clone() {
  23178. var destShape = new BoxShape();
  23179. this.cloneTo(destShape);
  23180. return destShape;
  23181. }
  23182. }
  23183. class CircleShape extends BaseShape {
  23184. constructor() {
  23185. super();
  23186. this.radius = 1.0;
  23187. this.arc = 360.0 / 180.0 * Math.PI;
  23188. this.emitFromEdge = false;
  23189. }
  23190. _getShapeBoundBox(boundBox) {
  23191. var min = boundBox.min;
  23192. min.x = min.z = -this.radius;
  23193. min.y = 0;
  23194. var max = boundBox.max;
  23195. max.x = max.z = this.radius;
  23196. max.y = 0;
  23197. }
  23198. _getSpeedBoundBox(boundBox) {
  23199. var min = boundBox.min;
  23200. min.x = min.y = -1;
  23201. min.z = 0;
  23202. var max = boundBox.max;
  23203. max.x = max.y = 1;
  23204. max.z = 0;
  23205. }
  23206. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  23207. var positionPoint = CircleShape._tempPositionPoint;
  23208. if (rand) {
  23209. rand.seed = randomSeeds[16];
  23210. if (this.emitFromEdge)
  23211. ShapeUtils._randomPointUnitArcCircle(this.arc, CircleShape._tempPositionPoint, rand);
  23212. else
  23213. ShapeUtils._randomPointInsideUnitArcCircle(this.arc, CircleShape._tempPositionPoint, rand);
  23214. randomSeeds[16] = rand.seed;
  23215. }
  23216. else {
  23217. if (this.emitFromEdge)
  23218. ShapeUtils._randomPointUnitArcCircle(this.arc, CircleShape._tempPositionPoint);
  23219. else
  23220. ShapeUtils._randomPointInsideUnitArcCircle(this.arc, CircleShape._tempPositionPoint);
  23221. }
  23222. position.x = -positionPoint.x;
  23223. position.y = positionPoint.y;
  23224. position.z = 0;
  23225. Vector3.scale(position, this.radius, position);
  23226. if (this.randomDirection) {
  23227. if (rand) {
  23228. rand.seed = randomSeeds[17];
  23229. ShapeUtils._randomPointUnitSphere(direction, rand);
  23230. randomSeeds[17] = rand.seed;
  23231. }
  23232. else {
  23233. ShapeUtils._randomPointUnitSphere(direction);
  23234. }
  23235. }
  23236. else {
  23237. position.cloneTo(direction);
  23238. }
  23239. }
  23240. cloneTo(destObject) {
  23241. super.cloneTo(destObject);
  23242. var destShape = destObject;
  23243. destShape.radius = this.radius;
  23244. destShape.arc = this.arc;
  23245. destShape.emitFromEdge = this.emitFromEdge;
  23246. destShape.randomDirection = this.randomDirection;
  23247. }
  23248. clone() {
  23249. var destShape = new CircleShape();
  23250. this.cloneTo(destShape);
  23251. return destShape;
  23252. }
  23253. }
  23254. CircleShape._tempPositionPoint = new Vector2();
  23255. class ConeShape extends BaseShape {
  23256. constructor() {
  23257. super();
  23258. this.angle = 25.0 / 180.0 * Math.PI;
  23259. this.radius = 1.0;
  23260. this.length = 5.0;
  23261. this.emitType = 0;
  23262. }
  23263. _getShapeBoundBox(boundBox) {
  23264. const coneRadius2 = this.radius + this.length * Math.sin(this.angle);
  23265. const coneLength = this.length * Math.cos(this.angle);
  23266. var min = boundBox.min;
  23267. min.x = min.y = -coneRadius2;
  23268. min.z = 0;
  23269. var max = boundBox.max;
  23270. max.x = max.y = coneRadius2;
  23271. max.z = coneLength;
  23272. }
  23273. _getSpeedBoundBox(boundBox) {
  23274. const sinA = Math.sin(this.angle);
  23275. var min = boundBox.min;
  23276. min.x = min.y = -sinA;
  23277. min.z = 0;
  23278. var max = boundBox.max;
  23279. max.x = max.y = sinA;
  23280. max.z = 1;
  23281. }
  23282. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  23283. var positionPointE = ConeShape._tempPositionPoint;
  23284. var positionX;
  23285. var positionY;
  23286. var directionPointE;
  23287. var dirCosA = Math.cos(this.angle);
  23288. var dirSinA = Math.sin(this.angle);
  23289. switch (this.emitType) {
  23290. case 0:
  23291. if (rand) {
  23292. rand.seed = randomSeeds[16];
  23293. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint, rand);
  23294. randomSeeds[16] = rand.seed;
  23295. }
  23296. else {
  23297. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint);
  23298. }
  23299. positionX = positionPointE.x;
  23300. positionY = positionPointE.y;
  23301. position.x = positionX * this.radius;
  23302. position.y = positionY * this.radius;
  23303. position.z = 0;
  23304. if (this.randomDirection) {
  23305. if (rand) {
  23306. rand.seed = randomSeeds[17];
  23307. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint, rand);
  23308. randomSeeds[17] = rand.seed;
  23309. }
  23310. else {
  23311. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint);
  23312. }
  23313. directionPointE = ConeShape._tempDirectionPoint;
  23314. direction.x = directionPointE.x * dirSinA;
  23315. direction.y = directionPointE.y * dirSinA;
  23316. }
  23317. else {
  23318. direction.x = positionX * dirSinA;
  23319. direction.y = positionY * dirSinA;
  23320. }
  23321. direction.z = dirCosA;
  23322. break;
  23323. case 1:
  23324. if (rand) {
  23325. rand.seed = randomSeeds[16];
  23326. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint, rand);
  23327. randomSeeds[16] = rand.seed;
  23328. }
  23329. else {
  23330. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint);
  23331. }
  23332. positionX = positionPointE.x;
  23333. positionY = positionPointE.y;
  23334. position.x = positionX * this.radius;
  23335. position.y = positionY * this.radius;
  23336. position.z = 0;
  23337. if (this.randomDirection) {
  23338. if (rand) {
  23339. rand.seed = randomSeeds[17];
  23340. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint, rand);
  23341. randomSeeds[17] = rand.seed;
  23342. }
  23343. else {
  23344. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint);
  23345. }
  23346. directionPointE = ConeShape._tempDirectionPoint;
  23347. direction.x = directionPointE.x * dirSinA;
  23348. direction.y = directionPointE.y * dirSinA;
  23349. }
  23350. else {
  23351. direction.x = positionX * dirSinA;
  23352. direction.y = positionY * dirSinA;
  23353. }
  23354. direction.z = dirCosA;
  23355. break;
  23356. case 2:
  23357. if (rand) {
  23358. rand.seed = randomSeeds[16];
  23359. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint, rand);
  23360. }
  23361. else {
  23362. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint);
  23363. }
  23364. positionX = positionPointE.x;
  23365. positionY = positionPointE.y;
  23366. position.x = positionX * this.radius;
  23367. position.y = positionY * this.radius;
  23368. position.z = 0;
  23369. direction.x = positionX * dirSinA;
  23370. direction.y = positionY * dirSinA;
  23371. direction.z = dirCosA;
  23372. Vector3.normalize(direction, direction);
  23373. if (rand) {
  23374. Vector3.scale(direction, this.length * rand.getFloat(), direction);
  23375. randomSeeds[16] = rand.seed;
  23376. }
  23377. else {
  23378. Vector3.scale(direction, this.length * Math.random(), direction);
  23379. }
  23380. Vector3.add(position, direction, position);
  23381. if (this.randomDirection) {
  23382. if (rand) {
  23383. rand.seed = randomSeeds[17];
  23384. ShapeUtils._randomPointUnitSphere(direction, rand);
  23385. randomSeeds[17] = rand.seed;
  23386. }
  23387. else {
  23388. ShapeUtils._randomPointUnitSphere(direction);
  23389. }
  23390. }
  23391. break;
  23392. case 3:
  23393. if (rand) {
  23394. rand.seed = randomSeeds[16];
  23395. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint, rand);
  23396. }
  23397. else {
  23398. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint);
  23399. }
  23400. positionX = positionPointE.x;
  23401. positionY = positionPointE.y;
  23402. position.x = positionX * this.radius;
  23403. position.y = positionY * this.radius;
  23404. position.z = 0;
  23405. direction.x = positionX * dirSinA;
  23406. direction.y = positionY * dirSinA;
  23407. direction.z = dirCosA;
  23408. Vector3.normalize(direction, direction);
  23409. if (rand) {
  23410. Vector3.scale(direction, this.length * rand.getFloat(), direction);
  23411. randomSeeds[16] = rand.seed;
  23412. }
  23413. else {
  23414. Vector3.scale(direction, this.length * Math.random(), direction);
  23415. }
  23416. Vector3.add(position, direction, position);
  23417. if (this.randomDirection) {
  23418. if (rand) {
  23419. rand.seed = randomSeeds[17];
  23420. ShapeUtils._randomPointUnitSphere(direction, rand);
  23421. randomSeeds[17] = rand.seed;
  23422. }
  23423. else {
  23424. ShapeUtils._randomPointUnitSphere(direction);
  23425. }
  23426. }
  23427. break;
  23428. default:
  23429. throw new Error("ConeShape:emitType is invalid.");
  23430. }
  23431. }
  23432. cloneTo(destObject) {
  23433. super.cloneTo(destObject);
  23434. var destShape = destObject;
  23435. destShape.angle = this.angle;
  23436. destShape.radius = this.radius;
  23437. destShape.length = this.length;
  23438. destShape.emitType = this.emitType;
  23439. destShape.randomDirection = this.randomDirection;
  23440. }
  23441. clone() {
  23442. var destShape = new ConeShape();
  23443. this.cloneTo(destShape);
  23444. return destShape;
  23445. }
  23446. }
  23447. ConeShape._tempPositionPoint = new Vector2();
  23448. ConeShape._tempDirectionPoint = new Vector2();
  23449. class HemisphereShape extends BaseShape {
  23450. constructor() {
  23451. super();
  23452. this.radius = 1.0;
  23453. this.emitFromShell = false;
  23454. }
  23455. _getShapeBoundBox(boundBox) {
  23456. var min = boundBox.min;
  23457. min.x = min.y = min.z = -this.radius;
  23458. var max = boundBox.max;
  23459. max.x = max.y = this.radius;
  23460. max.z = 0;
  23461. }
  23462. _getSpeedBoundBox(boundBox) {
  23463. var min = boundBox.min;
  23464. min.x = min.y = -1;
  23465. min.z = 0;
  23466. var max = boundBox.max;
  23467. max.x = max.y = max.z = 1;
  23468. }
  23469. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  23470. if (rand) {
  23471. rand.seed = randomSeeds[16];
  23472. if (this.emitFromShell)
  23473. ShapeUtils._randomPointUnitSphere(position, rand);
  23474. else
  23475. ShapeUtils._randomPointInsideUnitSphere(position, rand);
  23476. randomSeeds[16] = rand.seed;
  23477. }
  23478. else {
  23479. if (this.emitFromShell)
  23480. ShapeUtils._randomPointUnitSphere(position);
  23481. else
  23482. ShapeUtils._randomPointInsideUnitSphere(position);
  23483. }
  23484. Vector3.scale(position, this.radius, position);
  23485. var z = position.z;
  23486. (z < 0.0) && (position.z = z * -1.0);
  23487. if (this.randomDirection) {
  23488. if (rand) {
  23489. rand.seed = randomSeeds[17];
  23490. ShapeUtils._randomPointUnitSphere(direction, rand);
  23491. randomSeeds[17] = rand.seed;
  23492. }
  23493. else {
  23494. ShapeUtils._randomPointUnitSphere(direction);
  23495. }
  23496. }
  23497. else {
  23498. position.cloneTo(direction);
  23499. }
  23500. }
  23501. cloneTo(destObject) {
  23502. super.cloneTo(destObject);
  23503. var destShape = destObject;
  23504. destShape.radius = this.radius;
  23505. destShape.emitFromShell = this.emitFromShell;
  23506. destShape.randomDirection = this.randomDirection;
  23507. }
  23508. clone() {
  23509. var destShape = new HemisphereShape();
  23510. this.cloneTo(destShape);
  23511. return destShape;
  23512. }
  23513. }
  23514. class SphereShape extends BaseShape {
  23515. constructor() {
  23516. super();
  23517. this.radius = 1.0;
  23518. this.emitFromShell = false;
  23519. }
  23520. _getShapeBoundBox(boundBox) {
  23521. var min = boundBox.min;
  23522. min.x = min.y = min.z = -this.radius;
  23523. var max = boundBox.max;
  23524. max.x = max.y = max.z = this.radius;
  23525. }
  23526. _getSpeedBoundBox(boundBox) {
  23527. var min = boundBox.min;
  23528. min.x = min.y = min.z = -1;
  23529. var max = boundBox.max;
  23530. max.x = max.y = max.z = 1;
  23531. }
  23532. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  23533. if (rand) {
  23534. rand.seed = randomSeeds[16];
  23535. if (this.emitFromShell)
  23536. ShapeUtils._randomPointUnitSphere(position, rand);
  23537. else
  23538. ShapeUtils._randomPointInsideUnitSphere(position, rand);
  23539. randomSeeds[16] = rand.seed;
  23540. }
  23541. else {
  23542. if (this.emitFromShell)
  23543. ShapeUtils._randomPointUnitSphere(position);
  23544. else
  23545. ShapeUtils._randomPointInsideUnitSphere(position);
  23546. }
  23547. Vector3.scale(position, this.radius, position);
  23548. if (this.randomDirection) {
  23549. if (rand) {
  23550. rand.seed = randomSeeds[17];
  23551. ShapeUtils._randomPointUnitSphere(direction, rand);
  23552. randomSeeds[17] = rand.seed;
  23553. }
  23554. else {
  23555. ShapeUtils._randomPointUnitSphere(direction);
  23556. }
  23557. }
  23558. else {
  23559. position.cloneTo(direction);
  23560. }
  23561. }
  23562. cloneTo(destObject) {
  23563. super.cloneTo(destObject);
  23564. var destShape = destObject;
  23565. destShape.radius = this.radius;
  23566. destShape.emitFromShell = this.emitFromShell;
  23567. destShape.randomDirection = this.randomDirection;
  23568. }
  23569. clone() {
  23570. var destShape = new SphereShape();
  23571. this.cloneTo(destShape);
  23572. return destShape;
  23573. }
  23574. }
  23575. class SizeOverLifetime {
  23576. constructor(size) {
  23577. this._size = size;
  23578. }
  23579. get size() {
  23580. return this._size;
  23581. }
  23582. cloneTo(destObject) {
  23583. var destSizeOverLifetime = destObject;
  23584. this._size.cloneTo(destSizeOverLifetime._size);
  23585. destSizeOverLifetime.enable = this.enable;
  23586. }
  23587. clone() {
  23588. var destSize;
  23589. switch (this._size.type) {
  23590. case 0:
  23591. if (this._size.separateAxes)
  23592. destSize = GradientSize.createByGradientSeparate(this._size.gradientX.clone(), this._size.gradientY.clone(), this._size.gradientZ.clone());
  23593. else
  23594. destSize = GradientSize.createByGradient(this._size.gradient.clone());
  23595. break;
  23596. case 1:
  23597. if (this._size.separateAxes)
  23598. destSize = GradientSize.createByRandomTwoConstantSeparate(this._size.constantMinSeparate.clone(), this._size.constantMaxSeparate.clone());
  23599. else
  23600. destSize = GradientSize.createByRandomTwoConstant(this._size.constantMin, this._size.constantMax);
  23601. break;
  23602. case 2:
  23603. if (this._size.separateAxes)
  23604. 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());
  23605. else
  23606. destSize = GradientSize.createByRandomTwoGradient(this._size.gradientMin.clone(), this._size.gradientMax.clone());
  23607. break;
  23608. }
  23609. var destSizeOverLifetime = new SizeOverLifetime(destSize);
  23610. destSizeOverLifetime.enable = this.enable;
  23611. return destSizeOverLifetime;
  23612. }
  23613. }
  23614. class StartFrame {
  23615. constructor() {
  23616. this._type = 0;
  23617. this._constant = 0;
  23618. this._constantMin = 0;
  23619. this._constantMax = 0;
  23620. }
  23621. static createByConstant(constant = 0) {
  23622. var rotationOverLifetime = new StartFrame();
  23623. rotationOverLifetime._type = 0;
  23624. rotationOverLifetime._constant = constant;
  23625. return rotationOverLifetime;
  23626. }
  23627. static createByRandomTwoConstant(constantMin = 0, constantMax = 0) {
  23628. var rotationOverLifetime = new StartFrame();
  23629. rotationOverLifetime._type = 1;
  23630. rotationOverLifetime._constantMin = constantMin;
  23631. rotationOverLifetime._constantMax = constantMax;
  23632. return rotationOverLifetime;
  23633. }
  23634. get type() {
  23635. return this._type;
  23636. }
  23637. get constant() {
  23638. return this._constant;
  23639. }
  23640. get constantMin() {
  23641. return this._constantMin;
  23642. }
  23643. get constantMax() {
  23644. return this._constantMax;
  23645. }
  23646. cloneTo(destObject) {
  23647. var destStartFrame = destObject;
  23648. destStartFrame._type = this._type;
  23649. destStartFrame._constant = this._constant;
  23650. destStartFrame._constantMin = this._constantMin;
  23651. destStartFrame._constantMax = this._constantMax;
  23652. }
  23653. clone() {
  23654. var destStartFrame = new StartFrame();
  23655. this.cloneTo(destStartFrame);
  23656. return destStartFrame;
  23657. }
  23658. }
  23659. class TextureSheetAnimation {
  23660. constructor(frame, startFrame) {
  23661. this.type = 0;
  23662. this.randomRow = false;
  23663. this.rowIndex = 0;
  23664. this.cycles = 0;
  23665. this.enableUVChannels = 0;
  23666. this.enable = false;
  23667. this.tiles = new Vector2(1, 1);
  23668. this.type = 0;
  23669. this.randomRow = true;
  23670. this.rowIndex = 0;
  23671. this.cycles = 1;
  23672. this.enableUVChannels = 1;
  23673. this._frame = frame;
  23674. this._startFrame = startFrame;
  23675. }
  23676. get frame() {
  23677. return this._frame;
  23678. }
  23679. get startFrame() {
  23680. return this._startFrame;
  23681. }
  23682. cloneTo(destObject) {
  23683. var destTextureSheetAnimation = destObject;
  23684. this.tiles.cloneTo(destTextureSheetAnimation.tiles);
  23685. destTextureSheetAnimation.type = this.type;
  23686. destTextureSheetAnimation.randomRow = this.randomRow;
  23687. destTextureSheetAnimation.rowIndex = this.rowIndex;
  23688. destTextureSheetAnimation.cycles = this.cycles;
  23689. destTextureSheetAnimation.enableUVChannels = this.enableUVChannels;
  23690. destTextureSheetAnimation.enable = this.enable;
  23691. this._frame.cloneTo(destTextureSheetAnimation._frame);
  23692. this._startFrame.cloneTo(destTextureSheetAnimation._startFrame);
  23693. }
  23694. clone() {
  23695. var destFrame;
  23696. switch (this._frame.type) {
  23697. case 0:
  23698. destFrame = FrameOverTime.createByConstant(this._frame.constant);
  23699. break;
  23700. case 1:
  23701. destFrame = FrameOverTime.createByOverTime(this._frame.frameOverTimeData.clone());
  23702. break;
  23703. case 2:
  23704. destFrame = FrameOverTime.createByRandomTwoConstant(this._frame.constantMin, this._frame.constantMax);
  23705. break;
  23706. case 3:
  23707. destFrame = FrameOverTime.createByRandomTwoOverTime(this._frame.frameOverTimeDataMin.clone(), this._frame.frameOverTimeDataMax.clone());
  23708. break;
  23709. }
  23710. var destStartFrame;
  23711. switch (this._startFrame.type) {
  23712. case 0:
  23713. destStartFrame = StartFrame.createByConstant(this._startFrame.constant);
  23714. break;
  23715. case 1:
  23716. destStartFrame = StartFrame.createByRandomTwoConstant(this._startFrame.constantMin, this._startFrame.constantMax);
  23717. break;
  23718. }
  23719. var destTextureSheetAnimation = new TextureSheetAnimation(destFrame, destStartFrame);
  23720. this.cloneTo(destTextureSheetAnimation);
  23721. return destTextureSheetAnimation;
  23722. }
  23723. }
  23724. class VelocityOverLifetime {
  23725. constructor(velocity) {
  23726. this.enable = false;
  23727. this.space = 0;
  23728. this._velocity = velocity;
  23729. }
  23730. get velocity() {
  23731. return this._velocity;
  23732. }
  23733. cloneTo(destObject) {
  23734. var destVelocityOverLifetime = destObject;
  23735. this._velocity.cloneTo(destVelocityOverLifetime._velocity);
  23736. destVelocityOverLifetime.enable = this.enable;
  23737. destVelocityOverLifetime.space = this.space;
  23738. }
  23739. clone() {
  23740. var destVelocity;
  23741. switch (this._velocity.type) {
  23742. case 0:
  23743. destVelocity = GradientVelocity.createByConstant(this._velocity.constant.clone());
  23744. break;
  23745. case 1:
  23746. destVelocity = GradientVelocity.createByGradient(this._velocity.gradientX.clone(), this._velocity.gradientY.clone(), this._velocity.gradientZ.clone());
  23747. break;
  23748. case 2:
  23749. destVelocity = GradientVelocity.createByRandomTwoConstant(this._velocity.constantMin.clone(), this._velocity.constantMax.clone());
  23750. break;
  23751. case 3:
  23752. 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());
  23753. break;
  23754. }
  23755. var destVelocityOverLifetime = new VelocityOverLifetime(destVelocity);
  23756. destVelocityOverLifetime.enable = this.enable;
  23757. destVelocityOverLifetime.space = this.space;
  23758. return destVelocityOverLifetime;
  23759. }
  23760. }
  23761. class ShuriKenParticle3DShaderDeclaration {
  23762. }
  23763. ShuriKenParticle3DShaderDeclaration.WORLDPOSITION = Shader3D.propertyNameToID("u_WorldPosition");
  23764. ShuriKenParticle3DShaderDeclaration.WORLDROTATION = Shader3D.propertyNameToID("u_WorldRotation");
  23765. ShuriKenParticle3DShaderDeclaration.POSITIONSCALE = Shader3D.propertyNameToID("u_PositionScale");
  23766. ShuriKenParticle3DShaderDeclaration.SIZESCALE = Shader3D.propertyNameToID("u_SizeScale");
  23767. ShuriKenParticle3DShaderDeclaration.SCALINGMODE = Shader3D.propertyNameToID("u_ScalingMode");
  23768. ShuriKenParticle3DShaderDeclaration.GRAVITY = Shader3D.propertyNameToID("u_Gravity");
  23769. ShuriKenParticle3DShaderDeclaration.THREEDSTARTROTATION = Shader3D.propertyNameToID("u_ThreeDStartRotation");
  23770. ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDLENGTHSCALE = Shader3D.propertyNameToID("u_StretchedBillboardLengthScale");
  23771. ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDSPEEDSCALE = Shader3D.propertyNameToID("u_StretchedBillboardSpeedScale");
  23772. ShuriKenParticle3DShaderDeclaration.SIMULATIONSPACE = Shader3D.propertyNameToID("u_SimulationSpace");
  23773. ShuriKenParticle3DShaderDeclaration.CURRENTTIME = Shader3D.propertyNameToID("u_CurrentTime");
  23774. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST = Shader3D.propertyNameToID("u_VOLVelocityConst");
  23775. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX = Shader3D.propertyNameToID("u_VOLVelocityGradientX");
  23776. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY = Shader3D.propertyNameToID("u_VOLVelocityGradientY");
  23777. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ = Shader3D.propertyNameToID("u_VOLVelocityGradientZ");
  23778. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONSTMAX = Shader3D.propertyNameToID("u_VOLVelocityConstMax");
  23779. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTXMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxX");
  23780. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTYMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxY");
  23781. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxZ");
  23782. ShuriKenParticle3DShaderDeclaration.VOLSPACETYPE = Shader3D.propertyNameToID("u_VOLSpaceType");
  23783. ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS = Shader3D.propertyNameToID("u_ColorOverLifeGradientAlphas");
  23784. ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS = Shader3D.propertyNameToID("u_ColorOverLifeGradientColors");
  23785. ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS = Shader3D.propertyNameToID("u_MaxColorOverLifeGradientAlphas");
  23786. ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS = Shader3D.propertyNameToID("u_MaxColorOverLifeGradientColors");
  23787. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT = Shader3D.propertyNameToID("u_SOLSizeGradient");
  23788. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX = Shader3D.propertyNameToID("u_SOLSizeGradientX");
  23789. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY = Shader3D.propertyNameToID("u_SOLSizeGradientY");
  23790. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ = Shader3D.propertyNameToID("u_SOLSizeGradientZ");
  23791. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientMax = Shader3D.propertyNameToID("u_SOLSizeGradientMax");
  23792. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTXMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxX");
  23793. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTYMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxY");
  23794. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxZ");
  23795. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST = Shader3D.propertyNameToID("u_ROLAngularVelocityConst");
  23796. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE = Shader3D.propertyNameToID("u_ROLAngularVelocityConstSeprarate");
  23797. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT = Shader3D.propertyNameToID("u_ROLAngularVelocityGradient");
  23798. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientX");
  23799. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientY");
  23800. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientZ");
  23801. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityConstMax");
  23802. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAXSEPRARATE = Shader3D.propertyNameToID("u_ROLAngularVelocityConstMaxSeprarate");
  23803. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMax");
  23804. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTXMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxX");
  23805. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTYMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxY");
  23806. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxZ");
  23807. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTWMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxW");
  23808. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONCYCLES = Shader3D.propertyNameToID("u_TSACycles");
  23809. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONSUBUVLENGTH = Shader3D.propertyNameToID("u_TSASubUVLength");
  23810. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS = Shader3D.propertyNameToID("u_TSAGradientUVs");
  23811. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTMAXUVS = Shader3D.propertyNameToID("u_TSAMaxGradientUVs");
  23812. class ShurikenParticleMaterial extends Material {
  23813. constructor() {
  23814. super();
  23815. this.setShaderName("PARTICLESHURIKEN");
  23816. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  23817. this.renderMode = ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED;
  23818. }
  23819. static __initDefine__() {
  23820. ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP = Shader3D.getDefineByName("DIFFUSEMAP");
  23821. ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR = Shader3D.getDefineByName("TINTCOLOR");
  23822. ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  23823. ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  23824. }
  23825. get _TintColorR() {
  23826. return this._color.x;
  23827. }
  23828. set _TintColorR(value) {
  23829. this._color.x = value;
  23830. this.color = this._color;
  23831. }
  23832. get _TintColorG() {
  23833. return this._color.y;
  23834. }
  23835. set _TintColorG(value) {
  23836. this._color.y = value;
  23837. this.color = this._color;
  23838. }
  23839. get _TintColorB() {
  23840. return this._color.z;
  23841. }
  23842. set _TintColorB(value) {
  23843. this._color.z = value;
  23844. this.color = this._color;
  23845. }
  23846. get _TintColorA() {
  23847. return this._color.w;
  23848. }
  23849. set _TintColorA(value) {
  23850. this._color.w = value;
  23851. this.color = this._color;
  23852. }
  23853. get _MainTex_STX() {
  23854. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).x;
  23855. }
  23856. set _MainTex_STX(x) {
  23857. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23858. tilOff.x = x;
  23859. this.tilingOffset = tilOff;
  23860. }
  23861. get _MainTex_STY() {
  23862. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).y;
  23863. }
  23864. set _MainTex_STY(y) {
  23865. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23866. tilOff.y = y;
  23867. this.tilingOffset = tilOff;
  23868. }
  23869. get _MainTex_STZ() {
  23870. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).z;
  23871. }
  23872. set _MainTex_STZ(z) {
  23873. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23874. tilOff.z = z;
  23875. this.tilingOffset = tilOff;
  23876. }
  23877. get _MainTex_STW() {
  23878. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).w;
  23879. }
  23880. set _MainTex_STW(w) {
  23881. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23882. tilOff.w = w;
  23883. this.tilingOffset = tilOff;
  23884. }
  23885. set renderMode(value) {
  23886. switch (value) {
  23887. case ShurikenParticleMaterial.RENDERMODE_ADDTIVE:
  23888. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  23889. this.depthWrite = false;
  23890. this.cull = RenderState.CULL_NONE;
  23891. this.blend = RenderState.BLEND_ENABLE_ALL;
  23892. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  23893. this.blendDst = RenderState.BLENDPARAM_ONE;
  23894. this.alphaTest = false;
  23895. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG);
  23896. break;
  23897. case ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED:
  23898. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  23899. this.depthWrite = false;
  23900. this.cull = RenderState.CULL_NONE;
  23901. this.blend = RenderState.BLEND_ENABLE_ALL;
  23902. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  23903. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  23904. this.alphaTest = false;
  23905. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG);
  23906. break;
  23907. default:
  23908. throw new Error("ShurikenParticleMaterial : renderMode value error.");
  23909. }
  23910. }
  23911. get colorR() {
  23912. return this._TintColorR;
  23913. }
  23914. set colorR(value) {
  23915. this._TintColorR = value;
  23916. }
  23917. get colorG() {
  23918. return this._TintColorG;
  23919. }
  23920. set colorG(value) {
  23921. this._TintColorG = value;
  23922. }
  23923. get colorB() {
  23924. return this._TintColorB;
  23925. }
  23926. set colorB(value) {
  23927. this._TintColorB = value;
  23928. }
  23929. get colorA() {
  23930. return this._TintColorA;
  23931. }
  23932. set colorA(value) {
  23933. this._TintColorA = value;
  23934. }
  23935. get color() {
  23936. return this._shaderValues.getVector(ShurikenParticleMaterial.TINTCOLOR);
  23937. }
  23938. set color(value) {
  23939. if (value)
  23940. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR);
  23941. else
  23942. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR);
  23943. this._shaderValues.setVector(ShurikenParticleMaterial.TINTCOLOR, value);
  23944. }
  23945. get tilingOffsetX() {
  23946. return this._MainTex_STX;
  23947. }
  23948. set tilingOffsetX(x) {
  23949. this._MainTex_STX = x;
  23950. }
  23951. get tilingOffsetY() {
  23952. return this._MainTex_STY;
  23953. }
  23954. set tilingOffsetY(y) {
  23955. this._MainTex_STY = y;
  23956. }
  23957. get tilingOffsetZ() {
  23958. return this._MainTex_STZ;
  23959. }
  23960. set tilingOffsetZ(z) {
  23961. this._MainTex_STZ = z;
  23962. }
  23963. get tilingOffsetW() {
  23964. return this._MainTex_STW;
  23965. }
  23966. set tilingOffsetW(w) {
  23967. this._MainTex_STW = w;
  23968. }
  23969. get tilingOffset() {
  23970. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23971. }
  23972. set tilingOffset(value) {
  23973. if (value) {
  23974. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  23975. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  23976. else
  23977. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  23978. }
  23979. else {
  23980. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  23981. }
  23982. this._shaderValues.setVector(ShurikenParticleMaterial.TILINGOFFSET, value);
  23983. }
  23984. get texture() {
  23985. return this._shaderValues.getTexture(ShurikenParticleMaterial.DIFFUSETEXTURE);
  23986. }
  23987. set texture(value) {
  23988. if (value)
  23989. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP);
  23990. else
  23991. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP);
  23992. this._shaderValues.setTexture(ShurikenParticleMaterial.DIFFUSETEXTURE, value);
  23993. }
  23994. get depthWrite() {
  23995. return this._shaderValues.getBool(ShurikenParticleMaterial.DEPTH_WRITE);
  23996. }
  23997. set depthWrite(value) {
  23998. this._shaderValues.setBool(ShurikenParticleMaterial.DEPTH_WRITE, value);
  23999. }
  24000. get cull() {
  24001. return this._shaderValues.getInt(ShurikenParticleMaterial.CULL);
  24002. }
  24003. set cull(value) {
  24004. this._shaderValues.setInt(ShurikenParticleMaterial.CULL, value);
  24005. }
  24006. get blend() {
  24007. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND);
  24008. }
  24009. set blend(value) {
  24010. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND, value);
  24011. }
  24012. get blendSrc() {
  24013. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND_SRC);
  24014. }
  24015. set blendSrc(value) {
  24016. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND_SRC, value);
  24017. }
  24018. get blendDst() {
  24019. return this._shaderValues.getInt(ShurikenParticleMaterial.BLEND_DST);
  24020. }
  24021. set blendDst(value) {
  24022. this._shaderValues.setInt(ShurikenParticleMaterial.BLEND_DST, value);
  24023. }
  24024. get depthTest() {
  24025. return this._shaderValues.getInt(ShurikenParticleMaterial.DEPTH_TEST);
  24026. }
  24027. set depthTest(value) {
  24028. this._shaderValues.setInt(ShurikenParticleMaterial.DEPTH_TEST, value);
  24029. }
  24030. clone() {
  24031. var dest = new ShurikenParticleMaterial();
  24032. this.cloneTo(dest);
  24033. return dest;
  24034. }
  24035. }
  24036. ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED = 0;
  24037. ShurikenParticleMaterial.RENDERMODE_ADDTIVE = 1;
  24038. ShurikenParticleMaterial.DIFFUSETEXTURE = Shader3D.propertyNameToID("u_texture");
  24039. ShurikenParticleMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_Tintcolor");
  24040. ShurikenParticleMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  24041. ShurikenParticleMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  24042. ShurikenParticleMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  24043. ShurikenParticleMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  24044. ShurikenParticleMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  24045. ShurikenParticleMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  24046. ShurikenParticleMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  24047. class ShurikenParticleRenderer extends BaseRender {
  24048. constructor(owner) {
  24049. super(owner);
  24050. this._finalGravity = new Vector3();
  24051. this._tempRotationMatrix = new Matrix4x4();
  24052. this._mesh = null;
  24053. this.stretchedBillboardCameraSpeedScale = 0;
  24054. this.stretchedBillboardSpeedScale = 0;
  24055. this.stretchedBillboardLengthScale = 2;
  24056. this._defaultBoundBox = new BoundBox(new Vector3(), new Vector3());
  24057. this.renderMode = 0;
  24058. this._supportOctree = false;
  24059. }
  24060. get renderMode() {
  24061. return this._renderMode;
  24062. }
  24063. set renderMode(value) {
  24064. if (this._renderMode !== value) {
  24065. var defineDatas = this._shaderValues;
  24066. switch (this._renderMode) {
  24067. case 0:
  24068. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD);
  24069. break;
  24070. case 1:
  24071. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD);
  24072. break;
  24073. case 2:
  24074. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD);
  24075. break;
  24076. case 3:
  24077. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD);
  24078. break;
  24079. case 4:
  24080. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH);
  24081. break;
  24082. }
  24083. this._renderMode = value;
  24084. switch (value) {
  24085. case 0:
  24086. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD);
  24087. break;
  24088. case 1:
  24089. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD);
  24090. break;
  24091. case 2:
  24092. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD);
  24093. break;
  24094. case 3:
  24095. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD);
  24096. break;
  24097. case 4:
  24098. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH);
  24099. break;
  24100. default:
  24101. throw new Error("ShurikenParticleRender: unknown renderMode Value.");
  24102. }
  24103. var parSys = this._owner.particleSystem;
  24104. (parSys) && (parSys._initBufferDatas());
  24105. }
  24106. }
  24107. get mesh() {
  24108. return this._mesh;
  24109. }
  24110. set mesh(value) {
  24111. if (this._mesh !== value) {
  24112. (this._mesh) && (this._mesh._removeReference());
  24113. this._mesh = value;
  24114. (value) && (value._addReference());
  24115. this._owner.particleSystem._initBufferDatas();
  24116. }
  24117. }
  24118. _calculateBoundingBox() {
  24119. var min = this._bounds.getMin();
  24120. min.x = -Number.MAX_VALUE;
  24121. min.y = -Number.MAX_VALUE;
  24122. min.z = -Number.MAX_VALUE;
  24123. this._bounds.setMin(min);
  24124. var max = this._bounds.getMax();
  24125. max.x = Number.MAX_VALUE;
  24126. max.y = Number.MAX_VALUE;
  24127. max.z = Number.MAX_VALUE;
  24128. this._bounds.setMax(max);
  24129. if (Laya.Render.supportWebGLPlusCulling) {
  24130. var min = this._bounds.getMin();
  24131. var max = this._bounds.getMax();
  24132. var buffer = FrustumCulling._cullingBuffer;
  24133. buffer[this._cullingBufferIndex + 1] = min.x;
  24134. buffer[this._cullingBufferIndex + 2] = min.y;
  24135. buffer[this._cullingBufferIndex + 3] = min.z;
  24136. buffer[this._cullingBufferIndex + 4] = max.x;
  24137. buffer[this._cullingBufferIndex + 5] = max.y;
  24138. buffer[this._cullingBufferIndex + 6] = max.z;
  24139. }
  24140. }
  24141. _needRender(boundFrustum, context) {
  24142. if (boundFrustum) {
  24143. if (boundFrustum.intersects(this.bounds._getBoundBox())) {
  24144. if (this._owner.particleSystem.isAlive)
  24145. return true;
  24146. else
  24147. return false;
  24148. }
  24149. else {
  24150. return false;
  24151. }
  24152. }
  24153. else {
  24154. return true;
  24155. }
  24156. }
  24157. _renderUpdate(context, transfrom) {
  24158. var particleSystem = this._owner.particleSystem;
  24159. var sv = this._shaderValues;
  24160. var transform = this._owner.transform;
  24161. switch (particleSystem.simulationSpace) {
  24162. case 0:
  24163. break;
  24164. case 1:
  24165. sv.setVector3(ShuriKenParticle3DShaderDeclaration.WORLDPOSITION, transform.position);
  24166. sv.setQuaternion(ShuriKenParticle3DShaderDeclaration.WORLDROTATION, transform.rotation);
  24167. break;
  24168. default:
  24169. throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid.");
  24170. }
  24171. switch (particleSystem.scaleMode) {
  24172. case 0:
  24173. var scale = transform.getWorldLossyScale();
  24174. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, scale);
  24175. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, scale);
  24176. break;
  24177. case 1:
  24178. var localScale = transform.localScale;
  24179. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, localScale);
  24180. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, localScale);
  24181. break;
  24182. case 2:
  24183. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, transform.getWorldLossyScale());
  24184. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, Vector3._ONE);
  24185. break;
  24186. }
  24187. Vector3.scale(Physics3DUtils.gravity, particleSystem.gravityModifier, this._finalGravity);
  24188. sv.setVector3(ShuriKenParticle3DShaderDeclaration.GRAVITY, this._finalGravity);
  24189. sv.setInt(ShuriKenParticle3DShaderDeclaration.SIMULATIONSPACE, particleSystem.simulationSpace);
  24190. sv.setBool(ShuriKenParticle3DShaderDeclaration.THREEDSTARTROTATION, particleSystem.threeDStartRotation);
  24191. sv.setInt(ShuriKenParticle3DShaderDeclaration.SCALINGMODE, particleSystem.scaleMode);
  24192. sv.setNumber(ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDLENGTHSCALE, this.stretchedBillboardLengthScale);
  24193. sv.setNumber(ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDSPEEDSCALE, this.stretchedBillboardSpeedScale);
  24194. sv.setNumber(ShuriKenParticle3DShaderDeclaration.CURRENTTIME, particleSystem._currentTime);
  24195. }
  24196. get bounds() {
  24197. if (this._boundsChange) {
  24198. this._calculateBoundingBox();
  24199. this._boundsChange = false;
  24200. }
  24201. return this._bounds;
  24202. }
  24203. _destroy() {
  24204. super._destroy();
  24205. (this._mesh) && (this._mesh._removeReference(), this._mesh = null);
  24206. }
  24207. }
  24208. class VertexShuriKenParticle {
  24209. constructor() {
  24210. }
  24211. }
  24212. VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0 = 5;
  24213. VertexShuriKenParticle.PARTICLE_POSITION0 = 1;
  24214. VertexShuriKenParticle.PARTICLE_COLOR0 = 2;
  24215. VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0 = 3;
  24216. VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME = 4;
  24217. VertexShuriKenParticle.PARTICLE_DIRECTIONTIME = 0;
  24218. VertexShuriKenParticle.PARTICLE_STARTCOLOR0 = 6;
  24219. VertexShuriKenParticle.PARTICLE_ENDCOLOR0 = 7;
  24220. VertexShuriKenParticle.PARTICLE_STARTSIZE = 8;
  24221. VertexShuriKenParticle.PARTICLE_STARTROTATION = 9;
  24222. VertexShuriKenParticle.PARTICLE_STARTSPEED = 10;
  24223. VertexShuriKenParticle.PARTICLE_RANDOM0 = 11;
  24224. VertexShuriKenParticle.PARTICLE_RANDOM1 = 12;
  24225. VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION = 13;
  24226. VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION = 14;
  24227. class VertexShurikenParticleBillboard extends VertexShuriKenParticle {
  24228. constructor(cornerTextureCoordinate, positionStartLifeTime, velocity, startColor, startSize, startRotation0, startRotation1, startRotation2, ageAddScale, time, startSpeed, randoms0, randoms1, simulationWorldPostion) {
  24229. super();
  24230. this._cornerTextureCoordinate = cornerTextureCoordinate;
  24231. this._positionStartLifeTime = positionStartLifeTime;
  24232. this._velocity = velocity;
  24233. this._startColor = startColor;
  24234. this._startSize = startSize;
  24235. this._startRotation0 = startRotation0;
  24236. this._startRotation1 = startRotation1;
  24237. this._startRotation2 = startRotation2;
  24238. this._startLifeTime = ageAddScale;
  24239. this._time = time;
  24240. this._startSpeed = startSpeed;
  24241. this._randoms0 = this.random0;
  24242. this._randoms1 = this.random1;
  24243. this._simulationWorldPostion = simulationWorldPostion;
  24244. }
  24245. static get vertexDeclaration() {
  24246. return VertexShurikenParticleBillboard._vertexDeclaration;
  24247. }
  24248. static __init__() {
  24249. VertexShurikenParticleBillboard._vertexDeclaration = new VertexDeclaration(152, [new VertexElement(0, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0),
  24250. new VertexElement(16, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME),
  24251. new VertexElement(32, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_DIRECTIONTIME),
  24252. new VertexElement(48, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_STARTCOLOR0),
  24253. new VertexElement(64, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTSIZE),
  24254. new VertexElement(76, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTROTATION),
  24255. new VertexElement(88, VertexElementFormat.Single, VertexShuriKenParticle.PARTICLE_STARTSPEED),
  24256. new VertexElement(92, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM0),
  24257. new VertexElement(108, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM1),
  24258. new VertexElement(124, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION),
  24259. new VertexElement(136, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION)]);
  24260. }
  24261. get cornerTextureCoordinate() {
  24262. return this._cornerTextureCoordinate;
  24263. }
  24264. get positionStartLifeTime() {
  24265. return this._positionStartLifeTime;
  24266. }
  24267. get velocity() {
  24268. return this._velocity;
  24269. }
  24270. get startColor() {
  24271. return this._startColor;
  24272. }
  24273. get startSize() {
  24274. return this._startSize;
  24275. }
  24276. get startRotation0() {
  24277. return this._startRotation0;
  24278. }
  24279. get startRotation1() {
  24280. return this._startRotation1;
  24281. }
  24282. get startRotation2() {
  24283. return this._startRotation2;
  24284. }
  24285. get startLifeTime() {
  24286. return this._startLifeTime;
  24287. }
  24288. get time() {
  24289. return this._time;
  24290. }
  24291. get startSpeed() {
  24292. return this._startSpeed;
  24293. }
  24294. get random0() {
  24295. return this._randoms0;
  24296. }
  24297. get random1() {
  24298. return this._randoms1;
  24299. }
  24300. get simulationWorldPostion() {
  24301. return this._simulationWorldPostion;
  24302. }
  24303. }
  24304. class VertexShurikenParticleMesh extends VertexShuriKenParticle {
  24305. constructor(cornerTextureCoordinate, positionStartLifeTime, velocity, startColor, startSize, startRotation0, startRotation1, startRotation2, ageAddScale, time, startSpeed, randoms0, randoms1, simulationWorldPostion) {
  24306. super();
  24307. this._cornerTextureCoordinate = cornerTextureCoordinate;
  24308. this._positionStartLifeTime = positionStartLifeTime;
  24309. this._velocity = velocity;
  24310. this._startColor = startColor;
  24311. this._startSize = startSize;
  24312. this._startRotation0 = startRotation0;
  24313. this._startRotation1 = startRotation1;
  24314. this._startRotation2 = startRotation2;
  24315. this._startLifeTime = ageAddScale;
  24316. this._time = time;
  24317. this._startSpeed = startSpeed;
  24318. this._randoms0 = this.random0;
  24319. this._randoms1 = this.random1;
  24320. this._simulationWorldPostion = simulationWorldPostion;
  24321. }
  24322. static __init__() {
  24323. VertexShurikenParticleMesh._vertexDeclaration = new VertexDeclaration(172, [new VertexElement(0, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_POSITION0),
  24324. new VertexElement(12, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_COLOR0),
  24325. new VertexElement(28, VertexElementFormat.Vector2, VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0),
  24326. new VertexElement(36, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME),
  24327. new VertexElement(52, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_DIRECTIONTIME),
  24328. new VertexElement(68, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_STARTCOLOR0),
  24329. new VertexElement(84, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTSIZE),
  24330. new VertexElement(96, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTROTATION),
  24331. new VertexElement(108, VertexElementFormat.Single, VertexShuriKenParticle.PARTICLE_STARTSPEED),
  24332. new VertexElement(112, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM0),
  24333. new VertexElement(128, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM1),
  24334. new VertexElement(144, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION),
  24335. new VertexElement(156, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION)]);
  24336. }
  24337. static get vertexDeclaration() {
  24338. return VertexShurikenParticleMesh._vertexDeclaration;
  24339. }
  24340. get cornerTextureCoordinate() {
  24341. return this._cornerTextureCoordinate;
  24342. }
  24343. get position() {
  24344. return this._positionStartLifeTime;
  24345. }
  24346. get velocity() {
  24347. return this._velocity;
  24348. }
  24349. get startColor() {
  24350. return this._startColor;
  24351. }
  24352. get startSize() {
  24353. return this._startSize;
  24354. }
  24355. get startRotation0() {
  24356. return this._startRotation0;
  24357. }
  24358. get startRotation1() {
  24359. return this._startRotation1;
  24360. }
  24361. get startRotation2() {
  24362. return this._startRotation2;
  24363. }
  24364. get startLifeTime() {
  24365. return this._startLifeTime;
  24366. }
  24367. get time() {
  24368. return this._time;
  24369. }
  24370. get startSpeed() {
  24371. return this._startSpeed;
  24372. }
  24373. get random0() {
  24374. return this._randoms0;
  24375. }
  24376. get random1() {
  24377. return this._randoms1;
  24378. }
  24379. get simulationWorldPostion() {
  24380. return this._simulationWorldPostion;
  24381. }
  24382. }
  24383. class Rand {
  24384. constructor(seed) {
  24385. this._temp = new Uint32Array(1);
  24386. this.seeds = new Uint32Array(4);
  24387. this.seeds[0] = seed;
  24388. this.seeds[1] = this.seeds[0] * 0x6C078965 + 1;
  24389. this.seeds[2] = this.seeds[1] * 0x6C078965 + 1;
  24390. this.seeds[3] = this.seeds[2] * 0x6C078965 + 1;
  24391. }
  24392. static getFloatFromInt(v) {
  24393. return (v & 0x007FFFFF) * (1.0 / 8388607.0);
  24394. }
  24395. static getByteFromInt(v) {
  24396. return (v & 0x007FFFFF) >>> 15;
  24397. }
  24398. get seed() {
  24399. return this.seeds[0];
  24400. }
  24401. set seed(seed) {
  24402. this.seeds[0] = seed;
  24403. this.seeds[1] = this.seeds[0] * 0x6C078965 + 1;
  24404. this.seeds[2] = this.seeds[1] * 0x6C078965 + 1;
  24405. this.seeds[3] = this.seeds[2] * 0x6C078965 + 1;
  24406. }
  24407. getUint() {
  24408. this._temp[0] = this.seeds[0] ^ (this.seeds[0] << 11);
  24409. this.seeds[0] = this.seeds[1];
  24410. this.seeds[1] = this.seeds[2];
  24411. this.seeds[2] = this.seeds[3];
  24412. this.seeds[3] = (this.seeds[3] ^ (this.seeds[3] >>> 19)) ^ (this._temp[0] ^ (this._temp[0] >>> 8));
  24413. return this.seeds[3];
  24414. }
  24415. getFloat() {
  24416. this.getUint();
  24417. return (this.seeds[3] & 0x007FFFFF) * (1.0 / 8388607.0);
  24418. }
  24419. getSignedFloat() {
  24420. return this.getFloat() * 2.0 - 1.0;
  24421. }
  24422. }
  24423. class Emission {
  24424. constructor() {
  24425. this._emissionRate = 10;
  24426. this._destroyed = false;
  24427. this._bursts = [];
  24428. }
  24429. set emissionRate(value) {
  24430. if (value < 0)
  24431. throw new Error("ParticleBaseShape:emissionRate value must large or equal than 0.");
  24432. this._emissionRate = value;
  24433. }
  24434. get emissionRate() {
  24435. return this._emissionRate;
  24436. }
  24437. get destroyed() {
  24438. return this._destroyed;
  24439. }
  24440. destroy() {
  24441. this._bursts = null;
  24442. this._destroyed = true;
  24443. }
  24444. getBurstsCount() {
  24445. return this._bursts.length;
  24446. }
  24447. getBurstByIndex(index) {
  24448. return this._bursts[index];
  24449. }
  24450. addBurst(burst) {
  24451. var burstsCount = this._bursts.length;
  24452. if (burstsCount > 0)
  24453. for (var i = 0; i < burstsCount; i++) {
  24454. if (this._bursts[i].time > burst.time)
  24455. this._bursts.splice(i, 0, burst);
  24456. }
  24457. this._bursts.push(burst);
  24458. }
  24459. removeBurst(burst) {
  24460. var index = this._bursts.indexOf(burst);
  24461. if (index !== -1) {
  24462. this._bursts.splice(index, 1);
  24463. }
  24464. }
  24465. removeBurstByIndex(index) {
  24466. this._bursts.splice(index, 1);
  24467. }
  24468. clearBurst() {
  24469. this._bursts.length = 0;
  24470. }
  24471. cloneTo(destObject) {
  24472. var destEmission = destObject;
  24473. var destBursts = destEmission._bursts;
  24474. destBursts.length = this._bursts.length;
  24475. for (var i = 0, n = this._bursts.length; i < n; i++) {
  24476. var destBurst = destBursts[i];
  24477. if (destBurst)
  24478. this._bursts[i].cloneTo(destBurst);
  24479. else
  24480. destBursts[i] = this._bursts[i].clone();
  24481. }
  24482. destEmission._emissionRate = this._emissionRate;
  24483. destEmission.enable = this.enable;
  24484. }
  24485. clone() {
  24486. var destEmission = new Emission();
  24487. this.cloneTo(destEmission);
  24488. return destEmission;
  24489. }
  24490. }
  24491. class ShurikenParticleData {
  24492. constructor() {
  24493. }
  24494. static _getStartLifetimeFromGradient(startLifeTimeGradient, emissionTime) {
  24495. for (var i = 1, n = startLifeTimeGradient.gradientCount; i < n; i++) {
  24496. var key = startLifeTimeGradient.getKeyByIndex(i);
  24497. if (key >= emissionTime) {
  24498. var lastKey = startLifeTimeGradient.getKeyByIndex(i - 1);
  24499. var age = (emissionTime - lastKey) / (key - lastKey);
  24500. return Laya.MathUtil.lerp(startLifeTimeGradient.getValueByIndex(i - 1), startLifeTimeGradient.getValueByIndex(i), age);
  24501. }
  24502. }
  24503. throw new Error("ShurikenParticleData: can't get value foam startLifeTimeGradient.");
  24504. }
  24505. static _randomInvertRoationArray(rotatonE, outE, randomizeRotationDirection, rand, randomSeeds) {
  24506. var randDic;
  24507. if (rand) {
  24508. rand.seed = randomSeeds[6];
  24509. randDic = rand.getFloat();
  24510. randomSeeds[6] = rand.seed;
  24511. }
  24512. else {
  24513. randDic = Math.random();
  24514. }
  24515. if (randDic < randomizeRotationDirection) {
  24516. outE.x = -rotatonE.x;
  24517. outE.y = -rotatonE.y;
  24518. outE.z = -rotatonE.z;
  24519. }
  24520. else {
  24521. outE.x = rotatonE.x;
  24522. outE.y = rotatonE.y;
  24523. outE.z = rotatonE.z;
  24524. }
  24525. }
  24526. static _randomInvertRoation(rotaton, randomizeRotationDirection, rand, randomSeeds) {
  24527. var randDic;
  24528. if (rand) {
  24529. rand.seed = randomSeeds[6];
  24530. randDic = rand.getFloat();
  24531. randomSeeds[6] = rand.seed;
  24532. }
  24533. else {
  24534. randDic = Math.random();
  24535. }
  24536. if (randDic < randomizeRotationDirection)
  24537. rotaton = -rotaton;
  24538. return rotaton;
  24539. }
  24540. static create(particleSystem, particleRender, transform) {
  24541. var autoRandomSeed = particleSystem.autoRandomSeed;
  24542. var rand = particleSystem._rand;
  24543. var randomSeeds = particleSystem._randomSeeds;
  24544. switch (particleSystem.startColorType) {
  24545. case 0:
  24546. var constantStartColor = particleSystem.startColorConstant;
  24547. ShurikenParticleData.startColor.x = constantStartColor.x;
  24548. ShurikenParticleData.startColor.y = constantStartColor.y;
  24549. ShurikenParticleData.startColor.z = constantStartColor.z;
  24550. ShurikenParticleData.startColor.w = constantStartColor.w;
  24551. break;
  24552. case 2:
  24553. if (autoRandomSeed) {
  24554. Vector4.lerp(particleSystem.startColorConstantMin, particleSystem.startColorConstantMax, Math.random(), ShurikenParticleData.startColor);
  24555. }
  24556. else {
  24557. rand.seed = randomSeeds[3];
  24558. Vector4.lerp(particleSystem.startColorConstantMin, particleSystem.startColorConstantMax, rand.getFloat(), ShurikenParticleData.startColor);
  24559. randomSeeds[3] = rand.seed;
  24560. }
  24561. break;
  24562. }
  24563. var colorOverLifetime = particleSystem.colorOverLifetime;
  24564. if (colorOverLifetime && colorOverLifetime.enable) {
  24565. var color = colorOverLifetime.color;
  24566. switch (color.type) {
  24567. case 0:
  24568. ShurikenParticleData.startColor.x = ShurikenParticleData.startColor.x * color.constant.x;
  24569. ShurikenParticleData.startColor.y = ShurikenParticleData.startColor.y * color.constant.y;
  24570. ShurikenParticleData.startColor.z = ShurikenParticleData.startColor.z * color.constant.z;
  24571. ShurikenParticleData.startColor.w = ShurikenParticleData.startColor.w * color.constant.w;
  24572. break;
  24573. case 2:
  24574. var colorRandom;
  24575. if (autoRandomSeed) {
  24576. colorRandom = Math.random();
  24577. }
  24578. else {
  24579. rand.seed = randomSeeds[10];
  24580. colorRandom = rand.getFloat();
  24581. randomSeeds[10] = rand.seed;
  24582. }
  24583. var minConstantColor = color.constantMin;
  24584. var maxConstantColor = color.constantMax;
  24585. ShurikenParticleData.startColor.x = ShurikenParticleData.startColor.x * Laya.MathUtil.lerp(minConstantColor.x, maxConstantColor.x, colorRandom);
  24586. ShurikenParticleData.startColor.y = ShurikenParticleData.startColor.y * Laya.MathUtil.lerp(minConstantColor.y, maxConstantColor.y, colorRandom);
  24587. ShurikenParticleData.startColor.z = ShurikenParticleData.startColor.z * Laya.MathUtil.lerp(minConstantColor.z, maxConstantColor.z, colorRandom);
  24588. ShurikenParticleData.startColor.w = ShurikenParticleData.startColor.w * Laya.MathUtil.lerp(minConstantColor.w, maxConstantColor.w, colorRandom);
  24589. break;
  24590. }
  24591. }
  24592. var particleSize = ShurikenParticleData.startSize;
  24593. switch (particleSystem.startSizeType) {
  24594. case 0:
  24595. if (particleSystem.threeDStartSize) {
  24596. var startSizeConstantSeparate = particleSystem.startSizeConstantSeparate;
  24597. particleSize[0] = startSizeConstantSeparate.x;
  24598. particleSize[1] = startSizeConstantSeparate.y;
  24599. particleSize[2] = startSizeConstantSeparate.z;
  24600. }
  24601. else {
  24602. particleSize[0] = particleSize[1] = particleSize[2] = particleSystem.startSizeConstant;
  24603. }
  24604. break;
  24605. case 2:
  24606. if (particleSystem.threeDStartSize) {
  24607. var startSizeConstantMinSeparate = particleSystem.startSizeConstantMinSeparate;
  24608. var startSizeConstantMaxSeparate = particleSystem.startSizeConstantMaxSeparate;
  24609. if (autoRandomSeed) {
  24610. particleSize[0] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.x, startSizeConstantMaxSeparate.x, Math.random());
  24611. particleSize[1] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.y, startSizeConstantMaxSeparate.y, Math.random());
  24612. particleSize[2] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.z, startSizeConstantMaxSeparate.z, Math.random());
  24613. }
  24614. else {
  24615. rand.seed = randomSeeds[4];
  24616. particleSize[0] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.x, startSizeConstantMaxSeparate.x, rand.getFloat());
  24617. particleSize[1] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.y, startSizeConstantMaxSeparate.y, rand.getFloat());
  24618. particleSize[2] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.z, startSizeConstantMaxSeparate.z, rand.getFloat());
  24619. randomSeeds[4] = rand.seed;
  24620. }
  24621. }
  24622. else {
  24623. if (autoRandomSeed) {
  24624. particleSize[0] = particleSize[1] = particleSize[2] = Laya.MathUtil.lerp(particleSystem.startSizeConstantMin, particleSystem.startSizeConstantMax, Math.random());
  24625. }
  24626. else {
  24627. rand.seed = randomSeeds[4];
  24628. particleSize[0] = particleSize[1] = particleSize[2] = Laya.MathUtil.lerp(particleSystem.startSizeConstantMin, particleSystem.startSizeConstantMax, rand.getFloat());
  24629. randomSeeds[4] = rand.seed;
  24630. }
  24631. }
  24632. break;
  24633. }
  24634. var sizeOverLifetime = particleSystem.sizeOverLifetime;
  24635. if (sizeOverLifetime && sizeOverLifetime.enable && sizeOverLifetime.size.type === 1) {
  24636. var size = sizeOverLifetime.size;
  24637. if (size.separateAxes) {
  24638. if (autoRandomSeed) {
  24639. particleSize[0] = particleSize[0] * Laya.MathUtil.lerp(size.constantMinSeparate.x, size.constantMaxSeparate.x, Math.random());
  24640. particleSize[1] = particleSize[1] * Laya.MathUtil.lerp(size.constantMinSeparate.y, size.constantMaxSeparate.y, Math.random());
  24641. particleSize[2] = particleSize[2] * Laya.MathUtil.lerp(size.constantMinSeparate.z, size.constantMaxSeparate.z, Math.random());
  24642. }
  24643. else {
  24644. rand.seed = randomSeeds[11];
  24645. particleSize[0] = particleSize[0] * Laya.MathUtil.lerp(size.constantMinSeparate.x, size.constantMaxSeparate.x, rand.getFloat());
  24646. particleSize[1] = particleSize[1] * Laya.MathUtil.lerp(size.constantMinSeparate.y, size.constantMaxSeparate.y, rand.getFloat());
  24647. particleSize[2] = particleSize[2] * Laya.MathUtil.lerp(size.constantMinSeparate.z, size.constantMaxSeparate.z, rand.getFloat());
  24648. randomSeeds[11] = rand.seed;
  24649. }
  24650. }
  24651. else {
  24652. var randomSize;
  24653. if (autoRandomSeed) {
  24654. randomSize = Laya.MathUtil.lerp(size.constantMin, size.constantMax, Math.random());
  24655. }
  24656. else {
  24657. rand.seed = randomSeeds[11];
  24658. randomSize = Laya.MathUtil.lerp(size.constantMin, size.constantMax, rand.getFloat());
  24659. randomSeeds[11] = rand.seed;
  24660. }
  24661. particleSize[0] = particleSize[0] * randomSize;
  24662. particleSize[1] = particleSize[1] * randomSize;
  24663. particleSize[2] = particleSize[2] * randomSize;
  24664. }
  24665. }
  24666. var renderMode = particleRender.renderMode;
  24667. if (renderMode !== 1) {
  24668. switch (particleSystem.startRotationType) {
  24669. case 0:
  24670. if (particleSystem.threeDStartRotation) {
  24671. var startRotationConstantSeparate = particleSystem.startRotationConstantSeparate;
  24672. var randomRotationE = ShurikenParticleData._tempVector30;
  24673. ShurikenParticleData._randomInvertRoationArray(startRotationConstantSeparate, randomRotationE, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24674. ShurikenParticleData.startRotation[0] = randomRotationE.x;
  24675. ShurikenParticleData.startRotation[1] = randomRotationE.y;
  24676. if (renderMode !== 4)
  24677. ShurikenParticleData.startRotation[2] = -randomRotationE.z;
  24678. else
  24679. ShurikenParticleData.startRotation[2] = randomRotationE.z;
  24680. }
  24681. else {
  24682. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(particleSystem.startRotationConstant, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24683. ShurikenParticleData.startRotation[1] = 0;
  24684. ShurikenParticleData.startRotation[2] = 0;
  24685. }
  24686. break;
  24687. case 2:
  24688. if (particleSystem.threeDStartRotation) {
  24689. var startRotationConstantMinSeparate = particleSystem.startRotationConstantMinSeparate;
  24690. var startRotationConstantMaxSeparate = particleSystem.startRotationConstantMaxSeparate;
  24691. var lerpRoationE = ShurikenParticleData._tempVector30;
  24692. if (autoRandomSeed) {
  24693. lerpRoationE.x = Laya.MathUtil.lerp(startRotationConstantMinSeparate.x, startRotationConstantMaxSeparate.x, Math.random());
  24694. lerpRoationE.y = Laya.MathUtil.lerp(startRotationConstantMinSeparate.y, startRotationConstantMaxSeparate.y, Math.random());
  24695. lerpRoationE.z = Laya.MathUtil.lerp(startRotationConstantMinSeparate.z, startRotationConstantMaxSeparate.z, Math.random());
  24696. }
  24697. else {
  24698. rand.seed = randomSeeds[5];
  24699. lerpRoationE.x = Laya.MathUtil.lerp(startRotationConstantMinSeparate.x, startRotationConstantMaxSeparate.x, rand.getFloat());
  24700. lerpRoationE.y = Laya.MathUtil.lerp(startRotationConstantMinSeparate.y, startRotationConstantMaxSeparate.y, rand.getFloat());
  24701. lerpRoationE.z = Laya.MathUtil.lerp(startRotationConstantMinSeparate.z, startRotationConstantMaxSeparate.z, rand.getFloat());
  24702. randomSeeds[5] = rand.seed;
  24703. }
  24704. ShurikenParticleData._randomInvertRoationArray(lerpRoationE, lerpRoationE, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24705. ShurikenParticleData.startRotation[0] = lerpRoationE.x;
  24706. ShurikenParticleData.startRotation[1] = lerpRoationE.y;
  24707. if (renderMode !== 4)
  24708. ShurikenParticleData.startRotation[2] = -lerpRoationE.z;
  24709. else
  24710. ShurikenParticleData.startRotation[2] = lerpRoationE.z;
  24711. }
  24712. else {
  24713. if (autoRandomSeed) {
  24714. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(Laya.MathUtil.lerp(particleSystem.startRotationConstantMin, particleSystem.startRotationConstantMax, Math.random()), particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24715. }
  24716. else {
  24717. rand.seed = randomSeeds[5];
  24718. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(Laya.MathUtil.lerp(particleSystem.startRotationConstantMin, particleSystem.startRotationConstantMax, rand.getFloat()), particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24719. randomSeeds[5] = rand.seed;
  24720. }
  24721. }
  24722. break;
  24723. }
  24724. }
  24725. switch (particleSystem.startLifetimeType) {
  24726. case 0:
  24727. ShurikenParticleData.startLifeTime = particleSystem.startLifetimeConstant;
  24728. break;
  24729. case 1:
  24730. ShurikenParticleData.startLifeTime = ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradient, particleSystem.emissionTime);
  24731. break;
  24732. case 2:
  24733. if (autoRandomSeed) {
  24734. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(particleSystem.startLifetimeConstantMin, particleSystem.startLifetimeConstantMax, Math.random());
  24735. }
  24736. else {
  24737. rand.seed = randomSeeds[7];
  24738. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(particleSystem.startLifetimeConstantMin, particleSystem.startLifetimeConstantMax, rand.getFloat());
  24739. randomSeeds[7] = rand.seed;
  24740. }
  24741. break;
  24742. case 3:
  24743. var emissionTime = particleSystem.emissionTime;
  24744. if (autoRandomSeed) {
  24745. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin, emissionTime), ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax, emissionTime), Math.random());
  24746. }
  24747. else {
  24748. rand.seed = randomSeeds[7];
  24749. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin, emissionTime), ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax, emissionTime), rand.getFloat());
  24750. randomSeeds[7] = rand.seed;
  24751. }
  24752. break;
  24753. }
  24754. var textureSheetAnimation = particleSystem.textureSheetAnimation;
  24755. var enableSheetAnimation = textureSheetAnimation && textureSheetAnimation.enable;
  24756. if (enableSheetAnimation) {
  24757. var title = textureSheetAnimation.tiles;
  24758. var titleX = title.x, titleY = title.y;
  24759. var subU = 1.0 / titleX, subV = 1.0 / titleY;
  24760. var startFrameCount;
  24761. var startFrame = textureSheetAnimation.startFrame;
  24762. switch (startFrame.type) {
  24763. case 0:
  24764. startFrameCount = startFrame.constant;
  24765. break;
  24766. case 1:
  24767. if (autoRandomSeed) {
  24768. startFrameCount = Laya.MathUtil.lerp(startFrame.constantMin, startFrame.constantMax, Math.random());
  24769. }
  24770. else {
  24771. rand.seed = randomSeeds[14];
  24772. startFrameCount = Laya.MathUtil.lerp(startFrame.constantMin, startFrame.constantMax, rand.getFloat());
  24773. randomSeeds[14] = rand.seed;
  24774. }
  24775. break;
  24776. }
  24777. var frame = textureSheetAnimation.frame;
  24778. var cycles = textureSheetAnimation.cycles;
  24779. switch (frame.type) {
  24780. case 0:
  24781. startFrameCount += frame.constant * cycles;
  24782. break;
  24783. case 2:
  24784. if (autoRandomSeed) {
  24785. startFrameCount += Laya.MathUtil.lerp(frame.constantMin, frame.constantMax, Math.random()) * cycles;
  24786. }
  24787. else {
  24788. rand.seed = randomSeeds[15];
  24789. startFrameCount += Laya.MathUtil.lerp(frame.constantMin, frame.constantMax, rand.getFloat()) * cycles;
  24790. randomSeeds[15] = rand.seed;
  24791. }
  24792. break;
  24793. }
  24794. var startRow = 0;
  24795. switch (textureSheetAnimation.type) {
  24796. case 0:
  24797. startRow = Math.floor(startFrameCount / titleX);
  24798. break;
  24799. case 1:
  24800. if (textureSheetAnimation.randomRow) {
  24801. if (autoRandomSeed) {
  24802. startRow = Math.floor(Math.random() * titleY);
  24803. }
  24804. else {
  24805. rand.seed = randomSeeds[13];
  24806. startRow = Math.floor(rand.getFloat() * titleY);
  24807. randomSeeds[13] = rand.seed;
  24808. }
  24809. }
  24810. else {
  24811. startRow = textureSheetAnimation.rowIndex;
  24812. }
  24813. break;
  24814. }
  24815. var startCol = Math.floor(startFrameCount % titleX);
  24816. ShurikenParticleData.startUVInfo = ShurikenParticleData.startUVInfo;
  24817. ShurikenParticleData.startUVInfo[0] = subU;
  24818. ShurikenParticleData.startUVInfo[1] = subV;
  24819. ShurikenParticleData.startUVInfo[2] = startCol * subU;
  24820. ShurikenParticleData.startUVInfo[3] = startRow * subV;
  24821. }
  24822. else {
  24823. ShurikenParticleData.startUVInfo = ShurikenParticleData.startUVInfo;
  24824. ShurikenParticleData.startUVInfo[0] = 1.0;
  24825. ShurikenParticleData.startUVInfo[1] = 1.0;
  24826. ShurikenParticleData.startUVInfo[2] = 0.0;
  24827. ShurikenParticleData.startUVInfo[3] = 0.0;
  24828. }
  24829. }
  24830. }
  24831. ShurikenParticleData._tempVector30 = new Vector3();
  24832. ShurikenParticleData.startColor = new Vector4();
  24833. ShurikenParticleData.startSize = new Float32Array(3);
  24834. ShurikenParticleData.startRotation = new Float32Array(3);
  24835. ShurikenParticleData.startUVInfo = new Float32Array(4);
  24836. class ShurikenParticleSystem extends GeometryElement {
  24837. constructor(owner) {
  24838. super();
  24839. this._boundingSphere = null;
  24840. this._boundingBox = null;
  24841. this._boundingBoxCorners = null;
  24842. this._owner = null;
  24843. this._ownerRender = null;
  24844. this._vertices = null;
  24845. this._floatCountPerVertex = 0;
  24846. this._startLifeTimeIndex = 0;
  24847. this._timeIndex = 0;
  24848. this._simulateUpdate = false;
  24849. this._firstActiveElement = 0;
  24850. this._firstNewElement = 0;
  24851. this._firstFreeElement = 0;
  24852. this._firstRetiredElement = 0;
  24853. this._drawCounter = 0;
  24854. this._bufferMaxParticles = 0;
  24855. this._emission = null;
  24856. this._shape = null;
  24857. this._isEmitting = false;
  24858. this._isPlaying = false;
  24859. this._isPaused = false;
  24860. this._playStartDelay = 0;
  24861. this._frameRateTime = 0;
  24862. this._emissionTime = 0;
  24863. this._totalDelayTime = 0;
  24864. this._burstsIndex = 0;
  24865. this._velocityOverLifetime = null;
  24866. this._colorOverLifetime = null;
  24867. this._sizeOverLifetime = null;
  24868. this._rotationOverLifetime = null;
  24869. this._textureSheetAnimation = null;
  24870. this._startLifetimeType = 0;
  24871. this._startLifetimeConstant = 0;
  24872. this._startLifeTimeGradient = null;
  24873. this._startLifetimeConstantMin = 0;
  24874. this._startLifetimeConstantMax = 0;
  24875. this._startLifeTimeGradientMin = null;
  24876. this._startLifeTimeGradientMax = null;
  24877. this._maxStartLifetime = 0;
  24878. this._uvLength = new Vector2();
  24879. this._vertexStride = 0;
  24880. this._indexStride = 0;
  24881. this._vertexBuffer = null;
  24882. this._indexBuffer = null;
  24883. this._bufferState = new BufferState();
  24884. this._currentTime = 0;
  24885. this._startUpdateLoopCount = 0;
  24886. this._rand = null;
  24887. this._randomSeeds = null;
  24888. this.duration = 0;
  24889. this.looping = false;
  24890. this.prewarm = false;
  24891. this.startDelayType = 0;
  24892. this.startDelay = 0;
  24893. this.startDelayMin = 0;
  24894. this.startDelayMax = 0;
  24895. this.startSpeedType = 0;
  24896. this.startSpeedConstant = 0;
  24897. this.startSpeedConstantMin = 0;
  24898. this.startSpeedConstantMax = 0;
  24899. this.threeDStartSize = false;
  24900. this.startSizeType = 0;
  24901. this.startSizeConstant = 0;
  24902. this.startSizeConstantSeparate = null;
  24903. this.startSizeConstantMin = 0;
  24904. this.startSizeConstantMax = 0;
  24905. this.startSizeConstantMinSeparate = null;
  24906. this.startSizeConstantMaxSeparate = null;
  24907. this.threeDStartRotation = false;
  24908. this.startRotationType = 0;
  24909. this.startRotationConstant = 0;
  24910. this.startRotationConstantSeparate = null;
  24911. this.startRotationConstantMin = 0;
  24912. this.startRotationConstantMax = 0;
  24913. this.startRotationConstantMinSeparate = null;
  24914. this.startRotationConstantMaxSeparate = null;
  24915. this.randomizeRotationDirection = 0;
  24916. this.startColorType = 0;
  24917. this.startColorConstant = new Vector4(1, 1, 1, 1);
  24918. this.startColorConstantMin = new Vector4(0, 0, 0, 0);
  24919. this.startColorConstantMax = new Vector4(1, 1, 1, 1);
  24920. this.gravityModifier = 0;
  24921. this.simulationSpace = 0;
  24922. this.simulationSpeed = 1.0;
  24923. this.scaleMode = 1;
  24924. this.playOnAwake = false;
  24925. this.randomSeed = null;
  24926. this.autoRandomSeed = false;
  24927. this.isPerformanceMode = false;
  24928. this._firstActiveElement = 0;
  24929. this._firstNewElement = 0;
  24930. this._firstFreeElement = 0;
  24931. this._firstRetiredElement = 0;
  24932. this._owner = owner;
  24933. this._ownerRender = owner.particleRenderer;
  24934. this._boundingBoxCorners = [];
  24935. this._boundingSphere = new BoundSphere(new Vector3(), Number.MAX_VALUE);
  24936. 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));
  24937. this._currentTime = 0;
  24938. this._isEmitting = false;
  24939. this._isPlaying = false;
  24940. this._isPaused = false;
  24941. this._burstsIndex = 0;
  24942. this._frameRateTime = 0;
  24943. this._emissionTime = 0;
  24944. this._totalDelayTime = 0;
  24945. this._simulateUpdate = false;
  24946. this._bufferMaxParticles = 1;
  24947. this.duration = 5.0;
  24948. this.looping = true;
  24949. this.prewarm = false;
  24950. this.startDelayType = 0;
  24951. this.startDelay = 0.0;
  24952. this.startDelayMin = 0.0;
  24953. this.startDelayMax = 0.0;
  24954. this._startLifetimeType = 0;
  24955. this._startLifetimeConstant = 5.0;
  24956. this._startLifeTimeGradient = new GradientDataNumber();
  24957. this._startLifetimeConstantMin = 0.0;
  24958. this._startLifetimeConstantMax = 5.0;
  24959. this._startLifeTimeGradientMin = new GradientDataNumber();
  24960. this._startLifeTimeGradientMax = new GradientDataNumber();
  24961. this._maxStartLifetime = 5.0;
  24962. this.startSpeedType = 0;
  24963. this.startSpeedConstant = 5.0;
  24964. this.startSpeedConstantMin = 0.0;
  24965. this.startSpeedConstantMax = 5.0;
  24966. this.threeDStartSize = false;
  24967. this.startSizeType = 0;
  24968. this.startSizeConstant = 1;
  24969. this.startSizeConstantSeparate = new Vector3(1, 1, 1);
  24970. this.startSizeConstantMin = 0;
  24971. this.startSizeConstantMax = 1;
  24972. this.startSizeConstantMinSeparate = new Vector3(0, 0, 0);
  24973. this.startSizeConstantMaxSeparate = new Vector3(1, 1, 1);
  24974. this.threeDStartRotation = false;
  24975. this.startRotationType = 0;
  24976. this.startRotationConstant = 0;
  24977. this.startRotationConstantSeparate = new Vector3(0, 0, 0);
  24978. this.startRotationConstantMin = 0.0;
  24979. this.startRotationConstantMax = 0.0;
  24980. this.startRotationConstantMinSeparate = new Vector3(0, 0, 0);
  24981. this.startRotationConstantMaxSeparate = new Vector3(0, 0, 0);
  24982. this.gravityModifier = 0.0;
  24983. this.simulationSpace = 1;
  24984. this.scaleMode = 1;
  24985. this.playOnAwake = true;
  24986. this._rand = new Rand(0);
  24987. this.autoRandomSeed = true;
  24988. this.randomSeed = new Uint32Array(1);
  24989. this._randomSeeds = new Uint32Array(ShurikenParticleSystem._RANDOMOFFSET.length);
  24990. this.isPerformanceMode = true;
  24991. this._emission = new Emission();
  24992. this._emission.enable = true;
  24993. }
  24994. ;
  24995. get maxParticles() {
  24996. return this._bufferMaxParticles - 1;
  24997. }
  24998. set maxParticles(value) {
  24999. var newMaxParticles = value + 1;
  25000. if (newMaxParticles !== this._bufferMaxParticles) {
  25001. this._bufferMaxParticles = newMaxParticles;
  25002. this._initBufferDatas();
  25003. }
  25004. }
  25005. get emission() {
  25006. return this._emission;
  25007. }
  25008. get aliveParticleCount() {
  25009. if (this._firstNewElement >= this._firstRetiredElement)
  25010. return this._firstNewElement - this._firstRetiredElement;
  25011. else
  25012. return this._bufferMaxParticles - this._firstRetiredElement + this._firstNewElement;
  25013. }
  25014. get emissionTime() {
  25015. return this._emissionTime > this.duration ? this.duration : this._emissionTime;
  25016. }
  25017. get shape() {
  25018. return this._shape;
  25019. }
  25020. set shape(value) {
  25021. if (this._shape !== value) {
  25022. if (value && value.enable)
  25023. this._owner._render._shaderValues.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE);
  25024. else
  25025. this._owner._render._shaderValues.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE);
  25026. this._shape = value;
  25027. }
  25028. }
  25029. get isAlive() {
  25030. if (this._isPlaying || this.aliveParticleCount > 0)
  25031. return true;
  25032. return false;
  25033. }
  25034. get isEmitting() {
  25035. return this._isEmitting;
  25036. }
  25037. get isPlaying() {
  25038. return this._isPlaying;
  25039. }
  25040. get isPaused() {
  25041. return this._isPaused;
  25042. }
  25043. get startLifetimeType() {
  25044. return this._startLifetimeType;
  25045. }
  25046. set startLifetimeType(value) {
  25047. var i, n;
  25048. switch (this.startLifetimeType) {
  25049. case 0:
  25050. this._maxStartLifetime = this.startLifetimeConstant;
  25051. break;
  25052. case 1:
  25053. this._maxStartLifetime = -Number.MAX_VALUE;
  25054. var startLifeTimeGradient = startLifeTimeGradient;
  25055. for (i = 0, n = startLifeTimeGradient.gradientCount; i < n; i++)
  25056. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradient.getValueByIndex(i));
  25057. break;
  25058. case 2:
  25059. this._maxStartLifetime = Math.max(this.startLifetimeConstantMin, this.startLifetimeConstantMax);
  25060. break;
  25061. case 3:
  25062. this._maxStartLifetime = -Number.MAX_VALUE;
  25063. var startLifeTimeGradientMin = startLifeTimeGradientMin;
  25064. for (i = 0, n = startLifeTimeGradientMin.gradientCount; i < n; i++)
  25065. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradientMin.getValueByIndex(i));
  25066. var startLifeTimeGradientMax = startLifeTimeGradientMax;
  25067. for (i = 0, n = startLifeTimeGradientMax.gradientCount; i < n; i++)
  25068. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradientMax.getValueByIndex(i));
  25069. break;
  25070. }
  25071. this._startLifetimeType = value;
  25072. }
  25073. get startLifetimeConstant() {
  25074. return this._startLifetimeConstant;
  25075. }
  25076. set startLifetimeConstant(value) {
  25077. if (this._startLifetimeType === 0)
  25078. this._maxStartLifetime = value;
  25079. this._startLifetimeConstant = value;
  25080. }
  25081. get startLifeTimeGradient() {
  25082. return this._startLifeTimeGradient;
  25083. }
  25084. set startLifeTimeGradient(value) {
  25085. if (this._startLifetimeType === 1) {
  25086. this._maxStartLifetime = -Number.MAX_VALUE;
  25087. for (var i = 0, n = value.gradientCount; i < n; i++)
  25088. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  25089. }
  25090. this._startLifeTimeGradient = value;
  25091. }
  25092. get startLifetimeConstantMin() {
  25093. return this._startLifetimeConstantMin;
  25094. }
  25095. set startLifetimeConstantMin(value) {
  25096. if (this._startLifetimeType === 2)
  25097. this._maxStartLifetime = Math.max(value, this._startLifetimeConstantMax);
  25098. this._startLifetimeConstantMin = value;
  25099. }
  25100. get startLifetimeConstantMax() {
  25101. return this._startLifetimeConstantMax;
  25102. }
  25103. set startLifetimeConstantMax(value) {
  25104. if (this._startLifetimeType === 2)
  25105. this._maxStartLifetime = Math.max(this._startLifetimeConstantMin, value);
  25106. this._startLifetimeConstantMax = value;
  25107. }
  25108. get startLifeTimeGradientMin() {
  25109. return this._startLifeTimeGradientMin;
  25110. }
  25111. set startLifeTimeGradientMin(value) {
  25112. if (this._startLifetimeType === 3) {
  25113. var i, n;
  25114. this._maxStartLifetime = -Number.MAX_VALUE;
  25115. for (i = 0, n = value.gradientCount; i < n; i++)
  25116. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  25117. for (i = 0, n = this._startLifeTimeGradientMax.gradientCount; i < n; i++)
  25118. this._maxStartLifetime = Math.max(this._maxStartLifetime, this._startLifeTimeGradientMax.getValueByIndex(i));
  25119. }
  25120. this._startLifeTimeGradientMin = value;
  25121. }
  25122. get startLifeTimeGradientMax() {
  25123. return this._startLifeTimeGradientMax;
  25124. }
  25125. set startLifeTimeGradientMax(value) {
  25126. if (this._startLifetimeType === 3) {
  25127. var i, n;
  25128. this._maxStartLifetime = -Number.MAX_VALUE;
  25129. for (i = 0, n = this._startLifeTimeGradientMin.gradientCount; i < n; i++)
  25130. this._maxStartLifetime = Math.max(this._maxStartLifetime, this._startLifeTimeGradientMin.getValueByIndex(i));
  25131. for (i = 0, n = value.gradientCount; i < n; i++)
  25132. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  25133. }
  25134. this._startLifeTimeGradientMax = value;
  25135. }
  25136. get velocityOverLifetime() {
  25137. return this._velocityOverLifetime;
  25138. }
  25139. set velocityOverLifetime(value) {
  25140. var shaDat = this._owner._render._shaderValues;
  25141. if (value) {
  25142. var velocity = value.velocity;
  25143. var velocityType = velocity.type;
  25144. if (value.enable) {
  25145. switch (velocityType) {
  25146. case 0:
  25147. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  25148. break;
  25149. case 1:
  25150. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  25151. break;
  25152. case 2:
  25153. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  25154. break;
  25155. case 3:
  25156. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  25157. break;
  25158. }
  25159. }
  25160. else {
  25161. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  25162. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  25163. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  25164. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  25165. }
  25166. switch (velocityType) {
  25167. case 0:
  25168. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST, velocity.constant);
  25169. break;
  25170. case 1:
  25171. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX, velocity.gradientX._elements);
  25172. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY, velocity.gradientY._elements);
  25173. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ, velocity.gradientZ._elements);
  25174. break;
  25175. case 2:
  25176. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST, velocity.constantMin);
  25177. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONSTMAX, velocity.constantMax);
  25178. break;
  25179. case 3:
  25180. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX, velocity.gradientXMin._elements);
  25181. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTXMAX, velocity.gradientXMax._elements);
  25182. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY, velocity.gradientYMin._elements);
  25183. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTYMAX, velocity.gradientYMax._elements);
  25184. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ, velocity.gradientZMin._elements);
  25185. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZMAX, velocity.gradientZMax._elements);
  25186. break;
  25187. }
  25188. shaDat.setInt(ShuriKenParticle3DShaderDeclaration.VOLSPACETYPE, value.space);
  25189. }
  25190. else {
  25191. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  25192. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  25193. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  25194. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  25195. }
  25196. this._velocityOverLifetime = value;
  25197. }
  25198. get colorOverLifetime() {
  25199. return this._colorOverLifetime;
  25200. }
  25201. set colorOverLifetime(value) {
  25202. var shaDat = this._owner._render._shaderValues;
  25203. if (value) {
  25204. var color = value.color;
  25205. if (value.enable) {
  25206. switch (color.type) {
  25207. case 1:
  25208. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  25209. break;
  25210. case 3:
  25211. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  25212. break;
  25213. }
  25214. }
  25215. else {
  25216. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  25217. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  25218. }
  25219. switch (color.type) {
  25220. case 1:
  25221. var gradientColor = color.gradient;
  25222. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, gradientColor._alphaElements);
  25223. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, gradientColor._rgbElements);
  25224. break;
  25225. case 3:
  25226. var minGradientColor = color.gradientMin;
  25227. var maxGradientColor = color.gradientMax;
  25228. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, minGradientColor._alphaElements);
  25229. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, minGradientColor._rgbElements);
  25230. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS, maxGradientColor._alphaElements);
  25231. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS, maxGradientColor._rgbElements);
  25232. break;
  25233. }
  25234. }
  25235. else {
  25236. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  25237. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  25238. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, gradientColor._alphaElements);
  25239. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, gradientColor._rgbElements);
  25240. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, minGradientColor._alphaElements);
  25241. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, minGradientColor._rgbElements);
  25242. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS, maxGradientColor._alphaElements);
  25243. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS, maxGradientColor._rgbElements);
  25244. }
  25245. this._colorOverLifetime = value;
  25246. }
  25247. get sizeOverLifetime() {
  25248. return this._sizeOverLifetime;
  25249. }
  25250. set sizeOverLifetime(value) {
  25251. var shaDat = this._owner._render._shaderValues;
  25252. if (value) {
  25253. var size = value.size;
  25254. var sizeSeparate = size.separateAxes;
  25255. var sizeType = size.type;
  25256. if (value.enable) {
  25257. switch (sizeType) {
  25258. case 0:
  25259. if (sizeSeparate)
  25260. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  25261. else
  25262. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  25263. break;
  25264. case 2:
  25265. if (sizeSeparate)
  25266. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  25267. else
  25268. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  25269. break;
  25270. }
  25271. }
  25272. else {
  25273. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  25274. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  25275. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  25276. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  25277. }
  25278. switch (sizeType) {
  25279. case 0:
  25280. if (sizeSeparate) {
  25281. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX, size.gradientX._elements);
  25282. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY, size.gradientY._elements);
  25283. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ, size.gradientZ._elements);
  25284. }
  25285. else {
  25286. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT, size.gradient._elements);
  25287. }
  25288. break;
  25289. case 2:
  25290. if (sizeSeparate) {
  25291. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX, size.gradientXMin._elements);
  25292. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTXMAX, size.gradientXMax._elements);
  25293. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY, size.gradientYMin._elements);
  25294. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTYMAX, size.gradientYMax._elements);
  25295. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ, size.gradientZMin._elements);
  25296. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZMAX, size.gradientZMax._elements);
  25297. }
  25298. else {
  25299. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT, size.gradientMin._elements);
  25300. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientMax, size.gradientMax._elements);
  25301. }
  25302. break;
  25303. }
  25304. }
  25305. else {
  25306. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  25307. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  25308. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  25309. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  25310. }
  25311. this._sizeOverLifetime = value;
  25312. }
  25313. get rotationOverLifetime() {
  25314. return this._rotationOverLifetime;
  25315. }
  25316. set rotationOverLifetime(value) {
  25317. var shaDat = this._owner._render._shaderValues;
  25318. if (value) {
  25319. var rotation = value.angularVelocity;
  25320. if (!rotation)
  25321. return;
  25322. var rotationSeparate = rotation.separateAxes;
  25323. var rotationType = rotation.type;
  25324. if (value.enable) {
  25325. if (rotationSeparate)
  25326. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  25327. else
  25328. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  25329. switch (rotationType) {
  25330. case 0:
  25331. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  25332. break;
  25333. case 1:
  25334. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  25335. break;
  25336. case 2:
  25337. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  25338. break;
  25339. case 3:
  25340. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  25341. break;
  25342. }
  25343. }
  25344. else {
  25345. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  25346. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  25347. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  25348. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  25349. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  25350. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  25351. }
  25352. switch (rotationType) {
  25353. case 0:
  25354. if (rotationSeparate) {
  25355. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE, rotation.constantSeparate);
  25356. }
  25357. else {
  25358. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST, rotation.constant);
  25359. }
  25360. break;
  25361. case 1:
  25362. if (rotationSeparate) {
  25363. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX, rotation.gradientX._elements);
  25364. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY, rotation.gradientY._elements);
  25365. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ, rotation.gradientZ._elements);
  25366. }
  25367. else {
  25368. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT, rotation.gradient._elements);
  25369. }
  25370. break;
  25371. case 2:
  25372. if (rotationSeparate) {
  25373. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE, rotation.constantMinSeparate);
  25374. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAXSEPRARATE, rotation.constantMaxSeparate);
  25375. }
  25376. else {
  25377. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST, rotation.constantMin);
  25378. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAX, rotation.constantMax);
  25379. }
  25380. break;
  25381. case 3:
  25382. if (rotationSeparate) {
  25383. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX, rotation.gradientXMin._elements);
  25384. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTXMAX, rotation.gradientXMax._elements);
  25385. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY, rotation.gradientYMin._elements);
  25386. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTYMAX, rotation.gradientYMax._elements);
  25387. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ, rotation.gradientZMin._elements);
  25388. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZMAX, rotation.gradientZMax._elements);
  25389. }
  25390. else {
  25391. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT, rotation.gradientMin._elements);
  25392. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTMAX, rotation.gradientMax._elements);
  25393. }
  25394. break;
  25395. }
  25396. }
  25397. else {
  25398. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  25399. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  25400. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  25401. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  25402. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  25403. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  25404. }
  25405. this._rotationOverLifetime = value;
  25406. }
  25407. get textureSheetAnimation() {
  25408. return this._textureSheetAnimation;
  25409. }
  25410. set textureSheetAnimation(value) {
  25411. var shaDat = this._owner._render._shaderValues;
  25412. if (value) {
  25413. var frameOverTime = value.frame;
  25414. var textureAniType = frameOverTime.type;
  25415. if (value.enable) {
  25416. switch (textureAniType) {
  25417. case 1:
  25418. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  25419. break;
  25420. case 3:
  25421. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  25422. break;
  25423. }
  25424. }
  25425. else {
  25426. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  25427. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  25428. }
  25429. if (textureAniType === 1 || textureAniType === 3) {
  25430. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONCYCLES, value.cycles);
  25431. var title = value.tiles;
  25432. var _uvLengthE = this._uvLength;
  25433. _uvLengthE.x = 1.0 / title.x;
  25434. _uvLengthE.y = 1.0 / title.y;
  25435. shaDat.setVector2(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONSUBUVLENGTH, this._uvLength);
  25436. }
  25437. switch (textureAniType) {
  25438. case 1:
  25439. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS, frameOverTime.frameOverTimeData._elements);
  25440. break;
  25441. case 3:
  25442. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS, frameOverTime.frameOverTimeDataMin._elements);
  25443. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTMAXUVS, frameOverTime.frameOverTimeDataMax._elements);
  25444. break;
  25445. }
  25446. }
  25447. else {
  25448. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  25449. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  25450. }
  25451. this._textureSheetAnimation = value;
  25452. }
  25453. _getVertexBuffer(index = 0) {
  25454. if (index === 0)
  25455. return this._vertexBuffer;
  25456. else
  25457. return null;
  25458. }
  25459. _getIndexBuffer() {
  25460. return this._indexBuffer;
  25461. }
  25462. _generateBoundingSphere() {
  25463. var centerE = this._boundingSphere.center;
  25464. centerE.x = 0;
  25465. centerE.y = 0;
  25466. centerE.z = 0;
  25467. this._boundingSphere.radius = Number.MAX_VALUE;
  25468. }
  25469. _generateBoundingBox() {
  25470. var particle = this._owner;
  25471. var particleRender = particle.particleRenderer;
  25472. var boundMin = this._boundingBox.min;
  25473. var boundMax = this._boundingBox.max;
  25474. var i, n;
  25475. var maxStartLifeTime;
  25476. switch (this.startLifetimeType) {
  25477. case 0:
  25478. maxStartLifeTime = this.startLifetimeConstant;
  25479. break;
  25480. case 1:
  25481. maxStartLifeTime = -Number.MAX_VALUE;
  25482. var startLifeTimeGradient = startLifeTimeGradient;
  25483. for (i = 0, n = startLifeTimeGradient.gradientCount; i < n; i++)
  25484. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradient.getValueByIndex(i));
  25485. break;
  25486. case 2:
  25487. maxStartLifeTime = Math.max(this.startLifetimeConstantMin, this.startLifetimeConstantMax);
  25488. break;
  25489. case 3:
  25490. maxStartLifeTime = -Number.MAX_VALUE;
  25491. var startLifeTimeGradientMin = startLifeTimeGradientMin;
  25492. for (i = 0, n = startLifeTimeGradientMin.gradientCount; i < n; i++)
  25493. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradientMin.getValueByIndex(i));
  25494. var startLifeTimeGradientMax = startLifeTimeGradientMax;
  25495. for (i = 0, n = startLifeTimeGradientMax.gradientCount; i < n; i++)
  25496. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradientMax.getValueByIndex(i));
  25497. break;
  25498. }
  25499. var minStartSpeed, maxStartSpeed;
  25500. switch (this.startSpeedType) {
  25501. case 0:
  25502. minStartSpeed = maxStartSpeed = this.startSpeedConstant;
  25503. break;
  25504. case 1:
  25505. break;
  25506. case 2:
  25507. minStartSpeed = this.startLifetimeConstantMin;
  25508. maxStartSpeed = this.startLifetimeConstantMax;
  25509. break;
  25510. case 3:
  25511. break;
  25512. }
  25513. var minPosition, maxPosition, minDirection, maxDirection;
  25514. if (this._shape && this._shape.enable) ;
  25515. else {
  25516. minPosition = maxPosition = Vector3._ZERO;
  25517. minDirection = Vector3._ZERO;
  25518. maxDirection = Vector3._UnitZ;
  25519. }
  25520. var startMinVelocity = new Vector3(minDirection.x * minStartSpeed, minDirection.y * minStartSpeed, minDirection.z * minStartSpeed);
  25521. var startMaxVelocity = new Vector3(maxDirection.x * maxStartSpeed, maxDirection.y * maxStartSpeed, maxDirection.z * maxStartSpeed);
  25522. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) {
  25523. var lifeMinVelocity;
  25524. var lifeMaxVelocity;
  25525. var velocity = this._velocityOverLifetime.velocity;
  25526. switch (velocity.type) {
  25527. case 0:
  25528. lifeMinVelocity = lifeMaxVelocity = velocity.constant;
  25529. break;
  25530. case 1:
  25531. lifeMinVelocity = lifeMaxVelocity = new Vector3(velocity.gradientX.getAverageValue(), velocity.gradientY.getAverageValue(), velocity.gradientZ.getAverageValue());
  25532. break;
  25533. case 2:
  25534. lifeMinVelocity = velocity.constantMin;
  25535. lifeMaxVelocity = velocity.constantMax;
  25536. break;
  25537. case 3:
  25538. lifeMinVelocity = new Vector3(velocity.gradientXMin.getAverageValue(), velocity.gradientYMin.getAverageValue(), velocity.gradientZMin.getAverageValue());
  25539. lifeMaxVelocity = new Vector3(velocity.gradientXMax.getAverageValue(), velocity.gradientYMax.getAverageValue(), velocity.gradientZMax.getAverageValue());
  25540. break;
  25541. }
  25542. }
  25543. var positionScale, velocityScale;
  25544. var transform = this._owner.transform;
  25545. var worldPosition = transform.position;
  25546. var sizeScale = ShurikenParticleSystem._tempVector39;
  25547. var renderMode = particleRender.renderMode;
  25548. switch (this.scaleMode) {
  25549. case 0:
  25550. var scale = transform.getWorldLossyScale();
  25551. positionScale = scale;
  25552. sizeScale.x = scale.x;
  25553. sizeScale.y = scale.z;
  25554. sizeScale.z = scale.y;
  25555. (renderMode === 1) && (velocityScale = scale);
  25556. break;
  25557. case 1:
  25558. var localScale = transform.localScale;
  25559. positionScale = localScale;
  25560. sizeScale.x = localScale.x;
  25561. sizeScale.y = localScale.z;
  25562. sizeScale.z = localScale.y;
  25563. (renderMode === 1) && (velocityScale = localScale);
  25564. break;
  25565. case 2:
  25566. positionScale = transform.getWorldLossyScale();
  25567. sizeScale.x = sizeScale.y = sizeScale.z = 1;
  25568. (renderMode === 1) && (velocityScale = Vector3._ONE);
  25569. break;
  25570. }
  25571. var minStratPosition, maxStratPosition;
  25572. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) ;
  25573. else {
  25574. minStratPosition = new Vector3(startMinVelocity.x * maxStartLifeTime, startMinVelocity.y * maxStartLifeTime, startMinVelocity.z * maxStartLifeTime);
  25575. maxStratPosition = new Vector3(startMaxVelocity.x * maxStartLifeTime, startMaxVelocity.y * maxStartLifeTime, startMaxVelocity.z * maxStartLifeTime);
  25576. if (this.scaleMode != 2) {
  25577. Vector3.add(minPosition, minStratPosition, boundMin);
  25578. Vector3.multiply(positionScale, boundMin, boundMin);
  25579. Vector3.add(maxPosition, maxStratPosition, boundMax);
  25580. Vector3.multiply(positionScale, boundMax, boundMax);
  25581. }
  25582. else {
  25583. Vector3.multiply(positionScale, minPosition, boundMin);
  25584. Vector3.add(boundMin, minStratPosition, boundMin);
  25585. Vector3.multiply(positionScale, maxPosition, boundMax);
  25586. Vector3.add(boundMax, maxStratPosition, boundMax);
  25587. }
  25588. }
  25589. switch (this.simulationSpace) {
  25590. case 0:
  25591. break;
  25592. case 1:
  25593. Vector3.add(boundMin, worldPosition, boundMin);
  25594. Vector3.add(boundMax, worldPosition, boundMax);
  25595. break;
  25596. }
  25597. var maxSize, maxSizeY;
  25598. switch (this.startSizeType) {
  25599. case 0:
  25600. if (this.threeDStartSize) {
  25601. var startSizeConstantSeparate = startSizeConstantSeparate;
  25602. maxSize = Math.max(startSizeConstantSeparate.x, startSizeConstantSeparate.y);
  25603. if (renderMode === 1)
  25604. maxSizeY = startSizeConstantSeparate.y;
  25605. }
  25606. else {
  25607. maxSize = this.startSizeConstant;
  25608. if (renderMode === 1)
  25609. maxSizeY = this.startSizeConstant;
  25610. }
  25611. break;
  25612. case 1:
  25613. break;
  25614. case 2:
  25615. if (this.threeDStartSize) {
  25616. var startSizeConstantMaxSeparate = startSizeConstantMaxSeparate;
  25617. maxSize = Math.max(startSizeConstantMaxSeparate.x, startSizeConstantMaxSeparate.y);
  25618. if (renderMode === 1)
  25619. maxSizeY = startSizeConstantMaxSeparate.y;
  25620. }
  25621. else {
  25622. maxSize = this.startSizeConstantMax;
  25623. if (renderMode === 1)
  25624. maxSizeY = this.startSizeConstantMax;
  25625. }
  25626. break;
  25627. case 3:
  25628. break;
  25629. }
  25630. if (this._sizeOverLifetime && this._sizeOverLifetime.enable) {
  25631. var size = this._sizeOverLifetime.size;
  25632. maxSize *= this._sizeOverLifetime.size.getMaxSizeInGradient();
  25633. }
  25634. var threeDMaxSize = ShurikenParticleSystem._tempVector30;
  25635. var rotSize, nonRotSize;
  25636. switch (renderMode) {
  25637. case 0:
  25638. rotSize = maxSize * ShurikenParticleSystem.halfKSqrtOf2;
  25639. Vector3.scale(sizeScale, maxSize, threeDMaxSize);
  25640. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  25641. Vector3.add(boundMax, threeDMaxSize, boundMax);
  25642. break;
  25643. case 1:
  25644. var maxStretchPosition = ShurikenParticleSystem._tempVector31;
  25645. var maxStretchVelocity = ShurikenParticleSystem._tempVector32;
  25646. var minStretchVelocity = ShurikenParticleSystem._tempVector33;
  25647. var minStretchPosition = ShurikenParticleSystem._tempVector34;
  25648. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) ;
  25649. else {
  25650. Vector3.multiply(velocityScale, startMaxVelocity, maxStretchVelocity);
  25651. Vector3.multiply(velocityScale, startMinVelocity, minStretchVelocity);
  25652. }
  25653. var sizeStretch = maxSizeY * particleRender.stretchedBillboardLengthScale;
  25654. var maxStretchLength = Vector3.scalarLength(maxStretchVelocity) * particleRender.stretchedBillboardSpeedScale + sizeStretch;
  25655. var minStretchLength = Vector3.scalarLength(minStretchVelocity) * particleRender.stretchedBillboardSpeedScale + sizeStretch;
  25656. var norMaxStretchVelocity = ShurikenParticleSystem._tempVector35;
  25657. var norMinStretchVelocity = ShurikenParticleSystem._tempVector36;
  25658. Vector3.normalize(maxStretchVelocity, norMaxStretchVelocity);
  25659. Vector3.scale(norMaxStretchVelocity, maxStretchLength, minStretchPosition);
  25660. Vector3.subtract(maxStratPosition, minStretchPosition, minStretchPosition);
  25661. Vector3.normalize(minStretchVelocity, norMinStretchVelocity);
  25662. Vector3.scale(norMinStretchVelocity, minStretchLength, maxStretchPosition);
  25663. Vector3.add(minStratPosition, maxStretchPosition, maxStretchPosition);
  25664. rotSize = maxSize * ShurikenParticleSystem.halfKSqrtOf2;
  25665. Vector3.scale(sizeScale, rotSize, threeDMaxSize);
  25666. var halfNorMaxStretchVelocity = ShurikenParticleSystem._tempVector37;
  25667. var halfNorMinStretchVelocity = ShurikenParticleSystem._tempVector38;
  25668. Vector3.scale(norMaxStretchVelocity, 0.5, halfNorMaxStretchVelocity);
  25669. Vector3.scale(norMinStretchVelocity, 0.5, halfNorMinStretchVelocity);
  25670. Vector3.multiply(halfNorMaxStretchVelocity, sizeScale, halfNorMaxStretchVelocity);
  25671. Vector3.multiply(halfNorMinStretchVelocity, sizeScale, halfNorMinStretchVelocity);
  25672. Vector3.add(boundMin, halfNorMinStretchVelocity, boundMin);
  25673. Vector3.min(boundMin, minStretchPosition, boundMin);
  25674. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  25675. Vector3.subtract(boundMax, halfNorMaxStretchVelocity, boundMax);
  25676. Vector3.max(boundMax, maxStretchPosition, boundMax);
  25677. Vector3.add(boundMax, threeDMaxSize, boundMax);
  25678. break;
  25679. case 2:
  25680. maxSize *= Math.cos(0.78539816339744830961566084581988);
  25681. nonRotSize = maxSize * 0.5;
  25682. threeDMaxSize.x = sizeScale.x * nonRotSize;
  25683. threeDMaxSize.y = sizeScale.z * nonRotSize;
  25684. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  25685. Vector3.add(boundMax, threeDMaxSize, boundMax);
  25686. break;
  25687. case 3:
  25688. maxSize *= Math.cos(0.78539816339744830961566084581988);
  25689. nonRotSize = maxSize * 0.5;
  25690. Vector3.scale(sizeScale, nonRotSize, threeDMaxSize);
  25691. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  25692. Vector3.add(boundMax, threeDMaxSize, boundMax);
  25693. break;
  25694. }
  25695. this._boundingBox.getCorners(this._boundingBoxCorners);
  25696. }
  25697. _updateEmission() {
  25698. if (!this.isAlive)
  25699. return;
  25700. if (this._simulateUpdate) {
  25701. this._simulateUpdate = false;
  25702. }
  25703. else {
  25704. var elapsedTime = (this._startUpdateLoopCount !== Laya.Stat.loopCount && !this._isPaused) ? this._owner._scene.timer._delta / 1000.0 : 0;
  25705. elapsedTime = Math.min(ShurikenParticleSystem._maxElapsedTime, elapsedTime * this.simulationSpeed);
  25706. this._updateParticles(elapsedTime);
  25707. }
  25708. }
  25709. _updateParticles(elapsedTime) {
  25710. if (this._ownerRender.renderMode === 4 && !this._ownerRender.mesh)
  25711. return;
  25712. this._currentTime += elapsedTime;
  25713. this._retireActiveParticles();
  25714. this._freeRetiredParticles();
  25715. this._totalDelayTime += elapsedTime;
  25716. if (this._totalDelayTime < this._playStartDelay) {
  25717. return;
  25718. }
  25719. if (this._emission.enable && this._isEmitting && !this._isPaused)
  25720. this._advanceTime(elapsedTime, this._currentTime);
  25721. }
  25722. _updateParticlesSimulationRestart(time) {
  25723. this._firstActiveElement = 0;
  25724. this._firstNewElement = 0;
  25725. this._firstFreeElement = 0;
  25726. this._firstRetiredElement = 0;
  25727. this._burstsIndex = 0;
  25728. this._frameRateTime = time;
  25729. this._emissionTime = 0;
  25730. this._totalDelayTime = 0;
  25731. this._currentTime = time;
  25732. var delayTime = time;
  25733. if (delayTime < this._playStartDelay) {
  25734. this._totalDelayTime = delayTime;
  25735. return;
  25736. }
  25737. if (this._emission.enable)
  25738. this._advanceTime(time, time);
  25739. }
  25740. _retireActiveParticles() {
  25741. const epsilon = 0.0001;
  25742. while (this._firstActiveElement != this._firstNewElement) {
  25743. var index = this._firstActiveElement * this._floatCountPerVertex * this._vertexStride;
  25744. var timeIndex = index + this._timeIndex;
  25745. var particleAge = this._currentTime - this._vertices[timeIndex];
  25746. if (particleAge + epsilon < this._vertices[index + this._startLifeTimeIndex])
  25747. break;
  25748. this._vertices[timeIndex] = this._drawCounter;
  25749. this._firstActiveElement++;
  25750. if (this._firstActiveElement >= this._bufferMaxParticles)
  25751. this._firstActiveElement = 0;
  25752. }
  25753. }
  25754. _freeRetiredParticles() {
  25755. while (this._firstRetiredElement != this._firstActiveElement) {
  25756. var age = this._drawCounter - this._vertices[this._firstRetiredElement * this._floatCountPerVertex * this._vertexStride + this._timeIndex];
  25757. if (this.isPerformanceMode)
  25758. if (age < 3)
  25759. break;
  25760. this._firstRetiredElement++;
  25761. if (this._firstRetiredElement >= this._bufferMaxParticles)
  25762. this._firstRetiredElement = 0;
  25763. }
  25764. }
  25765. _burst(fromTime, toTime) {
  25766. var totalEmitCount = 0;
  25767. var bursts = this._emission._bursts;
  25768. for (var n = bursts.length; this._burstsIndex < n; this._burstsIndex++) {
  25769. var burst = bursts[this._burstsIndex];
  25770. var burstTime = burst.time;
  25771. if (fromTime <= burstTime && burstTime < toTime) {
  25772. var emitCount;
  25773. if (this.autoRandomSeed) {
  25774. emitCount = Laya.MathUtil.lerp(burst.minCount, burst.maxCount, Math.random());
  25775. }
  25776. else {
  25777. this._rand.seed = this._randomSeeds[0];
  25778. emitCount = Laya.MathUtil.lerp(burst.minCount, burst.maxCount, this._rand.getFloat());
  25779. this._randomSeeds[0] = this._rand.seed;
  25780. }
  25781. totalEmitCount += emitCount;
  25782. }
  25783. else {
  25784. break;
  25785. }
  25786. }
  25787. return totalEmitCount;
  25788. }
  25789. _advanceTime(elapsedTime, emitTime) {
  25790. var i;
  25791. var lastEmissionTime = this._emissionTime;
  25792. this._emissionTime += elapsedTime;
  25793. var totalEmitCount = 0;
  25794. if (this._emissionTime > this.duration) {
  25795. if (this.looping) {
  25796. totalEmitCount += this._burst(lastEmissionTime, this._emissionTime);
  25797. this._emissionTime -= this.duration;
  25798. this._burstsIndex = 0;
  25799. totalEmitCount += this._burst(0, this._emissionTime);
  25800. }
  25801. else {
  25802. totalEmitCount = Math.min(this.maxParticles - this.aliveParticleCount, totalEmitCount);
  25803. for (i = 0; i < totalEmitCount; i++)
  25804. this.emit(emitTime);
  25805. this._isPlaying = false;
  25806. this.stop();
  25807. return;
  25808. }
  25809. }
  25810. else {
  25811. totalEmitCount += this._burst(lastEmissionTime, this._emissionTime);
  25812. }
  25813. totalEmitCount = Math.min(this.maxParticles - this.aliveParticleCount, totalEmitCount);
  25814. for (i = 0; i < totalEmitCount; i++)
  25815. this.emit(emitTime);
  25816. var emissionRate = this.emission.emissionRate;
  25817. if (emissionRate > 0) {
  25818. var minEmissionTime = 1 / emissionRate;
  25819. this._frameRateTime += minEmissionTime;
  25820. this._frameRateTime = this._currentTime - (this._currentTime - this._frameRateTime) % this._maxStartLifetime;
  25821. while (this._frameRateTime <= emitTime) {
  25822. if (this.emit(this._frameRateTime))
  25823. this._frameRateTime += minEmissionTime;
  25824. else
  25825. break;
  25826. }
  25827. this._frameRateTime = Math.floor(emitTime / minEmissionTime) * minEmissionTime;
  25828. }
  25829. }
  25830. _initBufferDatas() {
  25831. if (this._vertexBuffer) {
  25832. this._vertexBuffer.destroy();
  25833. this._indexBuffer.destroy();
  25834. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer.indexCount * 2;
  25835. Laya.Resource._addMemory(-memorySize, -memorySize);
  25836. }
  25837. var gl = Laya.LayaGL.instance;
  25838. var render = this._ownerRender;
  25839. var renderMode = render.renderMode;
  25840. if (renderMode !== -1 && this.maxParticles > 0) {
  25841. var indices, i, j, m, indexOffset, perPartOffset, vertexDeclaration;
  25842. var vbMemorySize = 0, memorySize = 0;
  25843. var mesh = render.mesh;
  25844. if (renderMode === 4) {
  25845. if (mesh) {
  25846. vertexDeclaration = VertexShurikenParticleMesh.vertexDeclaration;
  25847. this._floatCountPerVertex = vertexDeclaration.vertexStride / 4;
  25848. this._startLifeTimeIndex = 12;
  25849. this._timeIndex = 16;
  25850. this._vertexStride = mesh._vertexCount;
  25851. var totalVertexCount = this._bufferMaxParticles * this._vertexStride;
  25852. var vbCount = Math.floor(totalVertexCount / 65535) + 1;
  25853. var lastVBVertexCount = totalVertexCount % 65535;
  25854. if (vbCount > 1) {
  25855. throw new Error("ShurikenParticleSystem:the maxParticleCount multiply mesh vertexCount is large than 65535.");
  25856. }
  25857. vbMemorySize = vertexDeclaration.vertexStride * lastVBVertexCount;
  25858. this._vertexBuffer = new VertexBuffer3D(vbMemorySize, gl.DYNAMIC_DRAW);
  25859. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  25860. this._vertices = new Float32Array(this._floatCountPerVertex * lastVBVertexCount);
  25861. this._indexStride = mesh._indexBuffer.indexCount;
  25862. var indexDatas = mesh._indexBuffer.getData();
  25863. var indexCount = this._bufferMaxParticles * this._indexStride;
  25864. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indexCount, gl.STATIC_DRAW);
  25865. indices = new Uint16Array(indexCount);
  25866. memorySize = vbMemorySize + indexCount * 2;
  25867. indexOffset = 0;
  25868. for (i = 0; i < this._bufferMaxParticles; i++) {
  25869. var indexValueOffset = i * this._vertexStride;
  25870. for (j = 0, m = indexDatas.length; j < m; j++)
  25871. indices[indexOffset++] = indexValueOffset + indexDatas[j];
  25872. }
  25873. this._indexBuffer.setData(indices);
  25874. this._bufferState.bind();
  25875. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  25876. this._bufferState.applyIndexBuffer(this._indexBuffer);
  25877. this._bufferState.unBind();
  25878. }
  25879. }
  25880. else {
  25881. vertexDeclaration = VertexShurikenParticleBillboard.vertexDeclaration;
  25882. this._floatCountPerVertex = vertexDeclaration.vertexStride / 4;
  25883. this._startLifeTimeIndex = 7;
  25884. this._timeIndex = 11;
  25885. this._vertexStride = 4;
  25886. vbMemorySize = vertexDeclaration.vertexStride * this._bufferMaxParticles * this._vertexStride;
  25887. this._vertexBuffer = new VertexBuffer3D(vbMemorySize, gl.DYNAMIC_DRAW);
  25888. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  25889. this._vertices = new Float32Array(this._floatCountPerVertex * this._bufferMaxParticles * this._vertexStride);
  25890. for (i = 0; i < this._bufferMaxParticles; i++) {
  25891. perPartOffset = i * this._floatCountPerVertex * this._vertexStride;
  25892. this._vertices[perPartOffset] = -0.5;
  25893. this._vertices[perPartOffset + 1] = -0.5;
  25894. this._vertices[perPartOffset + 2] = 0;
  25895. this._vertices[perPartOffset + 3] = 1;
  25896. perPartOffset += this._floatCountPerVertex;
  25897. this._vertices[perPartOffset] = 0.5;
  25898. this._vertices[perPartOffset + 1] = -0.5;
  25899. this._vertices[perPartOffset + 2] = 1;
  25900. this._vertices[perPartOffset + 3] = 1;
  25901. perPartOffset += this._floatCountPerVertex;
  25902. this._vertices[perPartOffset] = 0.5;
  25903. this._vertices[perPartOffset + 1] = 0.5;
  25904. this._vertices[perPartOffset + 2] = 1;
  25905. this._vertices[perPartOffset + 3] = 0;
  25906. perPartOffset += this._floatCountPerVertex;
  25907. this._vertices[perPartOffset] = -0.5;
  25908. this._vertices[perPartOffset + 1] = 0.5;
  25909. this._vertices[perPartOffset + 2] = 0;
  25910. this._vertices[perPartOffset + 3] = 0;
  25911. }
  25912. this._indexStride = 6;
  25913. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._bufferMaxParticles * 6, gl.STATIC_DRAW);
  25914. indices = new Uint16Array(this._bufferMaxParticles * 6);
  25915. for (i = 0; i < this._bufferMaxParticles; i++) {
  25916. indexOffset = i * 6;
  25917. var firstVertex = i * this._vertexStride, secondVertex = firstVertex + 2;
  25918. indices[indexOffset++] = firstVertex;
  25919. indices[indexOffset++] = secondVertex;
  25920. indices[indexOffset++] = firstVertex + 1;
  25921. indices[indexOffset++] = firstVertex;
  25922. indices[indexOffset++] = firstVertex + 3;
  25923. indices[indexOffset++] = secondVertex;
  25924. }
  25925. this._indexBuffer.setData(indices);
  25926. memorySize = vbMemorySize + this._bufferMaxParticles * 6 * 2;
  25927. this._bufferState.bind();
  25928. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  25929. this._bufferState.applyIndexBuffer(this._indexBuffer);
  25930. this._bufferState.unBind();
  25931. }
  25932. Laya.Resource._addMemory(memorySize, memorySize);
  25933. }
  25934. }
  25935. destroy() {
  25936. super.destroy();
  25937. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer.indexCount * 2;
  25938. Laya.Resource._addMemory(-memorySize, -memorySize);
  25939. this._bufferState.destroy();
  25940. this._vertexBuffer.destroy();
  25941. this._indexBuffer.destroy();
  25942. this._emission.destroy();
  25943. this._bufferState = null;
  25944. this._vertexBuffer = null;
  25945. this._indexBuffer = null;
  25946. this._owner = null;
  25947. this._vertices = null;
  25948. this._indexBuffer = null;
  25949. this._emission = null;
  25950. this._shape = null;
  25951. this.startLifeTimeGradient = null;
  25952. this.startLifeTimeGradientMin = null;
  25953. this.startLifeTimeGradientMax = null;
  25954. this.startSizeConstantSeparate = null;
  25955. this.startSizeConstantMinSeparate = null;
  25956. this.startSizeConstantMaxSeparate = null;
  25957. this.startRotationConstantSeparate = null;
  25958. this.startRotationConstantMinSeparate = null;
  25959. this.startRotationConstantMaxSeparate = null;
  25960. this.startColorConstant = null;
  25961. this.startColorConstantMin = null;
  25962. this.startColorConstantMax = null;
  25963. this._velocityOverLifetime = null;
  25964. this._colorOverLifetime = null;
  25965. this._sizeOverLifetime = null;
  25966. this._rotationOverLifetime = null;
  25967. this._textureSheetAnimation = null;
  25968. }
  25969. emit(time) {
  25970. var position = ShurikenParticleSystem._tempPosition;
  25971. var direction = ShurikenParticleSystem._tempDirection;
  25972. if (this._shape && this._shape.enable) {
  25973. if (this.autoRandomSeed)
  25974. this._shape.generatePositionAndDirection(position, direction);
  25975. else
  25976. this._shape.generatePositionAndDirection(position, direction, this._rand, this._randomSeeds);
  25977. }
  25978. else {
  25979. position.x = position.y = position.z = 0;
  25980. direction.x = direction.y = 0;
  25981. direction.z = 1;
  25982. }
  25983. return this.addParticle(position, direction, time);
  25984. }
  25985. addParticle(position, direction, time) {
  25986. Vector3.normalize(direction, direction);
  25987. var nextFreeParticle = this._firstFreeElement + 1;
  25988. if (nextFreeParticle >= this._bufferMaxParticles)
  25989. nextFreeParticle = 0;
  25990. if (nextFreeParticle === this._firstRetiredElement)
  25991. return false;
  25992. var transform = this._owner.transform;
  25993. ShurikenParticleData.create(this, this._ownerRender, transform);
  25994. var particleAge = this._currentTime - time;
  25995. if (particleAge >= ShurikenParticleData.startLifeTime)
  25996. return true;
  25997. var pos, rot;
  25998. if (this.simulationSpace == 0) {
  25999. pos = transform.position;
  26000. rot = transform.rotation;
  26001. }
  26002. var startSpeed;
  26003. switch (this.startSpeedType) {
  26004. case 0:
  26005. startSpeed = this.startSpeedConstant;
  26006. break;
  26007. case 2:
  26008. if (this.autoRandomSeed) {
  26009. startSpeed = Laya.MathUtil.lerp(this.startSpeedConstantMin, this.startSpeedConstantMax, Math.random());
  26010. }
  26011. else {
  26012. this._rand.seed = this._randomSeeds[8];
  26013. startSpeed = Laya.MathUtil.lerp(this.startSpeedConstantMin, this.startSpeedConstantMax, this._rand.getFloat());
  26014. this._randomSeeds[8] = this._rand.seed;
  26015. }
  26016. break;
  26017. }
  26018. var randomVelocityX, randomVelocityY, randomVelocityZ, randomColor, randomSize, randomRotation, randomTextureAnimation;
  26019. var needRandomVelocity = this._velocityOverLifetime && this._velocityOverLifetime.enable;
  26020. if (needRandomVelocity) {
  26021. var velocityType = this._velocityOverLifetime.velocity.type;
  26022. if (velocityType === 2 || velocityType === 3) {
  26023. if (this.autoRandomSeed) {
  26024. randomVelocityX = Math.random();
  26025. randomVelocityY = Math.random();
  26026. randomVelocityZ = Math.random();
  26027. }
  26028. else {
  26029. this._rand.seed = this._randomSeeds[9];
  26030. randomVelocityX = this._rand.getFloat();
  26031. randomVelocityY = this._rand.getFloat();
  26032. randomVelocityZ = this._rand.getFloat();
  26033. this._randomSeeds[9] = this._rand.seed;
  26034. }
  26035. }
  26036. else {
  26037. needRandomVelocity = false;
  26038. }
  26039. }
  26040. else {
  26041. needRandomVelocity = false;
  26042. }
  26043. var needRandomColor = this._colorOverLifetime && this._colorOverLifetime.enable;
  26044. if (needRandomColor) {
  26045. var colorType = this._colorOverLifetime.color.type;
  26046. if (colorType === 3) {
  26047. if (this.autoRandomSeed) {
  26048. randomColor = Math.random();
  26049. }
  26050. else {
  26051. this._rand.seed = this._randomSeeds[10];
  26052. randomColor = this._rand.getFloat();
  26053. this._randomSeeds[10] = this._rand.seed;
  26054. }
  26055. }
  26056. else {
  26057. needRandomColor = false;
  26058. }
  26059. }
  26060. else {
  26061. needRandomColor = false;
  26062. }
  26063. var needRandomSize = this._sizeOverLifetime && this._sizeOverLifetime.enable;
  26064. if (needRandomSize) {
  26065. var sizeType = this._sizeOverLifetime.size.type;
  26066. if (sizeType === 3) {
  26067. if (this.autoRandomSeed) {
  26068. randomSize = Math.random();
  26069. }
  26070. else {
  26071. this._rand.seed = this._randomSeeds[11];
  26072. randomSize = this._rand.getFloat();
  26073. this._randomSeeds[11] = this._rand.seed;
  26074. }
  26075. }
  26076. else {
  26077. needRandomSize = false;
  26078. }
  26079. }
  26080. else {
  26081. needRandomSize = false;
  26082. }
  26083. var needRandomRotation = this._rotationOverLifetime && this._rotationOverLifetime.enable;
  26084. if (needRandomRotation) {
  26085. var rotationType = this._rotationOverLifetime.angularVelocity.type;
  26086. if (rotationType === 2 || rotationType === 3) {
  26087. if (this.autoRandomSeed) {
  26088. randomRotation = Math.random();
  26089. }
  26090. else {
  26091. this._rand.seed = this._randomSeeds[12];
  26092. randomRotation = this._rand.getFloat();
  26093. this._randomSeeds[12] = this._rand.seed;
  26094. }
  26095. }
  26096. else {
  26097. needRandomRotation = false;
  26098. }
  26099. }
  26100. else {
  26101. needRandomRotation = false;
  26102. }
  26103. var needRandomTextureAnimation = this._textureSheetAnimation && this._textureSheetAnimation.enable;
  26104. if (needRandomTextureAnimation) {
  26105. var textureAnimationType = this._textureSheetAnimation.frame.type;
  26106. if (textureAnimationType === 3) {
  26107. if (this.autoRandomSeed) {
  26108. randomTextureAnimation = Math.random();
  26109. }
  26110. else {
  26111. this._rand.seed = this._randomSeeds[15];
  26112. randomTextureAnimation = this._rand.getFloat();
  26113. this._randomSeeds[15] = this._rand.seed;
  26114. }
  26115. }
  26116. else {
  26117. needRandomTextureAnimation = false;
  26118. }
  26119. }
  26120. else {
  26121. needRandomTextureAnimation = false;
  26122. }
  26123. var startIndex = this._firstFreeElement * this._floatCountPerVertex * this._vertexStride;
  26124. var subU = ShurikenParticleData.startUVInfo[0];
  26125. var subV = ShurikenParticleData.startUVInfo[1];
  26126. var startU = ShurikenParticleData.startUVInfo[2];
  26127. var startV = ShurikenParticleData.startUVInfo[3];
  26128. var meshVertices, meshVertexStride, meshPosOffset, meshCorOffset, meshUVOffset, meshVertexIndex;
  26129. var render = this._ownerRender;
  26130. if (render.renderMode === 4) {
  26131. var meshVB = render.mesh._vertexBuffer;
  26132. meshVertices = meshVB.getFloat32Data();
  26133. var meshVertexDeclaration = meshVB.vertexDeclaration;
  26134. meshPosOffset = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  26135. var colorElement = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  26136. meshCorOffset = colorElement ? colorElement._offset / 4 : -1;
  26137. var uvElement = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  26138. meshUVOffset = uvElement ? uvElement._offset / 4 : -1;
  26139. meshVertexStride = meshVertexDeclaration.vertexStride / 4;
  26140. meshVertexIndex = 0;
  26141. }
  26142. else {
  26143. this._vertices[startIndex + 2] = startU;
  26144. this._vertices[startIndex + 3] = startV + subV;
  26145. var secondOffset = startIndex + this._floatCountPerVertex;
  26146. this._vertices[secondOffset + 2] = startU + subU;
  26147. this._vertices[secondOffset + 3] = startV + subV;
  26148. var thirdOffset = secondOffset + this._floatCountPerVertex;
  26149. this._vertices[thirdOffset + 2] = startU + subU;
  26150. this._vertices[thirdOffset + 3] = startV;
  26151. var fourthOffset = thirdOffset + this._floatCountPerVertex;
  26152. this._vertices[fourthOffset + 2] = startU;
  26153. this._vertices[fourthOffset + 3] = startV;
  26154. }
  26155. for (var i = startIndex, n = startIndex + this._floatCountPerVertex * this._vertexStride; i < n; i += this._floatCountPerVertex) {
  26156. var offset;
  26157. if (render.renderMode === 4) {
  26158. offset = i;
  26159. var vertexOffset = meshVertexStride * (meshVertexIndex++);
  26160. var meshOffset = vertexOffset + meshPosOffset;
  26161. this._vertices[offset++] = meshVertices[meshOffset++];
  26162. this._vertices[offset++] = meshVertices[meshOffset++];
  26163. this._vertices[offset++] = meshVertices[meshOffset];
  26164. if (meshCorOffset === -1) {
  26165. this._vertices[offset++] = 1.0;
  26166. this._vertices[offset++] = 1.0;
  26167. this._vertices[offset++] = 1.0;
  26168. this._vertices[offset++] = 1.0;
  26169. }
  26170. else {
  26171. meshOffset = vertexOffset + meshCorOffset;
  26172. this._vertices[offset++] = meshVertices[meshOffset++];
  26173. this._vertices[offset++] = meshVertices[meshOffset++];
  26174. this._vertices[offset++] = meshVertices[meshOffset++];
  26175. this._vertices[offset++] = meshVertices[meshOffset];
  26176. }
  26177. if (meshUVOffset === -1) {
  26178. this._vertices[offset++] = 0.0;
  26179. this._vertices[offset++] = 0.0;
  26180. }
  26181. else {
  26182. meshOffset = vertexOffset + meshUVOffset;
  26183. this._vertices[offset++] = startU + meshVertices[meshOffset++] * subU;
  26184. this._vertices[offset++] = startV + meshVertices[meshOffset] * subV;
  26185. }
  26186. }
  26187. else {
  26188. offset = i + 4;
  26189. }
  26190. this._vertices[offset++] = position.x;
  26191. this._vertices[offset++] = position.y;
  26192. this._vertices[offset++] = position.z;
  26193. this._vertices[offset++] = ShurikenParticleData.startLifeTime;
  26194. this._vertices[offset++] = direction.x;
  26195. this._vertices[offset++] = direction.y;
  26196. this._vertices[offset++] = direction.z;
  26197. this._vertices[offset++] = time;
  26198. this._vertices[offset++] = ShurikenParticleData.startColor.x;
  26199. this._vertices[offset++] = ShurikenParticleData.startColor.y;
  26200. this._vertices[offset++] = ShurikenParticleData.startColor.z;
  26201. this._vertices[offset++] = ShurikenParticleData.startColor.w;
  26202. this._vertices[offset++] = ShurikenParticleData.startSize[0];
  26203. this._vertices[offset++] = ShurikenParticleData.startSize[1];
  26204. this._vertices[offset++] = ShurikenParticleData.startSize[2];
  26205. this._vertices[offset++] = ShurikenParticleData.startRotation[0];
  26206. this._vertices[offset++] = ShurikenParticleData.startRotation[1];
  26207. this._vertices[offset++] = ShurikenParticleData.startRotation[2];
  26208. this._vertices[offset++] = startSpeed;
  26209. needRandomColor && (this._vertices[offset + 1] = randomColor);
  26210. needRandomSize && (this._vertices[offset + 2] = randomSize);
  26211. needRandomRotation && (this._vertices[offset + 3] = randomRotation);
  26212. needRandomTextureAnimation && (this._vertices[offset + 4] = randomTextureAnimation);
  26213. if (needRandomVelocity) {
  26214. this._vertices[offset + 5] = randomVelocityX;
  26215. this._vertices[offset + 6] = randomVelocityY;
  26216. this._vertices[offset + 7] = randomVelocityZ;
  26217. }
  26218. switch (this.simulationSpace) {
  26219. case 0:
  26220. offset += 8;
  26221. this._vertices[offset++] = pos.x;
  26222. this._vertices[offset++] = pos.y;
  26223. this._vertices[offset++] = pos.z;
  26224. this._vertices[offset++] = rot.x;
  26225. this._vertices[offset++] = rot.y;
  26226. this._vertices[offset++] = rot.z;
  26227. this._vertices[offset++] = rot.w;
  26228. break;
  26229. case 1:
  26230. break;
  26231. default:
  26232. throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid.");
  26233. }
  26234. }
  26235. this._firstFreeElement = nextFreeParticle;
  26236. return true;
  26237. }
  26238. addNewParticlesToVertexBuffer() {
  26239. var start;
  26240. var byteStride = this._vertexStride * this._floatCountPerVertex * 4;
  26241. if (this._firstNewElement < this._firstFreeElement) {
  26242. start = this._firstNewElement * byteStride;
  26243. this._vertexBuffer.setData(this._vertices.buffer, start, start, (this._firstFreeElement - this._firstNewElement) * byteStride);
  26244. }
  26245. else {
  26246. start = this._firstNewElement * byteStride;
  26247. this._vertexBuffer.setData(this._vertices.buffer, start, start, (this._bufferMaxParticles - this._firstNewElement) * byteStride);
  26248. if (this._firstFreeElement > 0) {
  26249. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, this._firstFreeElement * byteStride);
  26250. }
  26251. }
  26252. this._firstNewElement = this._firstFreeElement;
  26253. }
  26254. _getType() {
  26255. return ShurikenParticleSystem._type;
  26256. }
  26257. _prepareRender(state) {
  26258. this._updateEmission();
  26259. if (this._firstNewElement != this._firstFreeElement)
  26260. this.addNewParticlesToVertexBuffer();
  26261. this._drawCounter++;
  26262. if (this._firstActiveElement != this._firstFreeElement)
  26263. return true;
  26264. else
  26265. return false;
  26266. }
  26267. _render(state) {
  26268. this._bufferState.bind();
  26269. var indexCount;
  26270. var gl = Laya.LayaGL.instance;
  26271. if (this._firstActiveElement < this._firstFreeElement) {
  26272. indexCount = (this._firstFreeElement - this._firstActiveElement) * this._indexStride;
  26273. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 2 * this._firstActiveElement * this._indexStride);
  26274. Laya.Stat.trianglesFaces += indexCount / 3;
  26275. Laya.Stat.renderBatches++;
  26276. }
  26277. else {
  26278. indexCount = (this._bufferMaxParticles - this._firstActiveElement) * this._indexStride;
  26279. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 2 * this._firstActiveElement * this._indexStride);
  26280. Laya.Stat.trianglesFaces += indexCount / 3;
  26281. Laya.Stat.renderBatches++;
  26282. if (this._firstFreeElement > 0) {
  26283. indexCount = this._firstFreeElement * this._indexStride;
  26284. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  26285. Laya.Stat.trianglesFaces += indexCount / 3;
  26286. Laya.Stat.renderBatches++;
  26287. }
  26288. }
  26289. }
  26290. play() {
  26291. this._burstsIndex = 0;
  26292. this._isEmitting = true;
  26293. this._isPlaying = true;
  26294. this._isPaused = false;
  26295. this._emissionTime = 0;
  26296. this._totalDelayTime = 0;
  26297. if (!this.autoRandomSeed) {
  26298. for (var i = 0, n = this._randomSeeds.length; i < n; i++)
  26299. this._randomSeeds[i] = this.randomSeed[0] + ShurikenParticleSystem._RANDOMOFFSET[i];
  26300. }
  26301. switch (this.startDelayType) {
  26302. case 0:
  26303. this._playStartDelay = this.startDelay;
  26304. break;
  26305. case 1:
  26306. if (this.autoRandomSeed) {
  26307. this._playStartDelay = Laya.MathUtil.lerp(this.startDelayMin, this.startDelayMax, Math.random());
  26308. }
  26309. else {
  26310. this._rand.seed = this._randomSeeds[2];
  26311. this._playStartDelay = Laya.MathUtil.lerp(this.startDelayMin, this.startDelayMax, this._rand.getFloat());
  26312. this._randomSeeds[2] = this._rand.seed;
  26313. }
  26314. break;
  26315. default:
  26316. throw new Error("Utils3D: startDelayType is invalid.");
  26317. }
  26318. this._frameRateTime = this._currentTime + this._playStartDelay;
  26319. this._startUpdateLoopCount = Laya.Stat.loopCount;
  26320. }
  26321. pause() {
  26322. this._isPaused = true;
  26323. }
  26324. simulate(time, restart = true) {
  26325. this._simulateUpdate = true;
  26326. if (restart) {
  26327. this._updateParticlesSimulationRestart(time);
  26328. }
  26329. else {
  26330. this._isPaused = false;
  26331. this._updateParticles(time);
  26332. }
  26333. this.pause();
  26334. }
  26335. stop() {
  26336. this._burstsIndex = 0;
  26337. this._isEmitting = false;
  26338. this._emissionTime = 0;
  26339. }
  26340. cloneTo(destObject) {
  26341. var dest = destObject;
  26342. dest.duration = this.duration;
  26343. dest.looping = this.looping;
  26344. dest.prewarm = this.prewarm;
  26345. dest.startDelayType = this.startDelayType;
  26346. dest.startDelay = this.startDelay;
  26347. dest.startDelayMin = this.startDelayMin;
  26348. dest.startDelayMax = this.startDelayMax;
  26349. dest._maxStartLifetime = this._maxStartLifetime;
  26350. dest.startLifetimeType = this.startLifetimeType;
  26351. dest.startLifetimeConstant = this.startLifetimeConstant;
  26352. this.startLifeTimeGradient.cloneTo(dest.startLifeTimeGradient);
  26353. dest.startLifetimeConstantMin = this.startLifetimeConstantMin;
  26354. dest.startLifetimeConstantMax = this.startLifetimeConstantMax;
  26355. this.startLifeTimeGradientMin.cloneTo(dest.startLifeTimeGradientMin);
  26356. this.startLifeTimeGradientMax.cloneTo(dest.startLifeTimeGradientMax);
  26357. dest.startSpeedType = this.startSpeedType;
  26358. dest.startSpeedConstant = this.startSpeedConstant;
  26359. dest.startSpeedConstantMin = this.startSpeedConstantMin;
  26360. dest.startSpeedConstantMax = this.startSpeedConstantMax;
  26361. dest.threeDStartSize = this.threeDStartSize;
  26362. dest.startSizeType = this.startSizeType;
  26363. dest.startSizeConstant = this.startSizeConstant;
  26364. this.startSizeConstantSeparate.cloneTo(dest.startSizeConstantSeparate);
  26365. dest.startSizeConstantMin = this.startSizeConstantMin;
  26366. dest.startSizeConstantMax = this.startSizeConstantMax;
  26367. this.startSizeConstantMinSeparate.cloneTo(dest.startSizeConstantMinSeparate);
  26368. this.startSizeConstantMaxSeparate.cloneTo(dest.startSizeConstantMaxSeparate);
  26369. dest.threeDStartRotation = this.threeDStartRotation;
  26370. dest.startRotationType = this.startRotationType;
  26371. dest.startRotationConstant = this.startRotationConstant;
  26372. this.startRotationConstantSeparate.cloneTo(dest.startRotationConstantSeparate);
  26373. dest.startRotationConstantMin = this.startRotationConstantMin;
  26374. dest.startRotationConstantMax = this.startRotationConstantMax;
  26375. this.startRotationConstantMinSeparate.cloneTo(dest.startRotationConstantMinSeparate);
  26376. this.startRotationConstantMaxSeparate.cloneTo(dest.startRotationConstantMaxSeparate);
  26377. dest.randomizeRotationDirection = this.randomizeRotationDirection;
  26378. dest.startColorType = this.startColorType;
  26379. this.startColorConstant.cloneTo(dest.startColorConstant);
  26380. this.startColorConstantMin.cloneTo(dest.startColorConstantMin);
  26381. this.startColorConstantMax.cloneTo(dest.startColorConstantMax);
  26382. dest.gravityModifier = this.gravityModifier;
  26383. dest.simulationSpace = this.simulationSpace;
  26384. dest.scaleMode = this.scaleMode;
  26385. dest.playOnAwake = this.playOnAwake;
  26386. dest.autoRandomSeed = this.autoRandomSeed;
  26387. dest.randomSeed[0] = this.randomSeed[0];
  26388. dest.maxParticles = this.maxParticles;
  26389. (this._emission) && (dest._emission = this._emission.clone());
  26390. (this.shape) && (dest.shape = this.shape.clone());
  26391. (this.velocityOverLifetime) && (dest.velocityOverLifetime = this.velocityOverLifetime.clone());
  26392. (this.colorOverLifetime) && (dest.colorOverLifetime = this.colorOverLifetime.clone());
  26393. (this.sizeOverLifetime) && (dest.sizeOverLifetime = this.sizeOverLifetime.clone());
  26394. (this.rotationOverLifetime) && (dest.rotationOverLifetime = this.rotationOverLifetime.clone());
  26395. (this.textureSheetAnimation) && (dest.textureSheetAnimation = this.textureSheetAnimation.clone());
  26396. dest.isPerformanceMode = this.isPerformanceMode;
  26397. dest._isEmitting = this._isEmitting;
  26398. dest._isPlaying = this._isPlaying;
  26399. dest._isPaused = this._isPaused;
  26400. dest._playStartDelay = this._playStartDelay;
  26401. dest._frameRateTime = this._frameRateTime;
  26402. dest._emissionTime = this._emissionTime;
  26403. dest._totalDelayTime = this._totalDelayTime;
  26404. dest._burstsIndex = this._burstsIndex;
  26405. }
  26406. clone() {
  26407. var dest = new ShurikenParticleSystem(null);
  26408. this.cloneTo(dest);
  26409. return dest;
  26410. }
  26411. }
  26412. ShurikenParticleSystem._RANDOMOFFSET = new Uint32Array([0x23571a3e, 0xc34f56fe, 0x13371337, 0x12460f3b, 0x6aed452e, 0xdec4aea1, 0x96aa4de3, 0x8d2c8431, 0xf3857f6f, 0xe0fbd834, 0x13740583, 0x591bc05c, 0x40eb95e4, 0xbc524e5f, 0xaf502044, 0xa614b381, 0x1034e524, 0xfc524e5f]);
  26413. ShurikenParticleSystem.halfKSqrtOf2 = 1.42 * 0.5;
  26414. ShurikenParticleSystem._maxElapsedTime = 1.0 / 3.0;
  26415. ShurikenParticleSystem._tempVector30 = new Vector3();
  26416. ShurikenParticleSystem._tempVector31 = new Vector3();
  26417. ShurikenParticleSystem._tempVector32 = new Vector3();
  26418. ShurikenParticleSystem._tempVector33 = new Vector3();
  26419. ShurikenParticleSystem._tempVector34 = new Vector3();
  26420. ShurikenParticleSystem._tempVector35 = new Vector3();
  26421. ShurikenParticleSystem._tempVector36 = new Vector3();
  26422. ShurikenParticleSystem._tempVector37 = new Vector3();
  26423. ShurikenParticleSystem._tempVector38 = new Vector3();
  26424. ShurikenParticleSystem._tempVector39 = new Vector3();
  26425. ShurikenParticleSystem._tempPosition = new Vector3();
  26426. ShurikenParticleSystem._tempDirection = new Vector3();
  26427. ShurikenParticleSystem._type = GeometryElement._typeCounter++;
  26428. class ShuriKenParticle3D extends RenderableSprite3D {
  26429. constructor() {
  26430. super(null);
  26431. this._render = new ShurikenParticleRenderer(this);
  26432. this._particleSystem = new ShurikenParticleSystem(this);
  26433. var elements = this._render._renderElements;
  26434. var element = elements[0] = new RenderElement();
  26435. element.setTransform(this._transform);
  26436. element.render = this._render;
  26437. element.setGeometry(this._particleSystem);
  26438. element.material = ShurikenParticleMaterial.defaultMaterial;
  26439. }
  26440. static __init__() {
  26441. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD = Shader3D.getDefineByName("SPHERHBILLBOARD");
  26442. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD = Shader3D.getDefineByName("STRETCHEDBILLBOARD");
  26443. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD = Shader3D.getDefineByName("HORIZONTALBILLBOARD");
  26444. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD = Shader3D.getDefineByName("VERTICALBILLBOARD");
  26445. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME = Shader3D.getDefineByName("COLOROVERLIFETIME");
  26446. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME = Shader3D.getDefineByName("RANDOMCOLOROVERLIFETIME");
  26447. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT = Shader3D.getDefineByName("VELOCITYOVERLIFETIMECONSTANT");
  26448. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE = Shader3D.getDefineByName("VELOCITYOVERLIFETIMECURVE");
  26449. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT = Shader3D.getDefineByName("VELOCITYOVERLIFETIMERANDOMCONSTANT");
  26450. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE = Shader3D.getDefineByName("VELOCITYOVERLIFETIMERANDOMCURVE");
  26451. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE = Shader3D.getDefineByName("TEXTURESHEETANIMATIONCURVE");
  26452. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE = Shader3D.getDefineByName("TEXTURESHEETANIMATIONRANDOMCURVE");
  26453. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME = Shader3D.getDefineByName("ROTATIONOVERLIFETIME");
  26454. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE = Shader3D.getDefineByName("ROTATIONOVERLIFETIMESEPERATE");
  26455. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT = Shader3D.getDefineByName("ROTATIONOVERLIFETIMECONSTANT");
  26456. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE = Shader3D.getDefineByName("ROTATIONOVERLIFETIMECURVE");
  26457. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS = Shader3D.getDefineByName("ROTATIONOVERLIFETIMERANDOMCONSTANTS");
  26458. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES = Shader3D.getDefineByName("ROTATIONOVERLIFETIMERANDOMCURVES");
  26459. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE = Shader3D.getDefineByName("SIZEOVERLIFETIMECURVE");
  26460. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE = Shader3D.getDefineByName("SIZEOVERLIFETIMECURVESEPERATE");
  26461. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES = Shader3D.getDefineByName("SIZEOVERLIFETIMERANDOMCURVES");
  26462. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE = Shader3D.getDefineByName("SIZEOVERLIFETIMERANDOMCURVESSEPERATE");
  26463. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH = Shader3D.getDefineByName("RENDERMODE_MESH");
  26464. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE = Shader3D.getDefineByName("SHAPE");
  26465. }
  26466. get particleSystem() {
  26467. return this._particleSystem;
  26468. }
  26469. get particleRenderer() {
  26470. return this._render;
  26471. }
  26472. _parseModule(module, moduleData) {
  26473. for (var t in moduleData) {
  26474. switch (t) {
  26475. case "bases":
  26476. var bases = moduleData.bases;
  26477. for (var k in bases)
  26478. module[k] = bases[k];
  26479. break;
  26480. case "vector2s":
  26481. var vector2s = moduleData.vector2s;
  26482. for (var k in vector2s) {
  26483. var vec2 = module[k];
  26484. var vec2Data = vector2s[k];
  26485. vec2.setValue(vec2Data[0], vec2Data[1]);
  26486. module[k] = vec2;
  26487. }
  26488. break;
  26489. case "vector3s":
  26490. var vector3s = moduleData.vector3s;
  26491. for (var k in vector3s) {
  26492. var vec3 = module[k];
  26493. var vec3Data = vector3s[k];
  26494. vec3.setValue(vec3Data[0], vec3Data[1], vec3Data[2]);
  26495. module[k] = vec3;
  26496. }
  26497. break;
  26498. case "vector4s":
  26499. var vector4s = moduleData.vector4s;
  26500. for (var k in vector4s) {
  26501. var vec4 = module[k];
  26502. var vec4Data = vector4s[k];
  26503. vec4.setValue(vec4Data[0], vec4Data[1], vec4Data[2], vec4Data[3]);
  26504. module[k] = vec4;
  26505. }
  26506. break;
  26507. case "gradientDataNumbers":
  26508. var gradientDataNumbers = moduleData.gradientDataNumbers;
  26509. for (var k in gradientDataNumbers) {
  26510. var gradientNumber = module[k];
  26511. var gradientNumberData = moduleData[k];
  26512. for (var i = 0, n = gradientNumberData.length; i < n; i++) {
  26513. var valueData = gradientNumberData[i];
  26514. gradientNumber.add(valueData.key, valueData.value);
  26515. }
  26516. module[k] = gradientNumber;
  26517. }
  26518. break;
  26519. case "resources":
  26520. var resources = moduleData.resources;
  26521. for (var k in resources)
  26522. module[k] = Laya.Loader.getRes(resources[k]);
  26523. break;
  26524. case "bursts":
  26525. var burstsData = moduleData.bursts;
  26526. for (var i = 0, n = burstsData.length; i < n; i++) {
  26527. var brust = burstsData[i];
  26528. module.addBurst(new Burst(brust.time, brust.min, brust.max));
  26529. }
  26530. break;
  26531. case "randomSeed":
  26532. module.randomSeed[0] = moduleData.randomSeed;
  26533. break;
  26534. case "shapeType":
  26535. case "type":
  26536. case "color":
  26537. case "size":
  26538. case "frame":
  26539. case "startFrame":
  26540. case "angularVelocity":
  26541. case "velocity":
  26542. break;
  26543. default:
  26544. throw "ShurikenParticle3D:unknown type.";
  26545. }
  26546. }
  26547. }
  26548. _parse(data, spriteMap) {
  26549. super._parse(data, spriteMap);
  26550. if (data.main) {
  26551. var particleSystem = this.particleSystem;
  26552. var particleRender = this.particleRenderer;
  26553. this._parseModule(particleRender, data.renderer);
  26554. this._parseModule(particleSystem, data.main);
  26555. this._parseModule(particleSystem.emission, data.emission);
  26556. var shapeData = data.shape;
  26557. if (shapeData) {
  26558. var shape;
  26559. switch (shapeData.shapeType) {
  26560. case 0:
  26561. shape = new SphereShape();
  26562. break;
  26563. case 1:
  26564. shape = new HemisphereShape();
  26565. break;
  26566. case 2:
  26567. shape = new ConeShape();
  26568. break;
  26569. case 3:
  26570. shape = new BoxShape();
  26571. break;
  26572. case 7:
  26573. shape = new CircleShape();
  26574. break;
  26575. default:
  26576. throw "ShuriKenParticle3D:unknown shape type.";
  26577. }
  26578. this._parseModule(shape, shapeData);
  26579. particleSystem.shape = shape;
  26580. }
  26581. var velocityOverLifetimeData = data.velocityOverLifetime;
  26582. if (velocityOverLifetimeData) {
  26583. var velocityData = velocityOverLifetimeData.velocity;
  26584. var velocity;
  26585. switch (velocityData.type) {
  26586. case 0:
  26587. var constantData = velocityData.constant;
  26588. velocity = GradientVelocity.createByConstant(constantData ? new Vector3(constantData[0], constantData[1], constantData[2]) : new Vector3(0, 0, 0));
  26589. break;
  26590. case 1:
  26591. velocity = GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX), this._initParticleVelocity(velocityData.gradientY), this._initParticleVelocity(velocityData.gradientZ));
  26592. break;
  26593. case 2:
  26594. var constantMinData = velocityData.constantMin;
  26595. var constantMaxData = velocityData.constantMax;
  26596. 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));
  26597. break;
  26598. case 3:
  26599. 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));
  26600. break;
  26601. }
  26602. var velocityOverLifetime = new VelocityOverLifetime(velocity);
  26603. this._parseModule(velocityOverLifetime, velocityOverLifetimeData);
  26604. particleSystem.velocityOverLifetime = velocityOverLifetime;
  26605. }
  26606. var colorOverLifetimeData = data.colorOverLifetime;
  26607. if (colorOverLifetimeData) {
  26608. var colorData = colorOverLifetimeData.color;
  26609. var color;
  26610. switch (colorData.type) {
  26611. case 0:
  26612. var constColorData = colorData.constant;
  26613. color = GradientColor.createByConstant(constColorData ? new Vector4(constColorData[0], constColorData[1], constColorData[2], constColorData[3]) : new Vector4(0, 0, 0, 0));
  26614. break;
  26615. case 1:
  26616. color = GradientColor.createByGradient(this._initParticleColor(colorData.gradient));
  26617. break;
  26618. case 2:
  26619. var minConstColorData = colorData.constantMin;
  26620. var maxConstColorData = colorData.constantMax;
  26621. 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));
  26622. break;
  26623. case 3:
  26624. color = GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin), this._initParticleColor(colorData.gradientMax));
  26625. break;
  26626. }
  26627. var colorOverLifetime = new ColorOverLifetime(color);
  26628. this._parseModule(colorOverLifetime, colorOverLifetimeData);
  26629. particleSystem.colorOverLifetime = colorOverLifetime;
  26630. }
  26631. var sizeOverLifetimeData = data.sizeOverLifetime;
  26632. if (sizeOverLifetimeData) {
  26633. var sizeData = sizeOverLifetimeData.size;
  26634. var size;
  26635. switch (sizeData.type) {
  26636. case 0:
  26637. if (sizeData.separateAxes) {
  26638. size = GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX), this._initParticleSize(sizeData.gradientY), this._initParticleSize(sizeData.gradientZ));
  26639. }
  26640. else {
  26641. size = GradientSize.createByGradient(this._initParticleSize(sizeData.gradient));
  26642. }
  26643. break;
  26644. case 1:
  26645. if (sizeData.separateAxes) {
  26646. var constantMinSeparateData = sizeData.constantMinSeparate;
  26647. var constantMaxSeparateData = sizeData.constantMaxSeparate;
  26648. 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));
  26649. }
  26650. else {
  26651. size = GradientSize.createByRandomTwoConstant(sizeData.constantMin || 0, sizeData.constantMax || 0);
  26652. }
  26653. break;
  26654. case 2:
  26655. if (sizeData.separateAxes) {
  26656. 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));
  26657. }
  26658. else {
  26659. size = GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin), this._initParticleSize(sizeData.gradientMax));
  26660. }
  26661. break;
  26662. }
  26663. var sizeOverLifetime = new SizeOverLifetime(size);
  26664. this._parseModule(sizeOverLifetime, sizeOverLifetimeData);
  26665. particleSystem.sizeOverLifetime = sizeOverLifetime;
  26666. }
  26667. var rotationOverLifetimeData = data.rotationOverLifetime;
  26668. if (rotationOverLifetimeData) {
  26669. var angularVelocityData = rotationOverLifetimeData.angularVelocity;
  26670. var angularVelocity;
  26671. switch (angularVelocityData.type) {
  26672. case 0:
  26673. if (angularVelocityData.separateAxes) {
  26674. var conSep = angularVelocityData.constantSeparate;
  26675. angularVelocity = GradientAngularVelocity.createByConstantSeparate(conSep ? new Vector3(conSep[0], conSep[1], conSep[2]) : new Vector3(0, 0, Math.PI / 4));
  26676. }
  26677. else {
  26678. angularVelocity = GradientAngularVelocity.createByConstant(angularVelocityData.constant || Math.PI / 4);
  26679. }
  26680. break;
  26681. case 1:
  26682. if (angularVelocityData.separateAxes) {
  26683. angularVelocity = GradientAngularVelocity.createByGradientSeparate(this._initParticleRotation(angularVelocityData.gradientX), this._initParticleRotation(angularVelocityData.gradientY), this._initParticleRotation(angularVelocityData.gradientZ));
  26684. }
  26685. else {
  26686. angularVelocity = GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient));
  26687. }
  26688. break;
  26689. case 2:
  26690. if (angularVelocityData.separateAxes) {
  26691. var minSep = angularVelocityData.constantMinSeparate;
  26692. var maxSep = angularVelocityData.constantMaxSeparate;
  26693. 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));
  26694. }
  26695. else {
  26696. angularVelocity = GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin || 0, angularVelocityData.constantMax || Math.PI / 4);
  26697. }
  26698. break;
  26699. case 3:
  26700. if (angularVelocityData.separateAxes) ;
  26701. else {
  26702. angularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin), this._initParticleRotation(angularVelocityData.gradientMax));
  26703. }
  26704. break;
  26705. }
  26706. var rotationOverLifetime = new RotationOverLifetime(angularVelocity);
  26707. this._parseModule(rotationOverLifetime, rotationOverLifetimeData);
  26708. particleSystem.rotationOverLifetime = rotationOverLifetime;
  26709. }
  26710. var textureSheetAnimationData = data.textureSheetAnimation;
  26711. if (textureSheetAnimationData) {
  26712. var frameData = textureSheetAnimationData.frame;
  26713. var frameOverTime;
  26714. switch (frameData.type) {
  26715. case 0:
  26716. frameOverTime = FrameOverTime.createByConstant(frameData.constant);
  26717. break;
  26718. case 1:
  26719. frameOverTime = FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime));
  26720. break;
  26721. case 2:
  26722. frameOverTime = FrameOverTime.createByRandomTwoConstant(frameData.constantMin, frameData.constantMax);
  26723. break;
  26724. case 3:
  26725. frameOverTime = FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin), this._initParticleFrame(frameData.overTimeMax));
  26726. break;
  26727. }
  26728. var startFrameData = textureSheetAnimationData.startFrame;
  26729. var startFrame;
  26730. switch (startFrameData.type) {
  26731. case 0:
  26732. startFrame = StartFrame.createByConstant(startFrameData.constant);
  26733. break;
  26734. case 1:
  26735. startFrame = StartFrame.createByRandomTwoConstant(startFrameData.constantMin, startFrameData.constantMax);
  26736. break;
  26737. }
  26738. var textureSheetAnimation = new TextureSheetAnimation(frameOverTime, startFrame);
  26739. this._parseModule(textureSheetAnimation, textureSheetAnimationData);
  26740. particleSystem.textureSheetAnimation = textureSheetAnimation;
  26741. }
  26742. }
  26743. else {
  26744. this._parseOld(data);
  26745. }
  26746. }
  26747. _activeHierarchy(activeChangeComponents) {
  26748. super._activeHierarchy(activeChangeComponents);
  26749. (this.particleSystem.playOnAwake) && (this.particleSystem.play());
  26750. }
  26751. _inActiveHierarchy(activeChangeComponents) {
  26752. super._inActiveHierarchy(activeChangeComponents);
  26753. (this.particleSystem.isAlive) && (this.particleSystem.simulate(0, true));
  26754. }
  26755. _cloneTo(destObject, srcSprite, dstSprite) {
  26756. var destShuriKenParticle3D = destObject;
  26757. var destParticleSystem = destShuriKenParticle3D._particleSystem;
  26758. this._particleSystem.cloneTo(destParticleSystem);
  26759. var destParticleRender = destShuriKenParticle3D._render;
  26760. var particleRender = this._render;
  26761. destParticleRender.sharedMaterials = particleRender.sharedMaterials;
  26762. destParticleRender.enable = particleRender.enable;
  26763. destParticleRender.renderMode = particleRender.renderMode;
  26764. destParticleRender.mesh = particleRender.mesh;
  26765. destParticleRender.stretchedBillboardCameraSpeedScale = particleRender.stretchedBillboardCameraSpeedScale;
  26766. destParticleRender.stretchedBillboardSpeedScale = particleRender.stretchedBillboardSpeedScale;
  26767. destParticleRender.stretchedBillboardLengthScale = particleRender.stretchedBillboardLengthScale;
  26768. destParticleRender.sortingFudge = particleRender.sortingFudge;
  26769. super._cloneTo(destObject, srcSprite, dstSprite);
  26770. }
  26771. destroy(destroyChild = true) {
  26772. if (this.destroyed)
  26773. return;
  26774. super.destroy(destroyChild);
  26775. this._particleSystem.destroy();
  26776. this._particleSystem = null;
  26777. }
  26778. _create() {
  26779. return new ShuriKenParticle3D();
  26780. }
  26781. _parseOld(data) {
  26782. const anglelToRad = Math.PI / 180.0;
  26783. var i, n;
  26784. var particleRender = this.particleRenderer;
  26785. var material;
  26786. var materialData = data.material;
  26787. (materialData) && (material = Laya.Loader.getRes(materialData.path));
  26788. particleRender.sharedMaterial = material;
  26789. var meshPath = data.meshPath;
  26790. (meshPath) && (particleRender.mesh = Laya.Loader.getRes(meshPath));
  26791. particleRender.renderMode = data.renderMode;
  26792. particleRender.stretchedBillboardCameraSpeedScale = data.stretchedBillboardCameraSpeedScale;
  26793. particleRender.stretchedBillboardSpeedScale = data.stretchedBillboardSpeedScale;
  26794. particleRender.stretchedBillboardLengthScale = data.stretchedBillboardLengthScale;
  26795. particleRender.sortingFudge = data.sortingFudge ? data.sortingFudge : 0.0;
  26796. var particleSystem = this.particleSystem;
  26797. particleSystem.isPerformanceMode = data.isPerformanceMode;
  26798. particleSystem.duration = data.duration;
  26799. particleSystem.looping = data.looping;
  26800. particleSystem.prewarm = data.prewarm;
  26801. particleSystem.startDelayType = data.startDelayType;
  26802. particleSystem.startDelay = data.startDelay;
  26803. particleSystem.startDelayMin = data.startDelayMin;
  26804. particleSystem.startDelayMax = data.startDelayMax;
  26805. particleSystem.startLifetimeType = data.startLifetimeType;
  26806. particleSystem.startLifetimeConstant = data.startLifetimeConstant;
  26807. particleSystem.startLifeTimeGradient = ShuriKenParticle3D._initStartLife(data.startLifetimeGradient);
  26808. particleSystem.startLifetimeConstantMin = data.startLifetimeConstantMin;
  26809. particleSystem.startLifetimeConstantMax = data.startLifetimeConstantMax;
  26810. particleSystem.startLifeTimeGradientMin = ShuriKenParticle3D._initStartLife(data.startLifetimeGradientMin);
  26811. particleSystem.startLifeTimeGradientMax = ShuriKenParticle3D._initStartLife(data.startLifetimeGradientMax);
  26812. particleSystem.startSpeedType = data.startSpeedType;
  26813. particleSystem.startSpeedConstant = data.startSpeedConstant;
  26814. particleSystem.startSpeedConstantMin = data.startSpeedConstantMin;
  26815. particleSystem.startSpeedConstantMax = data.startSpeedConstantMax;
  26816. particleSystem.threeDStartSize = data.threeDStartSize;
  26817. particleSystem.startSizeType = data.startSizeType;
  26818. particleSystem.startSizeConstant = data.startSizeConstant;
  26819. var startSizeConstantSeparateArray = data.startSizeConstantSeparate;
  26820. var startSizeConstantSeparateElement = particleSystem.startSizeConstantSeparate;
  26821. startSizeConstantSeparateElement.x = startSizeConstantSeparateArray[0];
  26822. startSizeConstantSeparateElement.y = startSizeConstantSeparateArray[1];
  26823. startSizeConstantSeparateElement.z = startSizeConstantSeparateArray[2];
  26824. particleSystem.startSizeConstantMin = data.startSizeConstantMin;
  26825. particleSystem.startSizeConstantMax = data.startSizeConstantMax;
  26826. var startSizeConstantMinSeparateArray = data.startSizeConstantMinSeparate;
  26827. var startSizeConstantMinSeparateElement = particleSystem.startSizeConstantMinSeparate;
  26828. startSizeConstantMinSeparateElement.x = startSizeConstantMinSeparateArray[0];
  26829. startSizeConstantMinSeparateElement.y = startSizeConstantMinSeparateArray[1];
  26830. startSizeConstantMinSeparateElement.z = startSizeConstantMinSeparateArray[2];
  26831. var startSizeConstantMaxSeparateArray = data.startSizeConstantMaxSeparate;
  26832. var startSizeConstantMaxSeparateElement = particleSystem.startSizeConstantMaxSeparate;
  26833. startSizeConstantMaxSeparateElement.x = startSizeConstantMaxSeparateArray[0];
  26834. startSizeConstantMaxSeparateElement.y = startSizeConstantMaxSeparateArray[1];
  26835. startSizeConstantMaxSeparateElement.z = startSizeConstantMaxSeparateArray[2];
  26836. particleSystem.threeDStartRotation = data.threeDStartRotation;
  26837. particleSystem.startRotationType = data.startRotationType;
  26838. particleSystem.startRotationConstant = data.startRotationConstant * anglelToRad;
  26839. var startRotationConstantSeparateArray = data.startRotationConstantSeparate;
  26840. var startRotationConstantSeparateElement = particleSystem.startRotationConstantSeparate;
  26841. startRotationConstantSeparateElement.x = startRotationConstantSeparateArray[0] * anglelToRad;
  26842. startRotationConstantSeparateElement.y = startRotationConstantSeparateArray[1] * anglelToRad;
  26843. startRotationConstantSeparateElement.z = startRotationConstantSeparateArray[2] * anglelToRad;
  26844. particleSystem.startRotationConstantMin = data.startRotationConstantMin * anglelToRad;
  26845. particleSystem.startRotationConstantMax = data.startRotationConstantMax * anglelToRad;
  26846. var startRotationConstantMinSeparateArray = data.startRotationConstantMinSeparate;
  26847. var startRotationConstantMinSeparateElement = particleSystem.startRotationConstantMinSeparate;
  26848. startRotationConstantMinSeparateElement.x = startRotationConstantMinSeparateArray[0] * anglelToRad;
  26849. startRotationConstantMinSeparateElement.y = startRotationConstantMinSeparateArray[1] * anglelToRad;
  26850. startRotationConstantMinSeparateElement.z = startRotationConstantMinSeparateArray[2] * anglelToRad;
  26851. var startRotationConstantMaxSeparateArray = data.startRotationConstantMaxSeparate;
  26852. var startRotationConstantMaxSeparateElement = particleSystem.startRotationConstantMaxSeparate;
  26853. startRotationConstantMaxSeparateElement.x = startRotationConstantMaxSeparateArray[0] * anglelToRad;
  26854. startRotationConstantMaxSeparateElement.y = startRotationConstantMaxSeparateArray[1] * anglelToRad;
  26855. startRotationConstantMaxSeparateElement.z = startRotationConstantMaxSeparateArray[2] * anglelToRad;
  26856. particleSystem.randomizeRotationDirection = data.randomizeRotationDirection;
  26857. particleSystem.startColorType = data.startColorType;
  26858. var startColorConstantArray = data.startColorConstant;
  26859. var startColorConstantElement = particleSystem.startColorConstant;
  26860. startColorConstantElement.x = startColorConstantArray[0];
  26861. startColorConstantElement.y = startColorConstantArray[1];
  26862. startColorConstantElement.z = startColorConstantArray[2];
  26863. startColorConstantElement.w = startColorConstantArray[3];
  26864. var startColorConstantMinArray = data.startColorConstantMin;
  26865. var startColorConstantMinElement = particleSystem.startColorConstantMin;
  26866. startColorConstantMinElement.x = startColorConstantMinArray[0];
  26867. startColorConstantMinElement.y = startColorConstantMinArray[1];
  26868. startColorConstantMinElement.z = startColorConstantMinArray[2];
  26869. startColorConstantMinElement.w = startColorConstantMinArray[3];
  26870. var startColorConstantMaxArray = data.startColorConstantMax;
  26871. var startColorConstantMaxElement = particleSystem.startColorConstantMax;
  26872. startColorConstantMaxElement.x = startColorConstantMaxArray[0];
  26873. startColorConstantMaxElement.y = startColorConstantMaxArray[1];
  26874. startColorConstantMaxElement.z = startColorConstantMaxArray[2];
  26875. startColorConstantMaxElement.w = startColorConstantMaxArray[3];
  26876. particleSystem.gravityModifier = data.gravityModifier;
  26877. particleSystem.simulationSpace = data.simulationSpace;
  26878. (data.simulationSpeed !== undefined) && (particleSystem.simulationSpeed = data.simulationSpeed);
  26879. particleSystem.scaleMode = data.scaleMode;
  26880. particleSystem.playOnAwake = data.playOnAwake;
  26881. particleSystem.maxParticles = data.maxParticles;
  26882. var autoRandomSeed = data.autoRandomSeed;
  26883. (autoRandomSeed != null) && (particleSystem.autoRandomSeed = autoRandomSeed);
  26884. var randomSeed = data.randomSeed;
  26885. (randomSeed != null) && (particleSystem.randomSeed[0] = randomSeed);
  26886. var emissionData = data.emission;
  26887. var emission = particleSystem.emission;
  26888. if (emissionData) {
  26889. emission.emissionRate = emissionData.emissionRate;
  26890. var burstsData = emissionData.bursts;
  26891. if (burstsData)
  26892. for (i = 0, n = burstsData.length; i < n; i++) {
  26893. var brust = burstsData[i];
  26894. emission.addBurst(new Burst(brust.time, brust.min, brust.max));
  26895. }
  26896. emission.enable = emissionData.enable;
  26897. }
  26898. else {
  26899. emission.enable = false;
  26900. }
  26901. var shapeData = data.shape;
  26902. if (shapeData) {
  26903. var shape;
  26904. switch (shapeData.shapeType) {
  26905. case 0:
  26906. var sphereShape;
  26907. shape = sphereShape = new SphereShape();
  26908. sphereShape.radius = shapeData.sphereRadius;
  26909. sphereShape.emitFromShell = shapeData.sphereEmitFromShell;
  26910. sphereShape.randomDirection = shapeData.sphereRandomDirection;
  26911. break;
  26912. case 1:
  26913. var hemiSphereShape;
  26914. shape = hemiSphereShape = new HemisphereShape();
  26915. hemiSphereShape.radius = shapeData.hemiSphereRadius;
  26916. hemiSphereShape.emitFromShell = shapeData.hemiSphereEmitFromShell;
  26917. hemiSphereShape.randomDirection = shapeData.hemiSphereRandomDirection;
  26918. break;
  26919. case 2:
  26920. var coneShape;
  26921. shape = coneShape = new ConeShape();
  26922. coneShape.angle = shapeData.coneAngle * anglelToRad;
  26923. coneShape.radius = shapeData.coneRadius;
  26924. coneShape.length = shapeData.coneLength;
  26925. coneShape.emitType = shapeData.coneEmitType;
  26926. coneShape.randomDirection = shapeData.coneRandomDirection;
  26927. break;
  26928. case 3:
  26929. var boxShape;
  26930. shape = boxShape = new BoxShape();
  26931. boxShape.x = shapeData.boxX;
  26932. boxShape.y = shapeData.boxY;
  26933. boxShape.z = shapeData.boxZ;
  26934. boxShape.randomDirection = shapeData.boxRandomDirection;
  26935. break;
  26936. case 7:
  26937. var circleShape;
  26938. shape = circleShape = new CircleShape();
  26939. circleShape.radius = shapeData.circleRadius;
  26940. circleShape.arc = shapeData.circleArc * anglelToRad;
  26941. circleShape.emitFromEdge = shapeData.circleEmitFromEdge;
  26942. circleShape.randomDirection = shapeData.circleRandomDirection;
  26943. break;
  26944. default:
  26945. var tempShape;
  26946. shape = tempShape = new CircleShape();
  26947. tempShape.radius = shapeData.circleRadius;
  26948. tempShape.arc = shapeData.circleArc * anglelToRad;
  26949. tempShape.emitFromEdge = shapeData.circleEmitFromEdge;
  26950. tempShape.randomDirection = shapeData.circleRandomDirection;
  26951. break;
  26952. }
  26953. shape.enable = shapeData.enable;
  26954. particleSystem.shape = shape;
  26955. }
  26956. var velocityOverLifetimeData = data.velocityOverLifetime;
  26957. if (velocityOverLifetimeData) {
  26958. var velocityData = velocityOverLifetimeData.velocity;
  26959. var velocity;
  26960. switch (velocityData.type) {
  26961. case 0:
  26962. var constantData = velocityData.constant;
  26963. velocity = GradientVelocity.createByConstant(new Vector3(constantData[0], constantData[1], constantData[2]));
  26964. break;
  26965. case 1:
  26966. velocity = GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX), this._initParticleVelocity(velocityData.gradientY), this._initParticleVelocity(velocityData.gradientZ));
  26967. break;
  26968. case 2:
  26969. var constantMinData = velocityData.constantMin;
  26970. var constantMaxData = velocityData.constantMax;
  26971. velocity = GradientVelocity.createByRandomTwoConstant(new Vector3(constantMinData[0], constantMinData[1], constantMinData[2]), new Vector3(constantMaxData[0], constantMaxData[1], constantMaxData[2]));
  26972. break;
  26973. case 3:
  26974. 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));
  26975. break;
  26976. }
  26977. var velocityOverLifetime = new VelocityOverLifetime(velocity);
  26978. velocityOverLifetime.space = velocityOverLifetimeData.space;
  26979. velocityOverLifetime.enable = velocityOverLifetimeData.enable;
  26980. particleSystem.velocityOverLifetime = velocityOverLifetime;
  26981. }
  26982. var colorOverLifetimeData = data.colorOverLifetime;
  26983. if (colorOverLifetimeData) {
  26984. var colorData = colorOverLifetimeData.color;
  26985. var color;
  26986. switch (colorData.type) {
  26987. case 0:
  26988. var constColorData = colorData.constant;
  26989. color = GradientColor.createByConstant(new Vector4(constColorData[0], constColorData[1], constColorData[2], constColorData[3]));
  26990. break;
  26991. case 1:
  26992. color = GradientColor.createByGradient(this._initParticleColor(colorData.gradient));
  26993. break;
  26994. case 2:
  26995. var minConstColorData = colorData.constantMin;
  26996. var maxConstColorData = colorData.constantMax;
  26997. color = GradientColor.createByRandomTwoConstant(new Vector4(minConstColorData[0], minConstColorData[1], minConstColorData[2], minConstColorData[3]), new Vector4(maxConstColorData[0], maxConstColorData[1], maxConstColorData[2], maxConstColorData[3]));
  26998. break;
  26999. case 3:
  27000. color = GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin), this._initParticleColor(colorData.gradientMax));
  27001. break;
  27002. }
  27003. var colorOverLifetime = new ColorOverLifetime(color);
  27004. colorOverLifetime.enable = colorOverLifetimeData.enable;
  27005. particleSystem.colorOverLifetime = colorOverLifetime;
  27006. }
  27007. var sizeOverLifetimeData = data.sizeOverLifetime;
  27008. if (sizeOverLifetimeData) {
  27009. var sizeData = sizeOverLifetimeData.size;
  27010. var size;
  27011. switch (sizeData.type) {
  27012. case 0:
  27013. if (sizeData.separateAxes) {
  27014. size = GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX), this._initParticleSize(sizeData.gradientY), this._initParticleSize(sizeData.gradientZ));
  27015. }
  27016. else {
  27017. size = GradientSize.createByGradient(this._initParticleSize(sizeData.gradient));
  27018. }
  27019. break;
  27020. case 1:
  27021. if (sizeData.separateAxes) {
  27022. var constantMinSeparateData = sizeData.constantMinSeparate;
  27023. var constantMaxSeparateData = sizeData.constantMaxSeparate;
  27024. size = GradientSize.createByRandomTwoConstantSeparate(new Vector3(constantMinSeparateData[0], constantMinSeparateData[1], constantMinSeparateData[2]), new Vector3(constantMaxSeparateData[0], constantMaxSeparateData[1], constantMaxSeparateData[2]));
  27025. }
  27026. else {
  27027. size = GradientSize.createByRandomTwoConstant(sizeData.constantMin, sizeData.constantMax);
  27028. }
  27029. break;
  27030. case 2:
  27031. if (sizeData.separateAxes) {
  27032. 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));
  27033. }
  27034. else {
  27035. size = GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin), this._initParticleSize(sizeData.gradientMax));
  27036. }
  27037. break;
  27038. }
  27039. var sizeOverLifetime = new SizeOverLifetime(size);
  27040. sizeOverLifetime.enable = sizeOverLifetimeData.enable;
  27041. particleSystem.sizeOverLifetime = sizeOverLifetime;
  27042. }
  27043. var rotationOverLifetimeData = data.rotationOverLifetime;
  27044. if (rotationOverLifetimeData) {
  27045. var angularVelocityData = rotationOverLifetimeData.angularVelocity;
  27046. var angularVelocity;
  27047. switch (angularVelocityData.type) {
  27048. case 0:
  27049. if (angularVelocityData.separateAxes) {
  27050. var conSep = angularVelocityData.constantSeparate;
  27051. angularVelocity = GradientAngularVelocity.createByConstantSeparate(new Vector3(conSep[0] * anglelToRad, conSep[1] * anglelToRad, conSep[2] * anglelToRad));
  27052. }
  27053. else {
  27054. angularVelocity = GradientAngularVelocity.createByConstant(angularVelocityData.constant * anglelToRad);
  27055. }
  27056. break;
  27057. case 1:
  27058. if (angularVelocityData.separateAxes) {
  27059. angularVelocity = GradientAngularVelocity.createByGradientSeparate(this._initParticleRotation(angularVelocityData.gradientX), this._initParticleRotation(angularVelocityData.gradientY), this._initParticleRotation(angularVelocityData.gradientZ));
  27060. }
  27061. else {
  27062. angularVelocity = GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient));
  27063. }
  27064. break;
  27065. case 2:
  27066. if (angularVelocityData.separateAxes) {
  27067. var minSep = angularVelocityData.constantMinSeparate;
  27068. var maxSep = angularVelocityData.constantMaxSeparate;
  27069. 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));
  27070. }
  27071. else {
  27072. angularVelocity = GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin * anglelToRad, angularVelocityData.constantMax * anglelToRad);
  27073. }
  27074. break;
  27075. case 3:
  27076. if (angularVelocityData.separateAxes) ;
  27077. else {
  27078. angularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin), this._initParticleRotation(angularVelocityData.gradientMax));
  27079. }
  27080. break;
  27081. }
  27082. var rotationOverLifetime = new RotationOverLifetime(angularVelocity);
  27083. rotationOverLifetime.enable = rotationOverLifetimeData.enable;
  27084. particleSystem.rotationOverLifetime = rotationOverLifetime;
  27085. }
  27086. var textureSheetAnimationData = data.textureSheetAnimation;
  27087. if (textureSheetAnimationData) {
  27088. var frameData = textureSheetAnimationData.frame;
  27089. var frameOverTime;
  27090. switch (frameData.type) {
  27091. case 0:
  27092. frameOverTime = FrameOverTime.createByConstant(frameData.constant);
  27093. break;
  27094. case 1:
  27095. frameOverTime = FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime));
  27096. break;
  27097. case 2:
  27098. frameOverTime = FrameOverTime.createByRandomTwoConstant(frameData.constantMin, frameData.constantMax);
  27099. break;
  27100. case 3:
  27101. frameOverTime = FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin), this._initParticleFrame(frameData.overTimeMax));
  27102. break;
  27103. }
  27104. var startFrameData = textureSheetAnimationData.startFrame;
  27105. var startFrame;
  27106. switch (startFrameData.type) {
  27107. case 0:
  27108. startFrame = StartFrame.createByConstant(startFrameData.constant);
  27109. break;
  27110. case 1:
  27111. startFrame = StartFrame.createByRandomTwoConstant(startFrameData.constantMin, startFrameData.constantMax);
  27112. break;
  27113. }
  27114. var textureSheetAnimation = new TextureSheetAnimation(frameOverTime, startFrame);
  27115. textureSheetAnimation.enable = textureSheetAnimationData.enable;
  27116. var tilesData = textureSheetAnimationData.tiles;
  27117. textureSheetAnimation.tiles = new Vector2(tilesData[0], tilesData[1]);
  27118. textureSheetAnimation.type = textureSheetAnimationData.type;
  27119. textureSheetAnimation.randomRow = textureSheetAnimationData.randomRow;
  27120. var rowIndex = textureSheetAnimationData.rowIndex;
  27121. (rowIndex !== undefined) && (textureSheetAnimation.rowIndex = rowIndex);
  27122. textureSheetAnimation.cycles = textureSheetAnimationData.cycles;
  27123. particleSystem.textureSheetAnimation = textureSheetAnimation;
  27124. }
  27125. }
  27126. _initParticleColor(gradientColorData) {
  27127. var gradientColor = new Gradient(4, 4);
  27128. if (!gradientColorData) {
  27129. gradientColor.addColorAlpha(0, 1);
  27130. gradientColor.addColorAlpha(1, 1);
  27131. gradientColor.addColorRGB(0, new Color(1.0, 1.0, 1.0, 1.0));
  27132. gradientColor.addColorRGB(1, new Color(1.0, 1.0, 1.0, 1.0));
  27133. }
  27134. else {
  27135. var alphasData = gradientColorData.alphas;
  27136. var i, n;
  27137. if (!alphasData) {
  27138. gradientColor.addColorAlpha(0, 1);
  27139. gradientColor.addColorAlpha(1, 1);
  27140. }
  27141. else {
  27142. for (i = 0, n = alphasData.length; i < n; i++) {
  27143. if (i == 3 && n > 4) {
  27144. i = n - 1;
  27145. console.warn("GradientDataColor warning:alpha data length is large than 4, will ignore the middle data.");
  27146. }
  27147. var alphaData = alphasData[i];
  27148. gradientColor.addColorAlpha(alphaData.key, alphaData.value);
  27149. }
  27150. }
  27151. var rgbsData = gradientColorData.rgbs;
  27152. if (!rgbsData) {
  27153. gradientColor.addColorRGB(0, new Color(1.0, 1.0, 1.0, 1.0));
  27154. gradientColor.addColorRGB(1, new Color(1.0, 1.0, 1.0, 1.0));
  27155. }
  27156. else {
  27157. for (i = 0, n = rgbsData.length; i < n; i++) {
  27158. if (i == 3 && n > 4) {
  27159. i = n - 1;
  27160. console.warn("GradientDataColor warning:rgb data length is large than 4, will ignore the middle data.");
  27161. }
  27162. var rgbData = rgbsData[i];
  27163. var rgbValue = rgbData.value;
  27164. gradientColor.addColorRGB(rgbData.key, new Color(rgbValue[0], rgbValue[1], rgbValue[2], 1.0));
  27165. }
  27166. }
  27167. }
  27168. return gradientColor;
  27169. }
  27170. _initParticleFrame(overTimeFramesData) {
  27171. var overTimeFrame = new GradientDataInt();
  27172. if (overTimeFramesData) {
  27173. var framesData = overTimeFramesData.frames;
  27174. for (var i = 0, n = framesData.length; i < n; i++) {
  27175. var frameData = framesData[i];
  27176. overTimeFrame.add(frameData.key, frameData.value);
  27177. }
  27178. }
  27179. else {
  27180. overTimeFrame.add(0, 0);
  27181. overTimeFrame.add(1, 1);
  27182. }
  27183. return overTimeFrame;
  27184. }
  27185. static _initStartLife(gradientData) {
  27186. var gradient = new GradientDataNumber();
  27187. var startLifetimesData = gradientData.startLifetimes;
  27188. for (var i = 0, n = startLifetimesData.length; i < n; i++) {
  27189. var valueData = startLifetimesData[i];
  27190. gradient.add(valueData.key, valueData.value);
  27191. }
  27192. return gradient;
  27193. }
  27194. _initParticleVelocity(gradientData) {
  27195. var gradient = new GradientDataNumber();
  27196. var velocitysData = gradientData.velocitys;
  27197. for (var i = 0, n = velocitysData.length; i < n; i++) {
  27198. var valueData = velocitysData[i];
  27199. gradient.add(valueData.key, valueData.value);
  27200. }
  27201. return gradient;
  27202. }
  27203. _initParticleSize(gradientSizeData) {
  27204. var gradientSize = new GradientDataNumber();
  27205. if (gradientSizeData) {
  27206. var sizesData = gradientSizeData.sizes;
  27207. for (var i = 0, n = sizesData.length; i < n; i++) {
  27208. var valueData = sizesData[i];
  27209. gradientSize.add(valueData.key, valueData.value);
  27210. }
  27211. }
  27212. else {
  27213. gradientSize.add(0, 0);
  27214. gradientSize.add(1, 1);
  27215. }
  27216. return gradientSize;
  27217. }
  27218. _initParticleRotation(gradientData) {
  27219. var gradient = new GradientDataNumber();
  27220. var angularVelocitysData = gradientData.angularVelocitys;
  27221. for (var i = 0, n = angularVelocitysData.length; i < n; i++) {
  27222. var valueData = angularVelocitysData[i];
  27223. gradient.add(valueData.key, valueData.value / 180.0 * Math.PI);
  27224. }
  27225. return gradient;
  27226. }
  27227. }
  27228. class SkinnedMeshSprite3DShaderDeclaration {
  27229. }
  27230. class SkinnedMeshRenderer extends MeshRenderer {
  27231. constructor(owner) {
  27232. super(owner);
  27233. this._bones = [];
  27234. this._skinnedDataLoopMarks = [];
  27235. this._localBounds = new Bounds(Vector3._ZERO, Vector3._ZERO);
  27236. this._cacheAnimationNode = [];
  27237. }
  27238. get localBounds() {
  27239. return this._localBounds;
  27240. }
  27241. set localBounds(value) {
  27242. this._localBounds = value;
  27243. }
  27244. get rootBone() {
  27245. return this._cacheRootBone;
  27246. }
  27247. set rootBone(value) {
  27248. if (this._cacheRootBone != value) {
  27249. if (this._cacheRootBone)
  27250. this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27251. else
  27252. this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27253. if (value)
  27254. value.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27255. else
  27256. this._owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27257. this._cacheRootBone = value;
  27258. this._onWorldMatNeedChange(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE);
  27259. }
  27260. }
  27261. get bones() {
  27262. return this._bones;
  27263. }
  27264. _computeSkinnedData() {
  27265. if (this._cacheMesh && this._cacheAvatar || this._cacheMesh && !this._cacheAvatar) {
  27266. var bindPoses = this._cacheMesh._inverseBindPoses;
  27267. var pathMarks = this._cacheMesh._skinnedMatrixCaches;
  27268. for (var i = 0, n = this._cacheMesh.subMeshCount; i < n; i++) {
  27269. var subMeshBoneIndices = this._cacheMesh.getSubMesh(i)._boneIndicesList;
  27270. var subData = this._skinnedData[i];
  27271. for (var j = 0, m = subMeshBoneIndices.length; j < m; j++) {
  27272. var boneIndices = subMeshBoneIndices[j];
  27273. this._computeSubSkinnedData(bindPoses, boneIndices, subData[j], pathMarks);
  27274. }
  27275. }
  27276. }
  27277. }
  27278. _computeSubSkinnedData(bindPoses, boneIndices, data, matrixCaches) {
  27279. for (var k = 0, q = boneIndices.length; k < q; k++) {
  27280. var index = boneIndices[k];
  27281. if (this._skinnedDataLoopMarks[index] === Laya.Stat.loopCount) {
  27282. var c = matrixCaches[index];
  27283. var preData = this._skinnedData[c.subMeshIndex][c.batchIndex];
  27284. var srcIndex = c.batchBoneIndex * 16;
  27285. var dstIndex = k * 16;
  27286. for (var d = 0; d < 16; d++)
  27287. data[dstIndex + d] = preData[srcIndex + d];
  27288. }
  27289. else {
  27290. if (!this._cacheAvatar) {
  27291. Utils3D._mulMatrixArray(this._bones[index].transform.worldMatrix.elements, bindPoses[index].elements, 0, data, k * 16);
  27292. }
  27293. else {
  27294. Utils3D._mulMatrixArray(this._cacheAnimationNode[index].transform.getWorldMatrix(), bindPoses[index].elements, 0, data, k * 16);
  27295. }
  27296. this._skinnedDataLoopMarks[index] = Laya.Stat.loopCount;
  27297. }
  27298. }
  27299. }
  27300. _onWorldMatNeedChange(flag) {
  27301. this._boundsChange = true;
  27302. if (this._octreeNode) {
  27303. if (this._cacheAvatar) {
  27304. if (this._indexInOctreeMotionList === -1)
  27305. this._octreeNode._octree.addMotionObject(this);
  27306. }
  27307. else {
  27308. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  27309. if (flag) {
  27310. if (this._indexInOctreeMotionList === -1)
  27311. this._octreeNode._octree.addMotionObject(this);
  27312. }
  27313. }
  27314. }
  27315. }
  27316. _createRenderElement() {
  27317. return new RenderElement();
  27318. }
  27319. _onMeshChange(value) {
  27320. super._onMeshChange(value);
  27321. this._cacheMesh = value;
  27322. var subMeshCount = value.subMeshCount;
  27323. this._skinnedData = [];
  27324. this._skinnedDataLoopMarks.length = value._inverseBindPoses.length;
  27325. for (var i = 0; i < subMeshCount; i++) {
  27326. var subBoneIndices = value.getSubMesh(i)._boneIndicesList;
  27327. var subCount = subBoneIndices.length;
  27328. var subData = this._skinnedData[i] = [];
  27329. for (var j = 0; j < subCount; j++)
  27330. subData[j] = new Float32Array(subBoneIndices[j].length * 16);
  27331. }
  27332. (this._cacheAvatar && value) && (this._getCacheAnimationNodes());
  27333. }
  27334. _setCacheAnimator(animator) {
  27335. this._cacheAnimator = animator;
  27336. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  27337. this._setRootNode();
  27338. }
  27339. _calculateBoundingBox() {
  27340. if (!this._cacheAvatar) {
  27341. if (this._cacheRootBone)
  27342. this._localBounds._tranform(this._cacheRootBone.transform.worldMatrix, this._bounds);
  27343. else
  27344. this._localBounds._tranform(this._owner.transform.worldMatrix, this._bounds);
  27345. }
  27346. else {
  27347. if (this._cacheAnimator && this._rootBone) {
  27348. var worldMat = SkinnedMeshRenderer._tempMatrix4x4;
  27349. Utils3D.matrix4x4MultiplyMFM(this._cacheAnimator.owner.transform.worldMatrix, this._cacheRootAnimationNode.transform.getWorldMatrix(), worldMat);
  27350. this._localBounds._tranform(worldMat, this._bounds);
  27351. }
  27352. else {
  27353. super._calculateBoundingBox();
  27354. }
  27355. }
  27356. if (Laya.Render.supportWebGLPlusCulling) {
  27357. var min = this._bounds.getMin();
  27358. var max = this._bounds.getMax();
  27359. var buffer = FrustumCulling._cullingBuffer;
  27360. buffer[this._cullingBufferIndex + 1] = min.x;
  27361. buffer[this._cullingBufferIndex + 2] = min.y;
  27362. buffer[this._cullingBufferIndex + 3] = min.z;
  27363. buffer[this._cullingBufferIndex + 4] = max.x;
  27364. buffer[this._cullingBufferIndex + 5] = max.y;
  27365. buffer[this._cullingBufferIndex + 6] = max.z;
  27366. }
  27367. }
  27368. _renderUpdate(context, transform) {
  27369. if (this._cacheAnimator) {
  27370. this._computeSkinnedData();
  27371. if (!this._cacheAvatar) {
  27372. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  27373. }
  27374. else {
  27375. var aniOwnerTrans = this._cacheAnimator.owner._transform;
  27376. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, aniOwnerTrans.worldMatrix);
  27377. }
  27378. }
  27379. else {
  27380. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  27381. }
  27382. }
  27383. _renderUpdateWithCamera(context, transform) {
  27384. var projectionView = context.projectionViewMatrix;
  27385. if (this._cacheAnimator) {
  27386. if (!this._cacheAvatar) {
  27387. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  27388. }
  27389. else {
  27390. var aniOwnerTrans = this._cacheAnimator.owner._transform;
  27391. Matrix4x4.multiply(projectionView, aniOwnerTrans.worldMatrix, this._projectionViewWorldMatrix);
  27392. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  27393. }
  27394. }
  27395. else {
  27396. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  27397. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  27398. }
  27399. }
  27400. _destroy() {
  27401. super._destroy();
  27402. if (!this._cacheAvatar) {
  27403. if (this._cacheRootBone)
  27404. (!this._cacheRootBone.destroyed) && (this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  27405. else
  27406. (this._owner && !this._owner.destroyed) && (this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  27407. }
  27408. else {
  27409. if (this._cacheRootAnimationNode)
  27410. this._cacheRootAnimationNode.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27411. }
  27412. }
  27413. get bounds() {
  27414. if (this._boundsChange || this._cacheAvatar) {
  27415. this._calculateBoundingBox();
  27416. this._boundsChange = false;
  27417. }
  27418. return this._bounds;
  27419. }
  27420. _setRootBone(name) {
  27421. this._rootBone = name;
  27422. this._setRootNode();
  27423. }
  27424. _setRootNode() {
  27425. var rootNode;
  27426. if (this._cacheAnimator && this._rootBone && this._cacheAvatar)
  27427. rootNode = this._cacheAnimator._avatarNodeMap[this._rootBone];
  27428. else
  27429. rootNode = null;
  27430. if (this._cacheRootAnimationNode != rootNode) {
  27431. this._onWorldMatNeedChange(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE);
  27432. this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27433. if (this._cacheRootAnimationNode)
  27434. this._cacheRootAnimationNode.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27435. (rootNode) && (rootNode.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  27436. this._cacheRootAnimationNode = rootNode;
  27437. }
  27438. }
  27439. _getCacheAnimationNodes() {
  27440. var meshBoneNames = this._cacheMesh._boneNames;
  27441. var innerBindPoseCount = this._cacheMesh._inverseBindPoses.length;
  27442. if (!Laya.Render.supportWebGLPlusAnimation) {
  27443. this._cacheAnimationNode.length = innerBindPoseCount;
  27444. var nodeMap = this._cacheAnimator._avatarNodeMap;
  27445. for (var i = 0; i < innerBindPoseCount; i++) {
  27446. var node = nodeMap[meshBoneNames[i]];
  27447. this._cacheAnimationNode[i] = node;
  27448. }
  27449. }
  27450. else {
  27451. this._cacheAnimationNodeIndices = new Uint16Array(innerBindPoseCount);
  27452. var nodeMapC = this._cacheAnimator._avatarNodeMap;
  27453. for (i = 0; i < innerBindPoseCount; i++) {
  27454. var nodeC = nodeMapC[meshBoneNames[i]];
  27455. this._cacheAnimationNodeIndices[i] = nodeC ? nodeC._worldMatrixIndex : 0;
  27456. }
  27457. }
  27458. }
  27459. _setCacheAvatar(value) {
  27460. if (this._cacheAvatar !== value) {
  27461. if (this._cacheMesh) {
  27462. this._cacheAvatar = value;
  27463. if (value) {
  27464. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  27465. this._getCacheAnimationNodes();
  27466. }
  27467. }
  27468. else {
  27469. this._cacheAvatar = value;
  27470. }
  27471. this._setRootNode();
  27472. }
  27473. }
  27474. _computeSubSkinnedDataNative(worldMatrixs, cacheAnimationNodeIndices, inverseBindPosesBuffer, boneIndices, data) {
  27475. Laya.LayaGL.instance.computeSubSkinnedData(worldMatrixs, cacheAnimationNodeIndices, inverseBindPosesBuffer, boneIndices, data);
  27476. }
  27477. _computeSkinnedDataForNative() {
  27478. if (this._cacheMesh && this._cacheAvatar || this._cacheMesh && !this._cacheAvatar) {
  27479. var bindPoses = this._cacheMesh._inverseBindPoses;
  27480. var pathMarks = this._cacheMesh._skinnedMatrixCaches;
  27481. for (var i = 0, n = this._cacheMesh.subMeshCount; i < n; i++) {
  27482. var subMeshBoneIndices = this._cacheMesh.getSubMesh(i)._boneIndicesList;
  27483. var subData = this._skinnedData[i];
  27484. for (var j = 0, m = subMeshBoneIndices.length; j < m; j++) {
  27485. var boneIndices = subMeshBoneIndices[j];
  27486. if (this._cacheAvatar && Laya.Render.supportWebGLPlusAnimation)
  27487. this._computeSubSkinnedDataNative(this._cacheAnimator._animationNodeWorldMatrixs, this._cacheAnimationNodeIndices, this._cacheMesh._inverseBindPosesBuffer, boneIndices, subData[j]);
  27488. else
  27489. this._computeSubSkinnedData(bindPoses, boneIndices, subData[j], pathMarks);
  27490. }
  27491. }
  27492. }
  27493. }
  27494. }
  27495. SkinnedMeshRenderer._tempMatrix4x4 = new Matrix4x4();
  27496. class SkinnedMeshSprite3D extends RenderableSprite3D {
  27497. constructor(mesh = null, name = null) {
  27498. super(name);
  27499. this._meshFilter = new MeshFilter(this);
  27500. this._render = new SkinnedMeshRenderer(this);
  27501. (mesh) && (this._meshFilter.sharedMesh = mesh);
  27502. }
  27503. static __init__() {
  27504. SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE = Shader3D.getDefineByName("BONE");
  27505. }
  27506. get meshFilter() {
  27507. return this._meshFilter;
  27508. }
  27509. get skinnedMeshRenderer() {
  27510. return this._render;
  27511. }
  27512. _parse(data, spriteMap) {
  27513. super._parse(data, spriteMap);
  27514. var render = this.skinnedMeshRenderer;
  27515. var lightmapIndex = data.lightmapIndex;
  27516. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  27517. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  27518. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  27519. (data.enableRender != undefined) && (render.enable = data.enableRender);
  27520. (data.receiveShadows != undefined) && (render.receiveShadow = data.receiveShadows);
  27521. (data.castShadow != undefined) && (render.castShadow = data.castShadow);
  27522. var meshPath;
  27523. meshPath = data.meshPath;
  27524. if (meshPath) {
  27525. var mesh = Laya.Loader.getRes(meshPath);
  27526. (mesh) && (this.meshFilter.sharedMesh = mesh);
  27527. }
  27528. var materials = data.materials;
  27529. if (materials) {
  27530. var sharedMaterials = render.sharedMaterials;
  27531. var materialCount = materials.length;
  27532. sharedMaterials.length = materialCount;
  27533. for (var i = 0; i < materialCount; i++) {
  27534. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  27535. }
  27536. render.sharedMaterials = sharedMaterials;
  27537. }
  27538. var boundBox = data.boundBox;
  27539. var min = boundBox.min;
  27540. var max = boundBox.max;
  27541. render.localBounds.setMin(new Vector3(min[0], min[1], min[2]));
  27542. render.localBounds.setMax(new Vector3(max[0], max[1], max[2]));
  27543. if (spriteMap) {
  27544. var rootBoneData = data.rootBone;
  27545. render.rootBone = spriteMap[rootBoneData];
  27546. var bonesData = data.bones;
  27547. var n;
  27548. for (i = 0, n = bonesData.length; i < n; i++)
  27549. render.bones.push(spriteMap[bonesData[i]]);
  27550. }
  27551. else {
  27552. (data.rootBone) && (render._setRootBone(data.rootBone));
  27553. }
  27554. }
  27555. _changeHierarchyAnimator(animator) {
  27556. super._changeHierarchyAnimator(animator);
  27557. this.skinnedMeshRenderer._setCacheAnimator(animator);
  27558. }
  27559. _changeAnimatorAvatar(avatar) {
  27560. this.skinnedMeshRenderer._setCacheAvatar(avatar);
  27561. }
  27562. _cloneTo(destObject, srcRoot, dstRoot) {
  27563. var meshSprite3D = destObject;
  27564. meshSprite3D.meshFilter.sharedMesh = this.meshFilter.sharedMesh;
  27565. var meshRender = this._render;
  27566. var destMeshRender = meshSprite3D._render;
  27567. destMeshRender.enable = meshRender.enable;
  27568. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  27569. destMeshRender.castShadow = meshRender.castShadow;
  27570. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  27571. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  27572. destMeshRender.receiveShadow = meshRender.receiveShadow;
  27573. destMeshRender.sortingFudge = meshRender.sortingFudge;
  27574. destMeshRender._rootBone = meshRender._rootBone;
  27575. var bones = meshRender.bones;
  27576. var destBones = destMeshRender.bones;
  27577. var bonesCount = bones.length;
  27578. destBones.length = bonesCount;
  27579. var rootBone = meshRender.rootBone;
  27580. if (rootBone) {
  27581. var pathes = Utils3D._getHierarchyPath(srcRoot, rootBone, SkinnedMeshSprite3D._tempArray0);
  27582. if (pathes)
  27583. destMeshRender.rootBone = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  27584. else
  27585. destMeshRender.rootBone = rootBone;
  27586. }
  27587. for (var i = 0; i < bones.length; i++) {
  27588. pathes = Utils3D._getHierarchyPath(srcRoot, bones[i], SkinnedMeshSprite3D._tempArray0);
  27589. if (pathes)
  27590. destBones[i] = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  27591. else
  27592. destBones[i] = bones[i];
  27593. }
  27594. var lbb = meshRender.localBounds;
  27595. (lbb) && (lbb.cloneTo(destMeshRender.localBounds));
  27596. super._cloneTo(destObject, srcRoot, dstRoot);
  27597. }
  27598. destroy(destroyChild = true) {
  27599. if (this.destroyed)
  27600. return;
  27601. super.destroy(destroyChild);
  27602. this._meshFilter.destroy();
  27603. }
  27604. _create() {
  27605. return new SkinnedMeshSprite3D();
  27606. }
  27607. }
  27608. SkinnedMeshSprite3D._tempArray0 = [];
  27609. SkinnedMeshSprite3D.BONES = Shader3D.propertyNameToID("u_Bones");
  27610. class TrailMaterial extends Material {
  27611. constructor() {
  27612. super();
  27613. this.setShaderName("Trail");
  27614. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  27615. this._shaderValues.setVector(TrailMaterial.TINTCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  27616. this.renderMode = TrailMaterial.RENDERMODE_ALPHABLENDED;
  27617. }
  27618. static __initDefine__() {
  27619. TrailMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  27620. TrailMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  27621. TrailMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  27622. }
  27623. get _TintColorR() {
  27624. return this._color.x;
  27625. }
  27626. set _TintColorR(value) {
  27627. this._color.x = value;
  27628. this.color = this._color;
  27629. }
  27630. get _TintColorG() {
  27631. return this._color.y;
  27632. }
  27633. set _TintColorG(value) {
  27634. this._color.y = value;
  27635. this.color = this._color;
  27636. }
  27637. get _TintColorB() {
  27638. return this._color.z;
  27639. }
  27640. set _TintColorB(value) {
  27641. this._color.z = value;
  27642. this.color = this._color;
  27643. }
  27644. get _TintColorA() {
  27645. return this._color.w;
  27646. }
  27647. set _TintColorA(value) {
  27648. this._color.w = value;
  27649. this.color = this._color;
  27650. }
  27651. get _MainTex_STX() {
  27652. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).x;
  27653. }
  27654. set _MainTex_STX(x) {
  27655. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27656. tilOff.x = x;
  27657. this.tilingOffset = tilOff;
  27658. }
  27659. get _MainTex_STY() {
  27660. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).y;
  27661. }
  27662. set _MainTex_STY(y) {
  27663. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27664. tilOff.y = y;
  27665. this.tilingOffset = tilOff;
  27666. }
  27667. get _MainTex_STZ() {
  27668. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).z;
  27669. }
  27670. set _MainTex_STZ(z) {
  27671. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27672. tilOff.z = z;
  27673. this.tilingOffset = tilOff;
  27674. }
  27675. get _MainTex_STW() {
  27676. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).w;
  27677. }
  27678. set _MainTex_STW(w) {
  27679. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27680. tilOff.w = w;
  27681. this.tilingOffset = tilOff;
  27682. }
  27683. set renderMode(value) {
  27684. switch (value) {
  27685. case TrailMaterial.RENDERMODE_ADDTIVE:
  27686. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  27687. this.alphaTest = false;
  27688. this.depthWrite = false;
  27689. this.cull = RenderState.CULL_NONE;
  27690. this.blend = RenderState.BLEND_ENABLE_ALL;
  27691. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  27692. this.blendDst = RenderState.BLENDPARAM_ONE;
  27693. this.depthTest = RenderState.DEPTHTEST_LESS;
  27694. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_ADDTIVEFOG);
  27695. break;
  27696. case TrailMaterial.RENDERMODE_ALPHABLENDED:
  27697. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  27698. this.alphaTest = false;
  27699. this.depthWrite = false;
  27700. this.cull = RenderState.CULL_NONE;
  27701. this.blend = RenderState.BLEND_ENABLE_ALL;
  27702. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  27703. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  27704. this.depthTest = RenderState.DEPTHTEST_LESS;
  27705. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_ADDTIVEFOG);
  27706. break;
  27707. default:
  27708. throw new Error("TrailMaterial : renderMode value error.");
  27709. }
  27710. }
  27711. get colorR() {
  27712. return this._TintColorR;
  27713. }
  27714. set colorR(value) {
  27715. this._TintColorR = value;
  27716. }
  27717. get colorG() {
  27718. return this._TintColorG;
  27719. }
  27720. set colorG(value) {
  27721. this._TintColorG = value;
  27722. }
  27723. get colorB() {
  27724. return this._TintColorB;
  27725. }
  27726. set colorB(value) {
  27727. this._TintColorB = value;
  27728. }
  27729. get colorA() {
  27730. return this._TintColorA;
  27731. }
  27732. set colorA(value) {
  27733. this._TintColorA = value;
  27734. }
  27735. get color() {
  27736. return this._shaderValues.getVector(TrailMaterial.TINTCOLOR);
  27737. }
  27738. set color(value) {
  27739. this._shaderValues.setVector(TrailMaterial.TINTCOLOR, value);
  27740. }
  27741. get texture() {
  27742. return this._shaderValues.getTexture(TrailMaterial.MAINTEXTURE);
  27743. }
  27744. set texture(value) {
  27745. if (value)
  27746. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_MAINTEXTURE);
  27747. else
  27748. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_MAINTEXTURE);
  27749. this._shaderValues.setTexture(TrailMaterial.MAINTEXTURE, value);
  27750. }
  27751. get tilingOffsetX() {
  27752. return this._MainTex_STX;
  27753. }
  27754. set tilingOffsetX(x) {
  27755. this._MainTex_STX = x;
  27756. }
  27757. get tilingOffsetY() {
  27758. return this._MainTex_STY;
  27759. }
  27760. set tilingOffsetY(y) {
  27761. this._MainTex_STY = y;
  27762. }
  27763. get tilingOffsetZ() {
  27764. return this._MainTex_STZ;
  27765. }
  27766. set tilingOffsetZ(z) {
  27767. this._MainTex_STZ = z;
  27768. }
  27769. get tilingOffsetW() {
  27770. return this._MainTex_STW;
  27771. }
  27772. set tilingOffsetW(w) {
  27773. this._MainTex_STW = w;
  27774. }
  27775. get tilingOffset() {
  27776. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27777. }
  27778. set tilingOffset(value) {
  27779. if (value) {
  27780. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  27781. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  27782. else
  27783. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  27784. }
  27785. else {
  27786. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  27787. }
  27788. this._shaderValues.setVector(TrailMaterial.TILINGOFFSET, value);
  27789. }
  27790. set depthWrite(value) {
  27791. this._shaderValues.setBool(TrailMaterial.DEPTH_WRITE, value);
  27792. }
  27793. get depthWrite() {
  27794. return this._shaderValues.getBool(TrailMaterial.DEPTH_WRITE);
  27795. }
  27796. set cull(value) {
  27797. this._shaderValues.setInt(TrailMaterial.CULL, value);
  27798. }
  27799. get cull() {
  27800. return this._shaderValues.getInt(TrailMaterial.CULL);
  27801. }
  27802. set blend(value) {
  27803. this._shaderValues.setInt(TrailMaterial.BLEND, value);
  27804. }
  27805. get blend() {
  27806. return this._shaderValues.getInt(TrailMaterial.BLEND);
  27807. }
  27808. set blendSrc(value) {
  27809. this._shaderValues.setInt(TrailMaterial.BLEND_SRC, value);
  27810. }
  27811. get blendSrc() {
  27812. return this._shaderValues.getInt(TrailMaterial.BLEND_SRC);
  27813. }
  27814. set blendDst(value) {
  27815. this._shaderValues.setInt(TrailMaterial.BLEND_DST, value);
  27816. }
  27817. get blendDst() {
  27818. return this._shaderValues.getInt(TrailMaterial.BLEND_DST);
  27819. }
  27820. set depthTest(value) {
  27821. this._shaderValues.setInt(TrailMaterial.DEPTH_TEST, value);
  27822. }
  27823. get depthTest() {
  27824. return this._shaderValues.getInt(TrailMaterial.DEPTH_TEST);
  27825. }
  27826. clone() {
  27827. var dest = new TrailMaterial();
  27828. this.cloneTo(dest);
  27829. return dest;
  27830. }
  27831. }
  27832. TrailMaterial.RENDERMODE_ALPHABLENDED = 0;
  27833. TrailMaterial.RENDERMODE_ADDTIVE = 1;
  27834. TrailMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_MainTexture");
  27835. TrailMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_MainColor");
  27836. TrailMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  27837. TrailMaterial.CULL = Shader3D.propertyNameToID("s_Cull");
  27838. TrailMaterial.BLEND = Shader3D.propertyNameToID("s_Blend");
  27839. TrailMaterial.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  27840. TrailMaterial.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  27841. TrailMaterial.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  27842. TrailMaterial.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  27843. class TextureMode {
  27844. }
  27845. TextureMode.Stretch = 0;
  27846. TextureMode.Tile = 1;
  27847. (function (TrailAlignment) {
  27848. TrailAlignment[TrailAlignment["View"] = 0] = "View";
  27849. TrailAlignment[TrailAlignment["TransformZ"] = 1] = "TransformZ";
  27850. })(exports.TrailAlignment || (exports.TrailAlignment = {}));
  27851. class VertexTrail {
  27852. static get vertexDeclaration1() {
  27853. return VertexTrail._vertexDeclaration1;
  27854. }
  27855. static get vertexDeclaration2() {
  27856. return VertexTrail._vertexDeclaration2;
  27857. }
  27858. get vertexDeclaration() {
  27859. return VertexTrail._vertexDeclaration1;
  27860. }
  27861. static __init__() {
  27862. VertexTrail._vertexDeclaration1 = new VertexDeclaration(32, [new VertexElement(0, VertexElementFormat.Vector3, VertexTrail.TRAIL_POSITION0),
  27863. new VertexElement(12, VertexElementFormat.Vector3, VertexTrail.TRAIL_OFFSETVECTOR),
  27864. new VertexElement(24, VertexElementFormat.Single, VertexTrail.TRAIL_TIME0),
  27865. new VertexElement(28, VertexElementFormat.Single, VertexTrail.TRAIL_TEXTURECOORDINATE0Y)]);
  27866. VertexTrail._vertexDeclaration2 = new VertexDeclaration(20, [new VertexElement(0, VertexElementFormat.Single, VertexTrail.TRAIL_TEXTURECOORDINATE0X),
  27867. new VertexElement(4, VertexElementFormat.Color, VertexTrail.TRAIL_COLOR)]);
  27868. }
  27869. }
  27870. VertexTrail.TRAIL_POSITION0 = 0;
  27871. VertexTrail.TRAIL_OFFSETVECTOR = 1;
  27872. VertexTrail.TRAIL_TIME0 = 2;
  27873. VertexTrail.TRAIL_TEXTURECOORDINATE0Y = 3;
  27874. VertexTrail.TRAIL_TEXTURECOORDINATE0X = 4;
  27875. VertexTrail.TRAIL_COLOR = 5;
  27876. class TrailGeometry extends GeometryElement {
  27877. constructor(owner) {
  27878. super();
  27879. this._floatCountPerVertices1 = 8;
  27880. this._floatCountPerVertices2 = 5;
  27881. this._increaseSegementCount = 16;
  27882. this._activeIndex = 0;
  27883. this._endIndex = 0;
  27884. this._needAddFirstVertex = false;
  27885. this._isTempEndVertex = false;
  27886. this._vertices1 = null;
  27887. this._vertices2 = null;
  27888. this._lastFixedVertexPosition = new Vector3();
  27889. this._bufferState = new BufferState();
  27890. this.tmpColor = new Color();
  27891. this._disappearBoundsMode = false;
  27892. this._owner = owner;
  27893. this._segementCount = this._increaseSegementCount;
  27894. this._resizeData(this._segementCount, this._bufferState);
  27895. var bounds = this._owner._owner.trailRenderer.bounds;
  27896. var sprite3dPosition = this._owner._owner.transform.position;
  27897. bounds.setMin(sprite3dPosition);
  27898. bounds.setMax(sprite3dPosition);
  27899. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  27900. }
  27901. _resizeData(segementCount, bufferState) {
  27902. this._subBirthTime = new Float32Array(segementCount);
  27903. this._subDistance = new Float64Array(segementCount);
  27904. var gl = Laya.LayaGL.instance;
  27905. var vertexCount = segementCount * 2;
  27906. var vertexDeclaration1 = VertexTrail.vertexDeclaration1;
  27907. var vertexDeclaration2 = VertexTrail.vertexDeclaration2;
  27908. var vertexBuffers = [];
  27909. var vertexbuffer1Size = vertexCount * vertexDeclaration1.vertexStride;
  27910. var vertexbuffer2Size = vertexCount * vertexDeclaration2.vertexStride;
  27911. var memorySize = vertexbuffer1Size + vertexbuffer2Size;
  27912. this._vertices1 = new Float32Array(vertexCount * this._floatCountPerVertices1);
  27913. this._vertices2 = new Float32Array(vertexCount * this._floatCountPerVertices2);
  27914. this._vertexBuffer1 = new VertexBuffer3D(vertexbuffer1Size, gl.STATIC_DRAW, false);
  27915. this._vertexBuffer1.vertexDeclaration = vertexDeclaration1;
  27916. this._vertexBuffer2 = new VertexBuffer3D(vertexbuffer2Size, gl.DYNAMIC_DRAW, false);
  27917. this._vertexBuffer2.vertexDeclaration = vertexDeclaration2;
  27918. vertexBuffers.push(this._vertexBuffer1);
  27919. vertexBuffers.push(this._vertexBuffer2);
  27920. bufferState.bind();
  27921. bufferState.applyVertexBuffers(vertexBuffers);
  27922. bufferState.unBind();
  27923. Laya.Resource._addMemory(memorySize, memorySize);
  27924. }
  27925. _resetData() {
  27926. var count = this._endIndex - this._activeIndex;
  27927. var oldVertices1 = new Float32Array(this._vertices1.buffer, this._floatCountPerVertices1 * 2 * this._activeIndex * 4, this._floatCountPerVertices1 * 2 * count);
  27928. var oldVertices2 = new Float32Array(this._vertices2.buffer, this._floatCountPerVertices2 * 2 * this._activeIndex * 4, this._floatCountPerVertices2 * 2 * count);
  27929. var oldSubDistance = new Float64Array(this._subDistance.buffer, this._activeIndex * 8, count);
  27930. var oldSubBirthTime = new Float32Array(this._subBirthTime.buffer, this._activeIndex * 4, count);
  27931. if (count === this._segementCount) {
  27932. this._vertexBuffer1.destroy();
  27933. this._vertexBuffer2.destroy();
  27934. var memorySize = this._vertexBuffer1._byteLength + this._vertexBuffer2._byteLength;
  27935. Laya.Resource._addMemory(-memorySize, -memorySize);
  27936. this._segementCount += this._increaseSegementCount;
  27937. this._resizeData(this._segementCount, this._bufferState);
  27938. }
  27939. this._vertices1.set(oldVertices1, 0);
  27940. this._vertices2.set(oldVertices2, 0);
  27941. this._subDistance.set(oldSubDistance, 0);
  27942. this._subBirthTime.set(oldSubBirthTime, 0);
  27943. this._endIndex = count;
  27944. this._activeIndex = 0;
  27945. this._vertexBuffer1.setData(this._vertices1.buffer, 0, this._floatCountPerVertices1 * 2 * this._activeIndex * 4, this._floatCountPerVertices1 * 2 * count * 4);
  27946. this._vertexBuffer2.setData(this._vertices2.buffer, 0, this._floatCountPerVertices2 * 2 * this._activeIndex * 4, this._floatCountPerVertices2 * 2 * count * 4);
  27947. }
  27948. _updateTrail(camera, lastPosition, position) {
  27949. if (!Vector3.equals(lastPosition, position)) {
  27950. if ((this._endIndex - this._activeIndex) === 0)
  27951. this._addTrailByFirstPosition(camera, position);
  27952. else
  27953. this._addTrailByNextPosition(camera, position);
  27954. }
  27955. }
  27956. _addTrailByFirstPosition(camera, position) {
  27957. (this._endIndex === this._segementCount) && (this._resetData());
  27958. this._subDistance[this._endIndex] = 0;
  27959. this._subBirthTime[this._endIndex] = this._owner._curtime;
  27960. this._endIndex++;
  27961. position.cloneTo(this._lastFixedVertexPosition);
  27962. this._needAddFirstVertex = true;
  27963. }
  27964. _addTrailByNextPosition(camera, position) {
  27965. var delVector3 = TrailGeometry._tempVector30;
  27966. var pointAtoBVector3 = TrailGeometry._tempVector31;
  27967. switch (this._owner.alignment) {
  27968. case exports.TrailAlignment.View:
  27969. var cameraMatrix = camera.viewMatrix;
  27970. Vector3.transformCoordinate(position, cameraMatrix, TrailGeometry._tempVector33);
  27971. Vector3.transformCoordinate(this._lastFixedVertexPosition, cameraMatrix, TrailGeometry._tempVector34);
  27972. Vector3.subtract(TrailGeometry._tempVector33, TrailGeometry._tempVector34, delVector3);
  27973. Vector3.cross(TrailGeometry._tempVector33, delVector3, pointAtoBVector3);
  27974. break;
  27975. case exports.TrailAlignment.TransformZ:
  27976. Vector3.subtract(position, this._lastFixedVertexPosition, delVector3);
  27977. var forward = TrailGeometry._tempVector32;
  27978. this._owner._owner.transform.getForward(forward);
  27979. Vector3.cross(delVector3, forward, pointAtoBVector3);
  27980. break;
  27981. }
  27982. Vector3.normalize(pointAtoBVector3, pointAtoBVector3);
  27983. Vector3.scale(pointAtoBVector3, this._owner.widthMultiplier / 2, pointAtoBVector3);
  27984. var delLength = Vector3.scalarLength(delVector3);
  27985. var tempEndIndex;
  27986. var offset;
  27987. if (this._needAddFirstVertex) {
  27988. this._updateVerticesByPositionData(position, pointAtoBVector3, this._endIndex - 1);
  27989. this._needAddFirstVertex = false;
  27990. }
  27991. if (delLength - this._owner.minVertexDistance >= MathUtils3D.zeroTolerance) {
  27992. if (this._isTempEndVertex) {
  27993. tempEndIndex = this._endIndex - 1;
  27994. offset = delLength - this._subDistance[tempEndIndex];
  27995. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, tempEndIndex);
  27996. this._owner._totalLength += offset;
  27997. }
  27998. else {
  27999. (this._endIndex === this._segementCount) && (this._resetData());
  28000. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, this._endIndex);
  28001. this._owner._totalLength += delLength;
  28002. this._endIndex++;
  28003. }
  28004. position.cloneTo(this._lastFixedVertexPosition);
  28005. this._isTempEndVertex = false;
  28006. }
  28007. else {
  28008. if (this._isTempEndVertex) {
  28009. tempEndIndex = this._endIndex - 1;
  28010. offset = delLength - this._subDistance[tempEndIndex];
  28011. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, tempEndIndex);
  28012. this._owner._totalLength += offset;
  28013. }
  28014. else {
  28015. (this._endIndex === this._segementCount) && (this._resetData());
  28016. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, this._endIndex);
  28017. this._owner._totalLength += delLength;
  28018. this._endIndex++;
  28019. }
  28020. this._isTempEndVertex = true;
  28021. }
  28022. }
  28023. _updateVerticesByPositionData(position, pointAtoBVector3, index) {
  28024. var vertexOffset = this._floatCountPerVertices1 * 2 * index;
  28025. var curtime = this._owner._curtime;
  28026. this._vertices1[vertexOffset] = position.x;
  28027. this._vertices1[vertexOffset + 1] = position.y;
  28028. this._vertices1[vertexOffset + 2] = position.z;
  28029. this._vertices1[vertexOffset + 3] = -pointAtoBVector3.x;
  28030. this._vertices1[vertexOffset + 4] = -pointAtoBVector3.y;
  28031. this._vertices1[vertexOffset + 5] = -pointAtoBVector3.z;
  28032. this._vertices1[vertexOffset + 6] = curtime;
  28033. this._vertices1[vertexOffset + 7] = 1.0;
  28034. this._vertices1[vertexOffset + 8] = position.x;
  28035. this._vertices1[vertexOffset + 9] = position.y;
  28036. this._vertices1[vertexOffset + 10] = position.z;
  28037. this._vertices1[vertexOffset + 11] = pointAtoBVector3.x;
  28038. this._vertices1[vertexOffset + 12] = pointAtoBVector3.y;
  28039. this._vertices1[vertexOffset + 13] = pointAtoBVector3.z;
  28040. this._vertices1[vertexOffset + 14] = curtime;
  28041. this._vertices1[vertexOffset + 15] = 0.0;
  28042. var bounds = this._owner._owner.trailRenderer.bounds;
  28043. var min = bounds.getMin();
  28044. var max = bounds.getMax();
  28045. var up = TrailGeometry._tempVector35;
  28046. var down = TrailGeometry._tempVector36;
  28047. var out = TrailGeometry._tempVector32;
  28048. Vector3.add(position, pointAtoBVector3, up);
  28049. Vector3.subtract(position, pointAtoBVector3, down);
  28050. Vector3.min(down, up, out);
  28051. Vector3.min(min, out, min);
  28052. bounds.setMin(min);
  28053. Vector3.max(up, down, out);
  28054. Vector3.max(max, out, max);
  28055. bounds.setMax(max);
  28056. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  28057. var floatCount = this._floatCountPerVertices1 * 2;
  28058. this._vertexBuffer1.setData(this._vertices1.buffer, vertexOffset * 4, vertexOffset * 4, floatCount * 4);
  28059. }
  28060. _updateVerticesByPosition(position, pointAtoBVector3, delDistance, index) {
  28061. this._updateVerticesByPositionData(position, pointAtoBVector3, index);
  28062. this._subDistance[index] = delDistance;
  28063. this._subBirthTime[index] = this._owner._curtime;
  28064. }
  28065. _updateVertexBufferUV() {
  28066. var bounds;
  28067. var min, max;
  28068. if (this._disappearBoundsMode) {
  28069. bounds = this._owner._owner.trailRenderer.bounds;
  28070. var sprite3dPosition = this._owner._owner.transform.position;
  28071. bounds.setMin(sprite3dPosition);
  28072. bounds.setMax(sprite3dPosition);
  28073. min = bounds.getMin();
  28074. max = bounds.getMax();
  28075. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  28076. }
  28077. var vertexCount = this._endIndex;
  28078. var curLength = 0;
  28079. var gradient = this._owner.colorGradient;
  28080. var startAlphaIndex = gradient.colorAlphaKeysCount - 1;
  28081. var startColorIndex = gradient.colorRGBKeysCount - 1;
  28082. var totalLength = this._owner._totalLength;
  28083. var stride = this._floatCountPerVertices2 * 2;
  28084. for (var i = this._activeIndex; i < vertexCount; i++) {
  28085. (i !== this._activeIndex) && (curLength += this._subDistance[i]);
  28086. var uvX;
  28087. var lerpFactor;
  28088. if (this._owner.textureMode == TextureMode.Stretch) {
  28089. uvX = 1.0 - curLength / totalLength;
  28090. lerpFactor = uvX;
  28091. }
  28092. else {
  28093. lerpFactor = 1.0 - curLength / totalLength;
  28094. uvX = 1.0 - (totalLength - curLength);
  28095. }
  28096. startColorIndex = gradient.evaluateColorRGB(lerpFactor, this.tmpColor, startColorIndex, true);
  28097. startAlphaIndex = gradient.evaluateColorAlpha(lerpFactor, this.tmpColor, startAlphaIndex, true);
  28098. var index = i * stride;
  28099. this._vertices2[index + 0] = uvX;
  28100. this._vertices2[index + 1] = this.tmpColor.r;
  28101. this._vertices2[index + 2] = this.tmpColor.g;
  28102. this._vertices2[index + 3] = this.tmpColor.b;
  28103. this._vertices2[index + 4] = this.tmpColor.a;
  28104. this._vertices2[index + 5] = uvX;
  28105. this._vertices2[index + 6] = this.tmpColor.r;
  28106. this._vertices2[index + 7] = this.tmpColor.g;
  28107. this._vertices2[index + 8] = this.tmpColor.b;
  28108. this._vertices2[index + 9] = this.tmpColor.a;
  28109. if (this._disappearBoundsMode) {
  28110. var posOffset = this._floatCountPerVertices1 * 2 * i;
  28111. var pos = TrailGeometry._tempVector32;
  28112. var up = TrailGeometry._tempVector33;
  28113. var side = TrailGeometry._tempVector34;
  28114. pos.setValue(this._vertices1[posOffset + 0], this._vertices1[posOffset + 1], this._vertices1[posOffset + 2]);
  28115. up.setValue(this._vertices1[posOffset + 3], this._vertices1[posOffset + 4], this._vertices1[posOffset + 5]);
  28116. Vector3.add(pos, up, side);
  28117. Vector3.min(side, min, min);
  28118. Vector3.max(side, max, max);
  28119. Vector3.subtract(pos, up, side);
  28120. Vector3.min(side, min, min);
  28121. Vector3.max(side, max, max);
  28122. }
  28123. }
  28124. if (this._disappearBoundsMode) {
  28125. bounds.setMin(min);
  28126. bounds.setMax(max);
  28127. this._disappearBoundsMode = false;
  28128. Laya.Render.supportWebGLPlusCulling && this._calculateBoundingBoxForNative();
  28129. }
  28130. var offset = this._activeIndex * stride;
  28131. this._vertexBuffer2.setData(this._vertices2.buffer, offset * 4, offset * 4, (vertexCount * stride - offset) * 4);
  28132. }
  28133. _updateDisappear() {
  28134. var count = this._endIndex;
  28135. for (var i = this._activeIndex; i < count; i++) {
  28136. if (this._owner._curtime - this._subBirthTime[i] >= this._owner.time + MathUtils3D.zeroTolerance) {
  28137. var nextIndex = i + 1;
  28138. if (nextIndex !== count)
  28139. this._owner._totalLength -= this._subDistance[nextIndex];
  28140. if (this._isTempEndVertex && (nextIndex === count - 1)) {
  28141. var offset = this._floatCountPerVertices1 * i * 2;
  28142. var fixedPos = this._lastFixedVertexPosition;
  28143. fixedPos.x = this._vertices1[0];
  28144. fixedPos.y = this._vertices1[1];
  28145. fixedPos.z = this._vertices1[2];
  28146. this._isTempEndVertex = false;
  28147. }
  28148. this._activeIndex++;
  28149. this._disappearBoundsMode = true;
  28150. }
  28151. else {
  28152. break;
  28153. }
  28154. }
  28155. }
  28156. _getType() {
  28157. return TrailGeometry._type;
  28158. }
  28159. _prepareRender(state) {
  28160. return this._endIndex - this._activeIndex > 1;
  28161. }
  28162. _render(state) {
  28163. this._bufferState.bind();
  28164. var gl = Laya.LayaGL.instance;
  28165. var start = this._activeIndex * 2;
  28166. var count = this._endIndex * 2 - start;
  28167. gl.drawArrays(gl.TRIANGLE_STRIP, start, count);
  28168. Laya.Stat.renderBatches++;
  28169. Laya.Stat.trianglesFaces += count - 2;
  28170. }
  28171. destroy() {
  28172. super.destroy();
  28173. var memorySize = this._vertexBuffer1._byteLength + this._vertexBuffer2._byteLength;
  28174. Laya.Resource._addMemory(-memorySize, -memorySize);
  28175. this._bufferState.destroy();
  28176. this._vertexBuffer1.destroy();
  28177. this._vertexBuffer2.destroy();
  28178. this._bufferState = null;
  28179. this._vertices1 = null;
  28180. this._vertexBuffer1 = null;
  28181. this._vertices2 = null;
  28182. this._vertexBuffer2 = null;
  28183. this._subBirthTime = null;
  28184. this._subDistance = null;
  28185. this._lastFixedVertexPosition = null;
  28186. this._disappearBoundsMode = false;
  28187. }
  28188. _calculateBoundingBoxForNative() {
  28189. var trail = this._owner._owner.trailRenderer;
  28190. var bounds = trail.bounds;
  28191. var min = bounds.getMin();
  28192. var max = bounds.getMax();
  28193. var buffer = FrustumCulling._cullingBuffer;
  28194. buffer[trail._cullingBufferIndex + 1] = min.x;
  28195. buffer[trail._cullingBufferIndex + 2] = min.y;
  28196. buffer[trail._cullingBufferIndex + 3] = min.z;
  28197. buffer[trail._cullingBufferIndex + 4] = max.x;
  28198. buffer[trail._cullingBufferIndex + 5] = max.y;
  28199. buffer[trail._cullingBufferIndex + 6] = max.z;
  28200. }
  28201. clear() {
  28202. this._activeIndex = 0;
  28203. this._endIndex = 0;
  28204. this._disappearBoundsMode = false;
  28205. this._subBirthTime.fill(0);
  28206. this._subDistance.fill(0);
  28207. this._segementCount = 0;
  28208. this._isTempEndVertex = false;
  28209. this._needAddFirstVertex = false;
  28210. this._lastFixedVertexPosition.setValue(0, 0, 0);
  28211. }
  28212. }
  28213. TrailGeometry.ALIGNMENT_VIEW = 0;
  28214. TrailGeometry.ALIGNMENT_TRANSFORM_Z = 1;
  28215. TrailGeometry._tempVector30 = new Vector3();
  28216. TrailGeometry._tempVector31 = new Vector3();
  28217. TrailGeometry._tempVector32 = new Vector3();
  28218. TrailGeometry._tempVector33 = new Vector3();
  28219. TrailGeometry._tempVector34 = new Vector3();
  28220. TrailGeometry._tempVector35 = new Vector3();
  28221. TrailGeometry._tempVector36 = new Vector3();
  28222. TrailGeometry._type = GeometryElement._typeCounter++;
  28223. class TrailFilter {
  28224. constructor(owner) {
  28225. this._totalLength = 0;
  28226. this._lastPosition = new Vector3();
  28227. this._curtime = 0;
  28228. this.alignment = TrailFilter.ALIGNMENT_VIEW;
  28229. this._owner = owner;
  28230. this._initDefaultData();
  28231. this.addRenderElement();
  28232. }
  28233. get time() {
  28234. return this._time;
  28235. }
  28236. set time(value) {
  28237. this._time = value;
  28238. this._owner._render._shaderValues.setNumber(TrailFilter.LIFETIME, value);
  28239. }
  28240. get minVertexDistance() {
  28241. return this._minVertexDistance;
  28242. }
  28243. set minVertexDistance(value) {
  28244. this._minVertexDistance = value;
  28245. }
  28246. get widthMultiplier() {
  28247. return this._widthMultiplier;
  28248. }
  28249. set widthMultiplier(value) {
  28250. this._widthMultiplier = value;
  28251. }
  28252. get widthCurve() {
  28253. return this._widthCurve;
  28254. }
  28255. set widthCurve(value) {
  28256. this._widthCurve = value;
  28257. var widthCurveFloatArray = new Float32Array(value.length * 4);
  28258. var i, j, index = 0;
  28259. for (i = 0, j = value.length; i < j; i++) {
  28260. widthCurveFloatArray[index++] = value[i].time;
  28261. widthCurveFloatArray[index++] = value[i].inTangent;
  28262. widthCurveFloatArray[index++] = value[i].outTangent;
  28263. widthCurveFloatArray[index++] = value[i].value;
  28264. }
  28265. this._owner._render._shaderValues.setBuffer(TrailFilter.WIDTHCURVE, widthCurveFloatArray);
  28266. this._owner._render._shaderValues.setInt(TrailFilter.WIDTHCURVEKEYLENGTH, value.length);
  28267. }
  28268. get colorGradient() {
  28269. return this._colorGradient;
  28270. }
  28271. set colorGradient(value) {
  28272. this._colorGradient = value;
  28273. }
  28274. get textureMode() {
  28275. return this._textureMode;
  28276. }
  28277. set textureMode(value) {
  28278. this._textureMode = value;
  28279. }
  28280. addRenderElement() {
  28281. var render = this._owner._render;
  28282. var elements = render._renderElements;
  28283. var material = render.sharedMaterials[0];
  28284. (material) || (material = TrailMaterial.defaultMaterial);
  28285. var element = new RenderElement();
  28286. element.setTransform(this._owner._transform);
  28287. element.render = render;
  28288. element.material = material;
  28289. this._trialGeometry = new TrailGeometry(this);
  28290. element.setGeometry(this._trialGeometry);
  28291. elements.push(element);
  28292. }
  28293. _update(state) {
  28294. var render = this._owner._render;
  28295. this._curtime += state.scene.timer._delta / 1000;
  28296. render._shaderValues.setNumber(TrailFilter.CURTIME, this._curtime);
  28297. var curPos = this._owner.transform.position;
  28298. var element = render._renderElements[0]._geometry;
  28299. element._updateDisappear();
  28300. element._updateTrail(state.camera, this._lastPosition, curPos);
  28301. element._updateVertexBufferUV();
  28302. curPos.cloneTo(this._lastPosition);
  28303. }
  28304. _initDefaultData() {
  28305. this.time = 5.0;
  28306. this.minVertexDistance = 0.1;
  28307. this.widthMultiplier = 1;
  28308. this.textureMode = TextureMode.Stretch;
  28309. var widthKeyFrames = [];
  28310. var widthKeyFrame1 = new FloatKeyframe();
  28311. widthKeyFrame1.time = 0;
  28312. widthKeyFrame1.inTangent = 0;
  28313. widthKeyFrame1.outTangent = 0;
  28314. widthKeyFrame1.value = 1;
  28315. widthKeyFrames.push(widthKeyFrame1);
  28316. var widthKeyFrame2 = new FloatKeyframe();
  28317. widthKeyFrame2.time = 1;
  28318. widthKeyFrame2.inTangent = 0;
  28319. widthKeyFrame2.outTangent = 0;
  28320. widthKeyFrame2.value = 1;
  28321. widthKeyFrames.push(widthKeyFrame2);
  28322. this.widthCurve = widthKeyFrames;
  28323. var gradient = new Gradient(2, 2);
  28324. gradient.mode = GradientMode.Blend;
  28325. gradient.addColorRGB(0, Color.WHITE);
  28326. gradient.addColorRGB(1, Color.WHITE);
  28327. gradient.addColorAlpha(0, 1);
  28328. gradient.addColorAlpha(1, 1);
  28329. this.colorGradient = gradient;
  28330. }
  28331. destroy() {
  28332. this._trialGeometry.destroy();
  28333. this._trialGeometry = null;
  28334. this._widthCurve = null;
  28335. this._colorGradient = null;
  28336. }
  28337. clear() {
  28338. this._trialGeometry.clear();
  28339. this._lastPosition.setValue(0, 0, 0);
  28340. this._curtime = 0;
  28341. this._totalLength = 0;
  28342. }
  28343. }
  28344. TrailFilter.CURTIME = Shader3D.propertyNameToID("u_CurTime");
  28345. TrailFilter.LIFETIME = Shader3D.propertyNameToID("u_LifeTime");
  28346. TrailFilter.WIDTHCURVE = Shader3D.propertyNameToID("u_WidthCurve");
  28347. TrailFilter.WIDTHCURVEKEYLENGTH = Shader3D.propertyNameToID("u_WidthCurveKeyLength");
  28348. TrailFilter.ALIGNMENT_VIEW = 0;
  28349. TrailFilter.ALIGNMENT_TRANSFORM_Z = 1;
  28350. class TrailRenderer extends BaseRender {
  28351. constructor(owner) {
  28352. super(owner);
  28353. this._projectionViewWorldMatrix = new Matrix4x4();
  28354. }
  28355. _calculateBoundingBox() {
  28356. }
  28357. _needRender(boundFrustum, context) {
  28358. this._owner.trailFilter._update(context);
  28359. if (boundFrustum)
  28360. return boundFrustum.intersects(this.bounds._getBoundBox());
  28361. else
  28362. return true;
  28363. }
  28364. _updateForNative(context) {
  28365. this._owner.trailFilter._update(context);
  28366. }
  28367. _renderUpdate(state, transform) {
  28368. super._renderUpdate(state, transform);
  28369. }
  28370. _renderUpdateWithCamera(context, transform) {
  28371. var projectionView = context.projectionViewMatrix;
  28372. if (transform) {
  28373. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  28374. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  28375. }
  28376. else {
  28377. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  28378. }
  28379. }
  28380. }
  28381. class TrailSprite3D extends RenderableSprite3D {
  28382. constructor(name = null) {
  28383. super(name);
  28384. this._render = new TrailRenderer(this);
  28385. this._geometryFilter = new TrailFilter(this);
  28386. }
  28387. static __init__() {
  28388. }
  28389. get trailFilter() {
  28390. return this._geometryFilter;
  28391. }
  28392. get trailRenderer() {
  28393. return this._render;
  28394. }
  28395. _parse(data, spriteMap) {
  28396. super._parse(data, spriteMap);
  28397. var render = this._render;
  28398. var filter = this._geometryFilter;
  28399. var i, j;
  28400. var materials = data.materials;
  28401. if (materials) {
  28402. var sharedMaterials = render.sharedMaterials;
  28403. var materialCount = materials.length;
  28404. sharedMaterials.length = materialCount;
  28405. for (i = 0; i < materialCount; i++)
  28406. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  28407. render.sharedMaterials = sharedMaterials;
  28408. }
  28409. filter.time = data.time;
  28410. filter.minVertexDistance = data.minVertexDistance;
  28411. filter.widthMultiplier = data.widthMultiplier;
  28412. filter.textureMode = data.textureMode;
  28413. (data.alignment != null) && (filter.alignment = data.alignment);
  28414. var widthCurve = [];
  28415. var widthCurveData = data.widthCurve;
  28416. for (i = 0, j = widthCurveData.length; i < j; i++) {
  28417. var trailkeyframe = new FloatKeyframe();
  28418. trailkeyframe.time = widthCurveData[i].time;
  28419. trailkeyframe.inTangent = widthCurveData[i].inTangent;
  28420. trailkeyframe.outTangent = widthCurveData[i].outTangent;
  28421. trailkeyframe.value = widthCurveData[i].value;
  28422. widthCurve.push(trailkeyframe);
  28423. }
  28424. filter.widthCurve = widthCurve;
  28425. var colorGradientData = data.colorGradient;
  28426. var colorKeys = colorGradientData.colorKeys;
  28427. var alphaKeys = colorGradientData.alphaKeys;
  28428. var colorGradient = new Gradient(colorKeys.length, alphaKeys.length);
  28429. colorGradient.mode = colorGradientData.mode;
  28430. for (i = 0, j = colorKeys.length; i < j; i++) {
  28431. var colorKey = colorKeys[i];
  28432. colorGradient.addColorRGB(colorKey.time, new Color(colorKey.value[0], colorKey.value[1], colorKey.value[2], 1.0));
  28433. }
  28434. for (i = 0, j = alphaKeys.length; i < j; i++) {
  28435. var alphaKey = alphaKeys[i];
  28436. colorGradient.addColorAlpha(alphaKey.time, alphaKey.value);
  28437. }
  28438. filter.colorGradient = colorGradient;
  28439. }
  28440. _onActive() {
  28441. super._onActive();
  28442. this._transform.position.cloneTo(this._geometryFilter._lastPosition);
  28443. }
  28444. _cloneTo(destObject, srcSprite, dstSprite) {
  28445. super._cloneTo(destObject, srcSprite, dstSprite);
  28446. var i, j;
  28447. var destTrailSprite3D = destObject;
  28448. var destTrailFilter = destTrailSprite3D.trailFilter;
  28449. destTrailFilter.time = this.trailFilter.time;
  28450. destTrailFilter.minVertexDistance = this.trailFilter.minVertexDistance;
  28451. destTrailFilter.widthMultiplier = this.trailFilter.widthMultiplier;
  28452. destTrailFilter.textureMode = this.trailFilter.textureMode;
  28453. destTrailFilter.alignment = this.trailFilter.alignment;
  28454. var widthCurveData = this.trailFilter.widthCurve;
  28455. var widthCurve = [];
  28456. for (i = 0, j = widthCurveData.length; i < j; i++) {
  28457. var keyFrame = new FloatKeyframe();
  28458. widthCurveData[i].cloneTo(keyFrame);
  28459. widthCurve.push(keyFrame);
  28460. }
  28461. destTrailFilter.widthCurve = widthCurve;
  28462. var destColorGradient = new Gradient(this.trailFilter.colorGradient.maxColorRGBKeysCount, this.trailFilter.colorGradient.maxColorAlphaKeysCount);
  28463. this.trailFilter.colorGradient.cloneTo(destColorGradient);
  28464. destTrailFilter.colorGradient = destColorGradient;
  28465. var destTrailRender = destTrailSprite3D.trailRenderer;
  28466. destTrailRender.sharedMaterial = this.trailRenderer.sharedMaterial;
  28467. }
  28468. destroy(destroyChild = true) {
  28469. if (this.destroyed)
  28470. return;
  28471. super.destroy(destroyChild);
  28472. this._geometryFilter.destroy();
  28473. this._geometryFilter = null;
  28474. }
  28475. clear() {
  28476. this._geometryFilter.clear();
  28477. }
  28478. _create() {
  28479. return new TrailSprite3D();
  28480. }
  28481. }
  28482. class VertexPositionTerrain {
  28483. constructor(position, normal, textureCoord0, textureCoord1) {
  28484. this._position = position;
  28485. this._normal = normal;
  28486. this._textureCoord0 = textureCoord0;
  28487. this._textureCoord1 = textureCoord1;
  28488. }
  28489. static __init__() {
  28490. VertexPositionTerrain._vertexDeclaration = new VertexDeclaration(40, [new VertexElement(0, VertexElementFormat.Vector3, VertexPositionTerrain.TERRAIN_POSITION0),
  28491. new VertexElement(12, VertexElementFormat.Vector3, VertexPositionTerrain.TERRAIN_NORMAL0),
  28492. new VertexElement(24, VertexElementFormat.Vector2, VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE0),
  28493. new VertexElement(32, VertexElementFormat.Vector2, VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE1)]);
  28494. }
  28495. static get vertexDeclaration() {
  28496. return VertexPositionTerrain._vertexDeclaration;
  28497. }
  28498. get position() {
  28499. return this._position;
  28500. }
  28501. get normal() {
  28502. return this._normal;
  28503. }
  28504. get textureCoord0() {
  28505. return this._textureCoord0;
  28506. }
  28507. get textureCoord1() {
  28508. return this._textureCoord1;
  28509. }
  28510. get vertexDeclaration() {
  28511. return VertexPositionTerrain._vertexDeclaration;
  28512. }
  28513. }
  28514. VertexPositionTerrain.TERRAIN_POSITION0 = 0;
  28515. VertexPositionTerrain.TERRAIN_NORMAL0 = 1;
  28516. VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE0 = 2;
  28517. VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE1 = 3;
  28518. class BulletInteractive {
  28519. }
  28520. BulletInteractive._interactive = {
  28521. "getWorldTransform": (rigidBodyID, worldTransPointer) => {
  28522. },
  28523. "setWorldTransform": (rigidBodyID, worldTransPointer) => {
  28524. var rigidBody = PhysicsComponent._physicObjectsMap[rigidBodyID];
  28525. rigidBody._simulation._updatedRigidbodies++;
  28526. rigidBody._updateTransformComponent(worldTransPointer);
  28527. }
  28528. };
  28529. class PhysicsCollider extends PhysicsTriggerComponent {
  28530. constructor(collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  28531. super(collisionGroup, canCollideWith);
  28532. this._enableProcessCollisions = false;
  28533. }
  28534. _addToSimulation() {
  28535. this._simulation._addPhysicsCollider(this, this._collisionGroup, this._canCollideWith);
  28536. }
  28537. _removeFromSimulation() {
  28538. this._simulation._removePhysicsCollider(this);
  28539. }
  28540. _parse(data) {
  28541. (data.friction != null) && (this.friction = data.friction);
  28542. (data.rollingFriction != null) && (this.rollingFriction = data.rollingFriction);
  28543. (data.restitution != null) && (this.restitution = data.restitution);
  28544. (data.isTrigger != null) && (this.isTrigger = data.isTrigger);
  28545. super._parse(data);
  28546. this._parseShape(data.shapes);
  28547. }
  28548. _onAdded() {
  28549. var bt = Physics3D._bullet;
  28550. var btColObj = bt.btCollisionObject_create();
  28551. bt.btCollisionObject_setUserIndex(btColObj, this.id);
  28552. bt.btCollisionObject_forceActivationState(btColObj, PhysicsComponent.ACTIVATIONSTATE_DISABLE_SIMULATION);
  28553. var flags = bt.btCollisionObject_getCollisionFlags(btColObj);
  28554. if (this.owner.isStatic) {
  28555. if ((flags & PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT) > 0)
  28556. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  28557. flags = flags | PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT;
  28558. }
  28559. else {
  28560. if ((flags & PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT) > 0)
  28561. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT;
  28562. flags = flags | PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  28563. }
  28564. bt.btCollisionObject_setCollisionFlags(btColObj, flags);
  28565. this._btColliderObject = btColObj;
  28566. super._onAdded();
  28567. }
  28568. }
  28569. class SubMesh extends GeometryElement {
  28570. constructor(mesh) {
  28571. super();
  28572. this._id = ++SubMesh._uniqueIDCounter;
  28573. this._mesh = mesh;
  28574. this._boneIndicesList = [];
  28575. this._subIndexBufferStart = [];
  28576. this._subIndexBufferCount = [];
  28577. }
  28578. get indexCount() {
  28579. return this._indexCount;
  28580. }
  28581. _setIndexRange(indexStart, indexCount) {
  28582. this._indexStart = indexStart;
  28583. this._indexCount = indexCount;
  28584. this._indices = new Uint16Array(this._indexBuffer.getData().buffer, indexStart * 2, indexCount);
  28585. }
  28586. _getType() {
  28587. return SubMesh._type;
  28588. }
  28589. _prepareRender(state) {
  28590. this._mesh._uploadVerticesData();
  28591. return true;
  28592. }
  28593. _render(state) {
  28594. var mesh = this._mesh;
  28595. if (mesh.indexFormat === exports.IndexFormat.UInt32 && !Laya.LayaGL.layaGPUInstance.supportElementIndexUint32()) {
  28596. console.warn("SubMesh:this device do not support IndexFormat.UInt32.");
  28597. return;
  28598. }
  28599. var gl = Laya.LayaGL.instance;
  28600. var skinnedDatas = state.renderElement.render._skinnedData;
  28601. var glIndexFormat;
  28602. var byteCount;
  28603. switch (mesh.indexFormat) {
  28604. case exports.IndexFormat.UInt32:
  28605. glIndexFormat = gl.UNSIGNED_INT;
  28606. byteCount = 4;
  28607. break;
  28608. case exports.IndexFormat.UInt16:
  28609. glIndexFormat = gl.UNSIGNED_SHORT;
  28610. byteCount = 2;
  28611. break;
  28612. case exports.IndexFormat.UInt8:
  28613. glIndexFormat = gl.UNSIGNED_BYTE;
  28614. byteCount = 1;
  28615. break;
  28616. }
  28617. mesh._bufferState.bind();
  28618. if (skinnedDatas) {
  28619. var subSkinnedDatas = skinnedDatas[this._indexInMesh];
  28620. for (var i = 0, n = this._boneIndicesList.length; i < n; i++) {
  28621. state.shader.uploadCustomUniform(SkinnedMeshSprite3D.BONES, subSkinnedDatas[i]);
  28622. gl.drawElements(gl.TRIANGLES, this._subIndexBufferCount[i], glIndexFormat, this._subIndexBufferStart[i] * byteCount);
  28623. }
  28624. }
  28625. else {
  28626. gl.drawElements(gl.TRIANGLES, this._indexCount, glIndexFormat, this._indexStart * byteCount);
  28627. }
  28628. Laya.Stat.trianglesFaces += this._indexCount / 3;
  28629. Laya.Stat.renderBatches++;
  28630. }
  28631. getIndices() {
  28632. if (this._mesh._isReadable)
  28633. return this._indices.slice();
  28634. else
  28635. throw "SubMesh:can't get indices on subMesh,mesh's isReadable must be true.";
  28636. }
  28637. setIndices(indices) {
  28638. this._indexBuffer.setData(indices, this._indexStart, 0, this._indexCount);
  28639. }
  28640. destroy() {
  28641. if (this._destroyed)
  28642. return;
  28643. super.destroy();
  28644. this._indexBuffer.destroy();
  28645. this._indexBuffer = null;
  28646. this._mesh = null;
  28647. this._boneIndicesList = null;
  28648. this._subIndexBufferStart = null;
  28649. this._subIndexBufferCount = null;
  28650. this._skinAnimationDatas = null;
  28651. }
  28652. }
  28653. SubMesh._uniqueIDCounter = 0;
  28654. SubMesh._type = GeometryElement._typeCounter++;
  28655. class skinnedMatrixCache {
  28656. constructor(subMeshIndex, batchIndex, batchBoneIndex) {
  28657. this.subMeshIndex = subMeshIndex;
  28658. this.batchIndex = batchIndex;
  28659. this.batchBoneIndex = batchBoneIndex;
  28660. }
  28661. }
  28662. class Mesh extends Laya.Resource {
  28663. constructor(isReadable = true) {
  28664. super();
  28665. this._tempVector30 = new Vector3();
  28666. this._tempVector31 = new Vector3();
  28667. this._tempVector32 = new Vector3();
  28668. this._minVerticesUpdate = -1;
  28669. this._maxVerticesUpdate = -1;
  28670. this._needUpdateBounds = true;
  28671. this._bounds = new Bounds(new Vector3(), new Vector3());
  28672. this._bufferState = new BufferState();
  28673. this._instanceBufferState = new BufferState();
  28674. this._vertexBuffer = null;
  28675. this._indexBuffer = null;
  28676. this._skinnedMatrixCaches = [];
  28677. this._vertexCount = 0;
  28678. this._indexFormat = exports.IndexFormat.UInt16;
  28679. this._isReadable = isReadable;
  28680. this._subMeshes = [];
  28681. }
  28682. static __init__() {
  28683. var physics3D = Physics3D._bullet;
  28684. if (physics3D) {
  28685. Mesh._nativeTempVector30 = physics3D.btVector3_create(0, 0, 0);
  28686. Mesh._nativeTempVector31 = physics3D.btVector3_create(0, 0, 0);
  28687. Mesh._nativeTempVector32 = physics3D.btVector3_create(0, 0, 0);
  28688. }
  28689. }
  28690. static load(url, complete) {
  28691. Laya.ILaya.loader.create(url, complete, null, Mesh.MESH);
  28692. }
  28693. get inverseAbsoluteBindPoses() {
  28694. return this._inverseBindPoses;
  28695. }
  28696. get vertexCount() {
  28697. return this._vertexCount;
  28698. }
  28699. get indexCount() {
  28700. return this._indexBuffer.indexCount;
  28701. }
  28702. get subMeshCount() {
  28703. return this._subMeshes.length;
  28704. }
  28705. get bounds() {
  28706. return this._bounds;
  28707. }
  28708. set bounds(value) {
  28709. if (this._bounds !== value)
  28710. value.cloneTo(this._bounds);
  28711. }
  28712. get indexFormat() {
  28713. return this._indexFormat;
  28714. }
  28715. _getPositionElement(vertexBuffer) {
  28716. var vertexElements = vertexBuffer.vertexDeclaration._vertexElements;
  28717. for (var i = 0, n = vertexElements.length; i < n; i++) {
  28718. var vertexElement = vertexElements[i];
  28719. if (vertexElement._elementFormat === VertexElementFormat.Vector3 && vertexElement._elementUsage === VertexMesh.MESH_POSITION0)
  28720. return vertexElement;
  28721. }
  28722. return null;
  28723. }
  28724. _getVerticeElementData(data, elementUsage) {
  28725. data.length = this._vertexCount;
  28726. var verDec = this._vertexBuffer.vertexDeclaration;
  28727. var element = verDec.getVertexElementByUsage(elementUsage);
  28728. if (element) {
  28729. var uint8Vertices = this._vertexBuffer.getUint8Data();
  28730. var floatVertices = this._vertexBuffer.getFloat32Data();
  28731. var uint8VerStr = verDec.vertexStride;
  28732. var floatVerStr = uint8VerStr / 4;
  28733. var uint8EleOffset = element._offset;
  28734. var floatEleOffset = uint8EleOffset / 4;
  28735. switch (elementUsage) {
  28736. case VertexMesh.MESH_TEXTURECOORDINATE0:
  28737. case VertexMesh.MESH_TEXTURECOORDINATE1:
  28738. for (var i = 0; i < this._vertexCount; i++) {
  28739. var offset = floatVerStr * i + floatEleOffset;
  28740. data[i] = new Vector2(floatVertices[offset], floatVertices[offset + 1]);
  28741. }
  28742. break;
  28743. case VertexMesh.MESH_POSITION0:
  28744. case VertexMesh.MESH_NORMAL0:
  28745. for (var i = 0; i < this._vertexCount; i++) {
  28746. var offset = floatVerStr * i + floatEleOffset;
  28747. data[i] = new Vector3(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2]);
  28748. }
  28749. break;
  28750. case VertexMesh.MESH_TANGENT0:
  28751. case VertexMesh.MESH_BLENDWEIGHT0:
  28752. for (var i = 0; i < this._vertexCount; i++) {
  28753. var offset = floatVerStr * i + floatEleOffset;
  28754. data[i] = new Vector4(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2], floatVertices[offset + 3]);
  28755. }
  28756. break;
  28757. case VertexMesh.MESH_COLOR0:
  28758. for (var i = 0; i < this._vertexCount; i++) {
  28759. var offset = floatVerStr * i + floatEleOffset;
  28760. data[i] = new Color(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2], floatVertices[offset + 3]);
  28761. }
  28762. break;
  28763. case VertexMesh.MESH_BLENDINDICES0:
  28764. for (var i = 0; i < this._vertexCount; i++) {
  28765. var offset = uint8VerStr * i + uint8EleOffset;
  28766. data[i] = new Vector4(uint8Vertices[offset], uint8Vertices[offset + 1], uint8Vertices[offset + 2], uint8Vertices[offset + 3]);
  28767. }
  28768. break;
  28769. default:
  28770. throw "Mesh:Unknown elementUsage.";
  28771. }
  28772. }
  28773. }
  28774. _setVerticeElementData(data, elementUsage) {
  28775. var verDec = this._vertexBuffer.vertexDeclaration;
  28776. var element = verDec.getVertexElementByUsage(elementUsage);
  28777. if (element) {
  28778. var uint8Vertices = this._vertexBuffer.getUint8Data();
  28779. var floatVertices = this._vertexBuffer.getFloat32Data();
  28780. var uint8VerStr = verDec.vertexStride;
  28781. var float8VerStr = uint8VerStr / 4;
  28782. var uint8EleOffset = element._offset;
  28783. var floatEleOffset = uint8EleOffset / 4;
  28784. switch (elementUsage) {
  28785. case VertexMesh.MESH_TEXTURECOORDINATE0:
  28786. case VertexMesh.MESH_TEXTURECOORDINATE1:
  28787. for (var i = 0, n = data.length; i < n; i++) {
  28788. var offset = float8VerStr * i + floatEleOffset;
  28789. var vec2 = data[i];
  28790. floatVertices[offset] = vec2.x;
  28791. floatVertices[offset + 1] = vec2.y;
  28792. }
  28793. break;
  28794. case VertexMesh.MESH_POSITION0:
  28795. case VertexMesh.MESH_NORMAL0:
  28796. for (var i = 0, n = data.length; i < n; i++) {
  28797. var offset = float8VerStr * i + floatEleOffset;
  28798. var vec3 = data[i];
  28799. floatVertices[offset] = vec3.x;
  28800. floatVertices[offset + 1] = vec3.y;
  28801. floatVertices[offset + 2] = vec3.z;
  28802. }
  28803. break;
  28804. case VertexMesh.MESH_TANGENT0:
  28805. case VertexMesh.MESH_BLENDWEIGHT0:
  28806. for (var i = 0, n = data.length; i < n; i++) {
  28807. var offset = float8VerStr * i + floatEleOffset;
  28808. var vec4 = data[i];
  28809. floatVertices[offset] = vec4.x;
  28810. floatVertices[offset + 1] = vec4.y;
  28811. floatVertices[offset + 2] = vec4.z;
  28812. floatVertices[offset + 3] = vec4.w;
  28813. }
  28814. break;
  28815. case VertexMesh.MESH_COLOR0:
  28816. for (var i = 0, n = data.length; i < n; i++) {
  28817. var offset = float8VerStr * i + floatEleOffset;
  28818. var cor = data[i];
  28819. floatVertices[offset] = cor.r;
  28820. floatVertices[offset + 1] = cor.g;
  28821. floatVertices[offset + 2] = cor.b;
  28822. floatVertices[offset + 3] = cor.a;
  28823. }
  28824. break;
  28825. case VertexMesh.MESH_BLENDINDICES0:
  28826. for (var i = 0, n = data.length; i < n; i++) {
  28827. var offset = uint8VerStr * i + uint8EleOffset;
  28828. var vec4 = data[i];
  28829. uint8Vertices[offset] = vec4.x;
  28830. uint8Vertices[offset + 1] = vec4.y;
  28831. uint8Vertices[offset + 2] = vec4.z;
  28832. uint8Vertices[offset + 3] = vec4.w;
  28833. }
  28834. break;
  28835. default:
  28836. throw "Mesh:Unknown elementUsage.";
  28837. }
  28838. this._minVerticesUpdate = 0;
  28839. this._maxVerticesUpdate = Number.MAX_SAFE_INTEGER;
  28840. }
  28841. else {
  28842. console.warn("Mesh: the mesh don't have this VertexElement.");
  28843. }
  28844. }
  28845. _disposeResource() {
  28846. for (var i = 0, n = this._subMeshes.length; i < n; i++)
  28847. this._subMeshes[i].destroy();
  28848. this._btTriangleMesh && Physics3D._bullet.btStridingMeshInterface_destroy(this._btTriangleMesh);
  28849. this._vertexBuffer.destroy();
  28850. this._indexBuffer.destroy();
  28851. this._bufferState.destroy();
  28852. this._instanceBufferState.destroy();
  28853. this._setCPUMemory(0);
  28854. this._setGPUMemory(0);
  28855. this._bufferState = null;
  28856. this._instanceBufferState = null;
  28857. this._vertexBuffer = null;
  28858. this._indexBuffer = null;
  28859. this._subMeshes = null;
  28860. this._btTriangleMesh = null;
  28861. this._indexBuffer = null;
  28862. this._boneNames = null;
  28863. this._inverseBindPoses = null;
  28864. }
  28865. _setSubMeshes(subMeshes) {
  28866. this._subMeshes = subMeshes;
  28867. for (var i = 0, n = subMeshes.length; i < n; i++)
  28868. subMeshes[i]._indexInMesh = i;
  28869. }
  28870. _setBuffer(vertexBuffer, indexBuffer) {
  28871. var bufferState = this._bufferState;
  28872. bufferState.bind();
  28873. bufferState.applyVertexBuffer(vertexBuffer);
  28874. bufferState.applyIndexBuffer(indexBuffer);
  28875. bufferState.unBind();
  28876. var instanceBufferState = this._instanceBufferState;
  28877. instanceBufferState.bind();
  28878. instanceBufferState.applyVertexBuffer(vertexBuffer);
  28879. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer);
  28880. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer);
  28881. instanceBufferState.applyIndexBuffer(indexBuffer);
  28882. instanceBufferState.unBind();
  28883. }
  28884. _getPhysicMesh() {
  28885. if (!this._btTriangleMesh) {
  28886. var bt = Physics3D._bullet;
  28887. var triangleMesh = bt.btTriangleMesh_create();
  28888. var nativePositio0 = Mesh._nativeTempVector30;
  28889. var nativePositio1 = Mesh._nativeTempVector31;
  28890. var nativePositio2 = Mesh._nativeTempVector32;
  28891. var position0 = this._tempVector30;
  28892. var position1 = this._tempVector31;
  28893. var position2 = this._tempVector32;
  28894. var vertexBuffer = this._vertexBuffer;
  28895. var positionElement = this._getPositionElement(vertexBuffer);
  28896. var verticesData = vertexBuffer.getFloat32Data();
  28897. var floatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  28898. var posOffset = positionElement._offset / 4;
  28899. var indices = this._indexBuffer.getData();
  28900. for (var i = 0, n = indices.length; i < n; i += 3) {
  28901. var p0Index = indices[i] * floatCount + posOffset;
  28902. var p1Index = indices[i + 1] * floatCount + posOffset;
  28903. var p2Index = indices[i + 2] * floatCount + posOffset;
  28904. position0.setValue(verticesData[p0Index], verticesData[p0Index + 1], verticesData[p0Index + 2]);
  28905. position1.setValue(verticesData[p1Index], verticesData[p1Index + 1], verticesData[p1Index + 2]);
  28906. position2.setValue(verticesData[p2Index], verticesData[p2Index + 1], verticesData[p2Index + 2]);
  28907. Utils3D._convertToBulletVec3(position0, nativePositio0, true);
  28908. Utils3D._convertToBulletVec3(position1, nativePositio1, true);
  28909. Utils3D._convertToBulletVec3(position2, nativePositio2, true);
  28910. bt.btTriangleMesh_addTriangle(triangleMesh, nativePositio0, nativePositio1, nativePositio2, true);
  28911. }
  28912. this._btTriangleMesh = triangleMesh;
  28913. }
  28914. return this._btTriangleMesh;
  28915. }
  28916. _uploadVerticesData() {
  28917. var min = this._minVerticesUpdate;
  28918. var max = this._maxVerticesUpdate;
  28919. if (min !== -1 && max !== -1) {
  28920. var offset = min;
  28921. this._vertexBuffer.setData(this._vertexBuffer.getUint8Data().buffer, offset, offset, max - min);
  28922. this._minVerticesUpdate = -1;
  28923. this._maxVerticesUpdate = -1;
  28924. }
  28925. }
  28926. getSubMesh(index) {
  28927. return this._subMeshes[index];
  28928. }
  28929. getPositions(positions) {
  28930. if (this._isReadable)
  28931. this._getVerticeElementData(positions, VertexMesh.MESH_POSITION0);
  28932. else
  28933. throw "Mesh:can't get positions on mesh,isReadable must be true.";
  28934. }
  28935. setPositions(positions) {
  28936. if (this._isReadable) {
  28937. this._setVerticeElementData(positions, VertexMesh.MESH_POSITION0);
  28938. this._needUpdateBounds = true;
  28939. }
  28940. else {
  28941. throw "Mesh:setPosition() need isReadable must be true or use setVertices().";
  28942. }
  28943. }
  28944. getColors(colors) {
  28945. if (this._isReadable)
  28946. this._getVerticeElementData(colors, VertexMesh.MESH_COLOR0);
  28947. else
  28948. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  28949. }
  28950. setColors(colors) {
  28951. if (this._isReadable)
  28952. this._setVerticeElementData(colors, VertexMesh.MESH_COLOR0);
  28953. else
  28954. throw "Mesh:setColors() need isReadable must be true or use setVertices().";
  28955. }
  28956. getUVs(uvs, channel = 0) {
  28957. if (this._isReadable) {
  28958. switch (channel) {
  28959. case 0:
  28960. this._getVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE0);
  28961. break;
  28962. case 1:
  28963. this._getVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE1);
  28964. break;
  28965. default:
  28966. throw "Mesh:Invalid channel.";
  28967. }
  28968. }
  28969. else {
  28970. throw "Mesh:can't get uvs on mesh,isReadable must be true.";
  28971. }
  28972. }
  28973. setUVs(uvs, channel = 0) {
  28974. if (this._isReadable) {
  28975. switch (channel) {
  28976. case 0:
  28977. this._setVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE0);
  28978. break;
  28979. case 1:
  28980. this._setVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE1);
  28981. break;
  28982. default:
  28983. throw "Mesh:Invalid channel.";
  28984. }
  28985. }
  28986. else {
  28987. throw "Mesh:setUVs() need isReadable must be true or use setVertices().";
  28988. }
  28989. }
  28990. getNormals(normals) {
  28991. if (this._isReadable)
  28992. this._getVerticeElementData(normals, VertexMesh.MESH_NORMAL0);
  28993. else
  28994. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  28995. }
  28996. setNormals(normals) {
  28997. if (this._isReadable)
  28998. this._setVerticeElementData(normals, VertexMesh.MESH_NORMAL0);
  28999. else
  29000. throw "Mesh:setNormals() need must be true or use setVertices().";
  29001. }
  29002. getTangents(tangents) {
  29003. if (this._isReadable)
  29004. this._getVerticeElementData(tangents, VertexMesh.MESH_TANGENT0);
  29005. else
  29006. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  29007. }
  29008. setTangents(tangents) {
  29009. if (this._isReadable)
  29010. this._setVerticeElementData(tangents, VertexMesh.MESH_TANGENT0);
  29011. else
  29012. throw "Mesh:setTangents() need isReadable must be true or use setVertices().";
  29013. }
  29014. getBoneWeights(boneWeights) {
  29015. if (this._isReadable)
  29016. this._getVerticeElementData(boneWeights, VertexMesh.MESH_BLENDWEIGHT0);
  29017. else
  29018. throw "Mesh:can't get boneWeights on mesh,isReadable must be true.";
  29019. }
  29020. setBoneWeights(boneWeights) {
  29021. if (this._isReadable)
  29022. this._setVerticeElementData(boneWeights, VertexMesh.MESH_BLENDWEIGHT0);
  29023. else
  29024. throw "Mesh:setBoneWeights() need isReadable must be true or use setVertices().";
  29025. }
  29026. getBoneIndices(boneIndices) {
  29027. if (this._isReadable)
  29028. this._getVerticeElementData(boneIndices, VertexMesh.MESH_BLENDINDICES0);
  29029. else
  29030. throw "Mesh:can't get boneIndices on mesh,isReadable must be true.";
  29031. }
  29032. setBoneIndices(boneIndices) {
  29033. if (this._isReadable)
  29034. this._setVerticeElementData(boneIndices, VertexMesh.MESH_BLENDINDICES0);
  29035. else
  29036. throw "Mesh:setBoneIndices() need isReadable must be true or use setVertices().";
  29037. }
  29038. markAsUnreadbale() {
  29039. this._uploadVerticesData();
  29040. this._vertexBuffer.markAsUnreadbale();
  29041. this._isReadable = false;
  29042. }
  29043. getVertexDeclaration() {
  29044. return this._vertexBuffer._vertexDeclaration;
  29045. }
  29046. getVertices() {
  29047. if (this._isReadable)
  29048. return this._vertexBuffer.getUint8Data().buffer.slice(0);
  29049. else
  29050. throw "Mesh:can't get vertices on mesh,isReadable must be true.";
  29051. }
  29052. setVertices(vertices) {
  29053. this._vertexBuffer.setData(vertices);
  29054. this._needUpdateBounds = true;
  29055. }
  29056. getIndices() {
  29057. if (this._isReadable)
  29058. return this._indexBuffer.getData().slice();
  29059. else
  29060. throw "Mesh:can't get indices on subMesh,mesh's isReadable must be true.";
  29061. }
  29062. setIndices(indices) {
  29063. var format;
  29064. if (indices instanceof Uint32Array)
  29065. format = exports.IndexFormat.UInt32;
  29066. else if (indices instanceof Uint16Array)
  29067. format = exports.IndexFormat.UInt16;
  29068. else if (indices instanceof Uint8Array)
  29069. format = exports.IndexFormat.UInt8;
  29070. var indexBuffer = this._indexBuffer;
  29071. if (this._indexFormat !== format || indexBuffer.indexCount !== indices.length) {
  29072. indexBuffer.destroy();
  29073. this._indexBuffer = indexBuffer = new IndexBuffer3D(format, indices.length, Laya.LayaGL.instance.STATIC_DRAW, this._isReadable);
  29074. }
  29075. indexBuffer.setData(indices);
  29076. this._indexFormat = format;
  29077. }
  29078. calculateBounds() {
  29079. if (this._isReadable) {
  29080. if (this._needUpdateBounds) {
  29081. var min = this._tempVector30;
  29082. var max = this._tempVector31;
  29083. min.x = min.y = min.z = Number.MAX_VALUE;
  29084. max.x = max.y = max.z = -Number.MAX_VALUE;
  29085. var vertexBuffer = this._vertexBuffer;
  29086. var positionElement = this._getPositionElement(vertexBuffer);
  29087. var verticesData = vertexBuffer.getFloat32Data();
  29088. var floatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  29089. var posOffset = positionElement._offset / 4;
  29090. for (var j = 0, m = verticesData.length; j < m; j += floatCount) {
  29091. var ofset = j + posOffset;
  29092. var pX = verticesData[ofset];
  29093. var pY = verticesData[ofset + 1];
  29094. var pZ = verticesData[ofset + 2];
  29095. min.x = Math.min(min.x, pX);
  29096. min.y = Math.min(min.y, pY);
  29097. min.z = Math.min(min.z, pZ);
  29098. max.x = Math.max(max.x, pX);
  29099. max.y = Math.max(max.y, pY);
  29100. max.z = Math.max(max.z, pZ);
  29101. }
  29102. this._bounds.setMin(min);
  29103. this._bounds.setMax(max);
  29104. this._needUpdateBounds = false;
  29105. }
  29106. }
  29107. else {
  29108. throw "Mesh:can't calculate bounds on subMesh,mesh's isReadable must be true.";
  29109. }
  29110. }
  29111. cloneTo(destObject) {
  29112. var destMesh = destObject;
  29113. var vb = this._vertexBuffer;
  29114. var destVB = new VertexBuffer3D(vb._byteLength, vb.bufferUsage, vb.canRead);
  29115. destVB.vertexDeclaration = vb.vertexDeclaration;
  29116. destVB.setData(vb.getUint8Data().slice().buffer);
  29117. destMesh._vertexBuffer = destVB;
  29118. destMesh._vertexCount = this._vertexCount;
  29119. var ib = this._indexBuffer;
  29120. var destIB = new IndexBuffer3D(exports.IndexFormat.UInt16, ib.indexCount, ib.bufferUsage, ib.canRead);
  29121. destIB.setData(ib.getData().slice());
  29122. destMesh._indexBuffer = destIB;
  29123. destMesh._setBuffer(destMesh._vertexBuffer, destIB);
  29124. destMesh._setCPUMemory(this.cpuMemory);
  29125. destMesh._setGPUMemory(this.gpuMemory);
  29126. var i;
  29127. var boneNames = this._boneNames;
  29128. if (boneNames) {
  29129. var destBoneNames = destMesh._boneNames = [];
  29130. for (i = 0; i < boneNames.length; i++)
  29131. destBoneNames[i] = boneNames[i];
  29132. }
  29133. var inverseBindPoses = this._inverseBindPoses;
  29134. if (inverseBindPoses) {
  29135. var destInverseBindPoses = destMesh._inverseBindPoses = [];
  29136. for (i = 0; i < inverseBindPoses.length; i++)
  29137. destInverseBindPoses[i] = inverseBindPoses[i];
  29138. }
  29139. var cacheLength = this._skinnedMatrixCaches.length;
  29140. destMesh._skinnedMatrixCaches.length = cacheLength;
  29141. for (i = 0; i < cacheLength; i++) {
  29142. var skinnedCache = this._skinnedMatrixCaches[i];
  29143. destMesh._skinnedMatrixCaches[i] = new skinnedMatrixCache(skinnedCache.subMeshIndex, skinnedCache.batchIndex, skinnedCache.batchBoneIndex);
  29144. }
  29145. for (i = 0; i < this.subMeshCount; i++) {
  29146. var subMesh = this._subMeshes[i];
  29147. var subIndexBufferStart = subMesh._subIndexBufferStart;
  29148. var subIndexBufferCount = subMesh._subIndexBufferCount;
  29149. var boneIndicesList = subMesh._boneIndicesList;
  29150. var destSubmesh = new SubMesh(destMesh);
  29151. destSubmesh._subIndexBufferStart.length = subIndexBufferStart.length;
  29152. destSubmesh._subIndexBufferCount.length = subIndexBufferCount.length;
  29153. destSubmesh._boneIndicesList.length = boneIndicesList.length;
  29154. for (var j = 0; j < subIndexBufferStart.length; j++)
  29155. destSubmesh._subIndexBufferStart[j] = subIndexBufferStart[j];
  29156. for (j = 0; j < subIndexBufferCount.length; j++)
  29157. destSubmesh._subIndexBufferCount[j] = subIndexBufferCount[j];
  29158. for (j = 0; j < boneIndicesList.length; j++)
  29159. destSubmesh._boneIndicesList[j] = new Uint16Array(boneIndicesList[j]);
  29160. destSubmesh._indexBuffer = destIB;
  29161. destSubmesh._indexStart = subMesh._indexStart;
  29162. destSubmesh._indexCount = subMesh._indexCount;
  29163. destSubmesh._indices = new Uint16Array(destIB.getData().buffer, subMesh._indexStart * 2, subMesh._indexCount);
  29164. var vertexBuffer = destMesh._vertexBuffer;
  29165. destSubmesh._vertexBuffer = vertexBuffer;
  29166. destMesh._subMeshes.push(destSubmesh);
  29167. }
  29168. destMesh._setSubMeshes(destMesh._subMeshes);
  29169. }
  29170. clone() {
  29171. var dest = new Mesh();
  29172. this.cloneTo(dest);
  29173. return dest;
  29174. }
  29175. }
  29176. Mesh.MESH = "MESH";
  29177. class PrimitiveMesh {
  29178. static __init__() {
  29179. }
  29180. static _createMesh(vertexDeclaration, vertices, indices) {
  29181. var gl = Laya.LayaGL.instance;
  29182. var mesh = new Mesh();
  29183. var subMesh = new SubMesh(mesh);
  29184. var vertexBuffer = new VertexBuffer3D(vertices.length * 4, gl.STATIC_DRAW, true);
  29185. vertexBuffer.vertexDeclaration = vertexDeclaration;
  29186. vertexBuffer.setData(vertices.buffer);
  29187. mesh._vertexBuffer = vertexBuffer;
  29188. mesh._vertexCount = vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  29189. var indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indices.length, gl.STATIC_DRAW, true);
  29190. indexBuffer.setData(indices);
  29191. mesh._indexBuffer = indexBuffer;
  29192. mesh._setBuffer(vertexBuffer, indexBuffer);
  29193. subMesh._vertexBuffer = vertexBuffer;
  29194. subMesh._indexBuffer = indexBuffer;
  29195. subMesh._setIndexRange(0, indexBuffer.indexCount);
  29196. var subIndexBufferStart = subMesh._subIndexBufferStart;
  29197. var subIndexBufferCount = subMesh._subIndexBufferCount;
  29198. var boneIndicesList = subMesh._boneIndicesList;
  29199. subIndexBufferStart.length = 1;
  29200. subIndexBufferCount.length = 1;
  29201. boneIndicesList.length = 1;
  29202. subIndexBufferStart[0] = 0;
  29203. subIndexBufferCount[0] = indexBuffer.indexCount;
  29204. var subMeshes = [];
  29205. subMeshes.push(subMesh);
  29206. mesh._setSubMeshes(subMeshes);
  29207. mesh.calculateBounds();
  29208. var memorySize = vertexBuffer._byteLength + indexBuffer._byteLength;
  29209. mesh._setCPUMemory(memorySize);
  29210. mesh._setGPUMemory(memorySize);
  29211. return mesh;
  29212. }
  29213. static createBox(long = 1, height = 1, width = 1) {
  29214. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29215. var halfLong = long / 2;
  29216. var halfHeight = height / 2;
  29217. var halfWidth = width / 2;
  29218. var vertices = new Float32Array([
  29219. -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,
  29220. -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,
  29221. -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,
  29222. 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,
  29223. -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,
  29224. -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
  29225. ]);
  29226. var indices = new Uint16Array([
  29227. 0, 1, 2, 2, 3, 0,
  29228. 4, 7, 6, 6, 5, 4,
  29229. 8, 9, 10, 10, 11, 8,
  29230. 12, 15, 14, 14, 13, 12,
  29231. 16, 17, 18, 18, 19, 16,
  29232. 20, 23, 22, 22, 21, 20
  29233. ]);
  29234. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29235. }
  29236. static createCapsule(radius = 0.5, height = 2, stacks = 16, slices = 32) {
  29237. var vertexCount = (stacks + 1) * (slices + 1) * 2 + (slices + 1) * 2;
  29238. var indexCount = (3 * stacks * (slices + 1)) * 2 * 2 + 2 * slices * 3;
  29239. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29240. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29241. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29242. var indices = new Uint16Array(indexCount);
  29243. var stackAngle = (Math.PI / 2.0) / stacks;
  29244. var sliceAngle = (Math.PI * 2.0) / slices;
  29245. var hcHeight = height / 2 - radius;
  29246. var posX = 0;
  29247. var posY = 0;
  29248. var posZ = 0;
  29249. var vc = 0;
  29250. var ic = 0;
  29251. var verticeCount = 0;
  29252. var stack, slice;
  29253. for (stack = 0; stack <= stacks; stack++) {
  29254. for (slice = 0; slice <= slices; slice++) {
  29255. posX = radius * Math.cos(stack * stackAngle) * Math.cos(slice * sliceAngle + Math.PI);
  29256. posY = radius * Math.sin(stack * stackAngle);
  29257. posZ = radius * Math.cos(stack * stackAngle) * Math.sin(slice * sliceAngle + Math.PI);
  29258. vertices[vc++] = posX;
  29259. vertices[vc++] = posY + hcHeight;
  29260. vertices[vc++] = posZ;
  29261. vertices[vc++] = posX;
  29262. vertices[vc++] = posY;
  29263. vertices[vc++] = posZ;
  29264. vertices[vc++] = 1 - slice / slices;
  29265. vertices[vc++] = (1 - stack / stacks) * ((Math.PI * radius / 2) / (height + Math.PI * radius));
  29266. if (stack < stacks) {
  29267. indices[ic++] = (stack * (slices + 1)) + slice + (slices + 1);
  29268. indices[ic++] = (stack * (slices + 1)) + slice;
  29269. indices[ic++] = (stack * (slices + 1)) + slice + 1;
  29270. indices[ic++] = (stack * (slices + 1)) + slice + (slices);
  29271. indices[ic++] = (stack * (slices + 1)) + slice;
  29272. indices[ic++] = (stack * (slices + 1)) + slice + (slices + 1);
  29273. }
  29274. }
  29275. }
  29276. verticeCount += (stacks + 1) * (slices + 1);
  29277. for (stack = 0; stack <= stacks; stack++) {
  29278. for (slice = 0; slice <= slices; slice++) {
  29279. posX = radius * Math.cos(stack * stackAngle) * Math.cos(slice * sliceAngle + Math.PI);
  29280. posY = radius * Math.sin(-stack * stackAngle);
  29281. posZ = radius * Math.cos(stack * stackAngle) * Math.sin(slice * sliceAngle + Math.PI);
  29282. vertices[vc++] = posX;
  29283. vertices[vc++] = posY - hcHeight;
  29284. vertices[vc++] = posZ;
  29285. vertices[vc++] = posX;
  29286. vertices[vc++] = posY;
  29287. vertices[vc++] = posZ;
  29288. vertices[vc++] = 1 - slice / slices;
  29289. vertices[vc++] = ((stack / stacks) * (Math.PI * radius / 2) + (height + Math.PI * radius / 2)) / (height + Math.PI * radius);
  29290. if (stack < stacks) {
  29291. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice;
  29292. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices + 1);
  29293. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + 1;
  29294. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice;
  29295. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices);
  29296. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices + 1);
  29297. }
  29298. }
  29299. }
  29300. verticeCount += (stacks + 1) * (slices + 1);
  29301. for (slice = 0; slice <= slices; slice++) {
  29302. posX = radius * Math.cos(slice * sliceAngle + Math.PI);
  29303. posY = hcHeight;
  29304. posZ = radius * Math.sin(slice * sliceAngle + Math.PI);
  29305. vertices[vc++] = posX;
  29306. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29307. vertices[vc++] = posY;
  29308. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  29309. vertices[vc++] = posZ;
  29310. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29311. vertices[vc++] = posX;
  29312. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29313. vertices[vc++] = 0;
  29314. vertices[vc + (slices + 1) * 8 - 1] = 0;
  29315. vertices[vc++] = posZ;
  29316. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29317. vertices[vc++] = 1 - slice * 1 / slices;
  29318. vertices[vc + (slices + 1) * 8 - 1] = 1 - slice * 1 / slices;
  29319. vertices[vc++] = (Math.PI * radius / 2) / (height + Math.PI * radius);
  29320. vertices[vc + (slices + 1) * 8 - 1] = (Math.PI * radius / 2 + height) / (height + Math.PI * radius);
  29321. }
  29322. for (slice = 0; slice < slices; slice++) {
  29323. indices[ic++] = slice + verticeCount + (slices + 1);
  29324. indices[ic++] = slice + verticeCount + 1;
  29325. indices[ic++] = slice + verticeCount;
  29326. indices[ic++] = slice + verticeCount + (slices + 1);
  29327. indices[ic++] = slice + verticeCount + (slices + 1) + 1;
  29328. indices[ic++] = slice + verticeCount + 1;
  29329. }
  29330. verticeCount += 2 * (slices + 1);
  29331. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29332. }
  29333. static createCone(radius = 0.5, height = 1, slices = 32) {
  29334. var vertexCount = (slices + 1 + 1) + (slices + 1) * 2;
  29335. var indexCount = 6 * slices + 3 * slices;
  29336. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29337. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29338. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29339. var indices = new Uint16Array(indexCount);
  29340. var sliceAngle = (Math.PI * 2.0) / slices;
  29341. var halfHeight = height / 2;
  29342. var curAngle = 0;
  29343. var verticeCount = 0;
  29344. var posX = 0;
  29345. var posY = 0;
  29346. var posZ = 0;
  29347. var normal = new Vector3();
  29348. var downV3 = new Vector3(0, -1, 0);
  29349. var upPoint = new Vector3(0, halfHeight, 0);
  29350. var downPoint = new Vector3();
  29351. var v3 = new Vector3();
  29352. var q4 = new Quaternion();
  29353. var rotateAxis = new Vector3();
  29354. var rotateRadius;
  29355. var vc = 0;
  29356. var ic = 0;
  29357. for (var rv = 0; rv <= slices; rv++) {
  29358. curAngle = rv * sliceAngle;
  29359. posX = Math.cos(curAngle + Math.PI) * radius;
  29360. posY = halfHeight;
  29361. posZ = Math.sin(curAngle + Math.PI) * radius;
  29362. vertices[vc++] = 0;
  29363. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29364. vertices[vc++] = posY;
  29365. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  29366. vertices[vc++] = 0;
  29367. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29368. normal.x = posX;
  29369. normal.y = 0;
  29370. normal.z = posZ;
  29371. downPoint.x = posX;
  29372. downPoint.y = -posY;
  29373. downPoint.z = posZ;
  29374. Vector3.subtract(downPoint, upPoint, v3);
  29375. Vector3.normalize(v3, v3);
  29376. rotateRadius = Math.acos(Vector3.dot(downV3, v3));
  29377. Vector3.cross(downV3, v3, rotateAxis);
  29378. Vector3.normalize(rotateAxis, rotateAxis);
  29379. Quaternion.createFromAxisAngle(rotateAxis, rotateRadius, q4);
  29380. Vector3.normalize(normal, normal);
  29381. Vector3.transformQuat(normal, q4, normal);
  29382. Vector3.normalize(normal, normal);
  29383. vertices[vc++] = normal.x;
  29384. vertices[vc + (slices + 1) * 8 - 1] = normal.x;
  29385. vertices[vc++] = normal.y;
  29386. vertices[vc + (slices + 1) * 8 - 1] = normal.y;
  29387. vertices[vc++] = normal.z;
  29388. vertices[vc + (slices + 1) * 8 - 1] = normal.z;
  29389. vertices[vc++] = 1 - rv * 1 / slices;
  29390. vertices[vc + (slices + 1) * 8 - 1] = 1 - rv * 1 / slices;
  29391. vertices[vc++] = 0;
  29392. vertices[vc + (slices + 1) * 8 - 1] = 1;
  29393. }
  29394. vc += (slices + 1) * 8;
  29395. for (var ri = 0; ri < slices; ri++) {
  29396. indices[ic++] = ri + verticeCount + (slices + 1);
  29397. indices[ic++] = ri + verticeCount + 1;
  29398. indices[ic++] = ri + verticeCount;
  29399. indices[ic++] = ri + verticeCount + (slices + 1);
  29400. indices[ic++] = ri + verticeCount + (slices + 1) + 1;
  29401. indices[ic++] = ri + verticeCount + 1;
  29402. }
  29403. verticeCount += 2 * (slices + 1);
  29404. for (var bv = 0; bv <= slices; bv++) {
  29405. if (bv === 0) {
  29406. vertices[vc++] = 0;
  29407. vertices[vc++] = -halfHeight;
  29408. vertices[vc++] = 0;
  29409. vertices[vc++] = 0;
  29410. vertices[vc++] = -1;
  29411. vertices[vc++] = 0;
  29412. vertices[vc++] = 0.5;
  29413. vertices[vc++] = 0.5;
  29414. }
  29415. curAngle = bv * sliceAngle;
  29416. posX = Math.cos(curAngle + Math.PI) * radius;
  29417. posY = -halfHeight;
  29418. posZ = Math.sin(curAngle + Math.PI) * radius;
  29419. vertices[vc++] = posX;
  29420. vertices[vc++] = posY;
  29421. vertices[vc++] = posZ;
  29422. vertices[vc++] = 0;
  29423. vertices[vc++] = -1;
  29424. vertices[vc++] = 0;
  29425. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  29426. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  29427. }
  29428. for (var bi = 0; bi < slices; bi++) {
  29429. indices[ic++] = 0 + verticeCount;
  29430. indices[ic++] = bi + 2 + verticeCount;
  29431. indices[ic++] = bi + 1 + verticeCount;
  29432. }
  29433. verticeCount += slices + 1 + 1;
  29434. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29435. }
  29436. static createCylinder(radius = 0.5, height = 2, slices = 32) {
  29437. var vertexCount = (slices + 1 + 1) + (slices + 1) * 2 + (slices + 1 + 1);
  29438. var indexCount = 3 * slices + 6 * slices + 3 * slices;
  29439. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29440. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29441. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29442. var indices = new Uint16Array(indexCount);
  29443. var sliceAngle = (Math.PI * 2.0) / slices;
  29444. var halfHeight = height / 2;
  29445. var curAngle = 0;
  29446. var verticeCount = 0;
  29447. var posX = 0;
  29448. var posY = 0;
  29449. var posZ = 0;
  29450. var vc = 0;
  29451. var ic = 0;
  29452. for (var tv = 0; tv <= slices; tv++) {
  29453. if (tv === 0) {
  29454. vertices[vc++] = 0;
  29455. vertices[vc++] = halfHeight;
  29456. vertices[vc++] = 0;
  29457. vertices[vc++] = 0;
  29458. vertices[vc++] = 1;
  29459. vertices[vc++] = 0;
  29460. vertices[vc++] = 0.5;
  29461. vertices[vc++] = 0.5;
  29462. }
  29463. curAngle = tv * sliceAngle;
  29464. posX = Math.cos(curAngle) * radius;
  29465. posY = halfHeight;
  29466. posZ = Math.sin(curAngle) * radius;
  29467. vertices[vc++] = posX;
  29468. vertices[vc++] = posY;
  29469. vertices[vc++] = posZ;
  29470. vertices[vc++] = 0;
  29471. vertices[vc++] = 1;
  29472. vertices[vc++] = 0;
  29473. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  29474. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  29475. }
  29476. for (var ti = 0; ti < slices; ti++) {
  29477. indices[ic++] = 0;
  29478. indices[ic++] = ti + 1;
  29479. indices[ic++] = ti + 2;
  29480. }
  29481. verticeCount += slices + 1 + 1;
  29482. for (var rv = 0; rv <= slices; rv++) {
  29483. curAngle = rv * sliceAngle;
  29484. posX = Math.cos(curAngle + Math.PI) * radius;
  29485. posY = halfHeight;
  29486. posZ = Math.sin(curAngle + Math.PI) * radius;
  29487. vertices[vc++] = posX;
  29488. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29489. vertices[vc++] = posY;
  29490. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  29491. vertices[vc++] = posZ;
  29492. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29493. vertices[vc++] = posX;
  29494. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29495. vertices[vc++] = 0;
  29496. vertices[vc + (slices + 1) * 8 - 1] = 0;
  29497. vertices[vc++] = posZ;
  29498. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29499. vertices[vc++] = 1 - rv * 1 / slices;
  29500. vertices[vc + (slices + 1) * 8 - 1] = 1 - rv * 1 / slices;
  29501. vertices[vc++] = 0;
  29502. vertices[vc + (slices + 1) * 8 - 1] = 1;
  29503. }
  29504. vc += (slices + 1) * 8;
  29505. for (var ri = 0; ri < slices; ri++) {
  29506. indices[ic++] = ri + verticeCount + (slices + 1);
  29507. indices[ic++] = ri + verticeCount + 1;
  29508. indices[ic++] = ri + verticeCount;
  29509. indices[ic++] = ri + verticeCount + (slices + 1);
  29510. indices[ic++] = ri + verticeCount + (slices + 1) + 1;
  29511. indices[ic++] = ri + verticeCount + 1;
  29512. }
  29513. verticeCount += 2 * (slices + 1);
  29514. for (var bv = 0; bv <= slices; bv++) {
  29515. if (bv === 0) {
  29516. vertices[vc++] = 0;
  29517. vertices[vc++] = -halfHeight;
  29518. vertices[vc++] = 0;
  29519. vertices[vc++] = 0;
  29520. vertices[vc++] = -1;
  29521. vertices[vc++] = 0;
  29522. vertices[vc++] = 0.5;
  29523. vertices[vc++] = 0.5;
  29524. }
  29525. curAngle = bv * sliceAngle;
  29526. posX = Math.cos(curAngle + Math.PI) * radius;
  29527. posY = -halfHeight;
  29528. posZ = Math.sin(curAngle + Math.PI) * radius;
  29529. vertices[vc++] = posX;
  29530. vertices[vc++] = posY;
  29531. vertices[vc++] = posZ;
  29532. vertices[vc++] = 0;
  29533. vertices[vc++] = -1;
  29534. vertices[vc++] = 0;
  29535. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  29536. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  29537. }
  29538. for (var bi = 0; bi < slices; bi++) {
  29539. indices[ic++] = 0 + verticeCount;
  29540. indices[ic++] = bi + 2 + verticeCount;
  29541. indices[ic++] = bi + 1 + verticeCount;
  29542. }
  29543. verticeCount += slices + 1 + 1;
  29544. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29545. }
  29546. static createPlane(long = 10, width = 10, stacks = 10, slices = 10) {
  29547. var vertexCount = (stacks + 1) * (slices + 1);
  29548. var indexCount = stacks * slices * 2 * 3;
  29549. var indices = new Uint16Array(indexCount);
  29550. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29551. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29552. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29553. var halfLong = long / 2;
  29554. var halfWidth = width / 2;
  29555. var stacksLong = long / stacks;
  29556. var slicesWidth = width / slices;
  29557. var verticeCount = 0;
  29558. for (var i = 0; i <= slices; i++) {
  29559. for (var j = 0; j <= stacks; j++) {
  29560. vertices[verticeCount++] = j * stacksLong - halfLong;
  29561. vertices[verticeCount++] = 0;
  29562. vertices[verticeCount++] = i * slicesWidth - halfWidth;
  29563. vertices[verticeCount++] = 0;
  29564. vertices[verticeCount++] = 1;
  29565. vertices[verticeCount++] = 0;
  29566. vertices[verticeCount++] = j * 1 / stacks;
  29567. vertices[verticeCount++] = i * 1 / slices;
  29568. }
  29569. }
  29570. var indiceIndex = 0;
  29571. for (i = 0; i < slices; i++) {
  29572. for (j = 0; j < stacks; j++) {
  29573. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j;
  29574. indices[indiceIndex++] = i * (stacks + 1) + j;
  29575. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j + 1;
  29576. indices[indiceIndex++] = i * (stacks + 1) + j;
  29577. indices[indiceIndex++] = i * (stacks + 1) + j + 1;
  29578. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j + 1;
  29579. }
  29580. }
  29581. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29582. }
  29583. static createQuad(long = 1, width = 1) {
  29584. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29585. var halfLong = long / 2;
  29586. var halfWidth = width / 2;
  29587. 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]);
  29588. var indices = new Uint16Array([0, 1, 2, 3, 2, 1]);
  29589. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29590. }
  29591. static createSphere(radius = 0.5, stacks = 32, slices = 32) {
  29592. var vertexCount = (stacks + 1) * (slices + 1);
  29593. var indexCount = (3 * stacks * (slices + 1)) * 2;
  29594. var indices = new Uint16Array(indexCount);
  29595. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29596. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29597. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29598. var stackAngle = Math.PI / stacks;
  29599. var sliceAngle = (Math.PI * 2.0) / slices;
  29600. var vertexIndex = 0;
  29601. vertexCount = 0;
  29602. indexCount = 0;
  29603. for (var stack = 0; stack < (stacks + 1); stack++) {
  29604. var r = Math.sin(stack * stackAngle);
  29605. var y = Math.cos(stack * stackAngle);
  29606. for (var slice = 0; slice < (slices + 1); slice++) {
  29607. var x = r * Math.sin(slice * sliceAngle + Math.PI * 1 / 2);
  29608. var z = r * Math.cos(slice * sliceAngle + Math.PI * 1 / 2);
  29609. vertices[vertexCount + 0] = x * radius;
  29610. vertices[vertexCount + 1] = y * radius;
  29611. vertices[vertexCount + 2] = z * radius;
  29612. vertices[vertexCount + 3] = x;
  29613. vertices[vertexCount + 4] = y;
  29614. vertices[vertexCount + 5] = z;
  29615. vertices[vertexCount + 6] = slice / slices;
  29616. vertices[vertexCount + 7] = stack / stacks;
  29617. vertexCount += vertexFloatStride;
  29618. if (stack != (stacks - 1)) {
  29619. indices[indexCount++] = vertexIndex + (slices + 1);
  29620. indices[indexCount++] = vertexIndex;
  29621. indices[indexCount++] = vertexIndex + 1;
  29622. indices[indexCount++] = vertexIndex + (slices);
  29623. indices[indexCount++] = vertexIndex;
  29624. indices[indexCount++] = vertexIndex + (slices + 1);
  29625. vertexIndex++;
  29626. }
  29627. }
  29628. }
  29629. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29630. }
  29631. }
  29632. 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";
  29633. 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}";
  29634. 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";
  29635. 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}";
  29636. 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 \"Shadow.glsl\"\r\n#ifdef CALCULATE_SHADOWS\r\n\tvarying vec4 v_ShadowCoord;\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 += decodeHDR(texture2D(u_LightMap, v_LightMapUV),5.0);\r\n#endif\r\n\r\n#ifdef CALCULATE_SHADOWS\r\n\tfloat shadowValue = shadowValue = sampleShadowmap(v_ShadowCoord);\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 CALCULATE_SHADOWS\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";
  29637. 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(CALCULATE_SHADOWS)&&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 CALCULATE_SHADOWS\r\n\tvarying vec4 v_ShadowCoord;\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(CALCULATE_SHADOWS)&&defined(SHADOWMAP_PSSM1))\r\n\t\tv_PositionWorld=(u_WorldMat*a_Position).xyz;\r\n\t#endif\r\n\r\n\t#ifdef CALCULATE_SHADOWS\r\n\t\tv_ShadowCoord = getShadowCoord(vec4(v_PositionWorld));\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  29638. var GlobalIllumination = "struct LayaGIInput\r\n{\r\n\tvec2 lightmapUV;\r\n};\r\n\r\n#define LAYA_SPECCUBE_LOD_STEPS 6.0\r\n\r\nuniform vec3 u_AmbientColor;\r\n\r\n#if defined(GI_AMBIENT_SH)\r\n\tuniform vec4 u_AmbientSHAr;\r\n\tuniform vec4 u_AmbientSHAg;\r\n\tuniform vec4 u_AmbientSHAb;\r\n\tuniform vec4 u_AmbientSHBr;\r\n\tuniform vec4 u_AmbientSHBg;\r\n\tuniform vec4 u_AmbientSHBb;\r\n\tuniform vec4 u_AmbientSHC;\r\n#endif\r\n\r\nuniform samplerCube u_ReflectTexture;\r\nuniform vec4 u_ReflectCubeHDRParams;\r\n\r\n\r\n#ifdef GI_AMBIENT_SH\r\n\tmediump vec3 shEvalLinearL0L1(mediump vec4 normal)\r\n\t{\r\n\t\tmediump vec3 x;\r\n\t\t// Linear (L1) + constant (L0) polynomial terms\r\n\t\tx.r = dot(u_AmbientSHAr, normal);\r\n\t\tx.g = dot(u_AmbientSHAg, normal);\r\n\t\tx.b = dot(u_AmbientSHAb, normal);\r\n\t\treturn x;\r\n\t}\r\n\r\n\tmediump vec3 shEvalLinearL2(mediump vec4 normal)\r\n\t{\r\n\t\tmediump vec3 x1,x2;\r\n\t\t// 4 of the quadratic (L2) polynomials\r\n\t\tmediump vec4 vB = normal.xyzz * normal.yzzx;\r\n\t\tx1.r = dot(u_AmbientSHBr, vB);\r\n\t\tx1.g = dot(u_AmbientSHBg, vB);\r\n\t\tx1.b = dot(u_AmbientSHBb, vB);\r\n\r\n\t\t// Final (5th) quadratic (L2) polynomial\r\n\t\tmediump float vC = normal.x*normal.x - normal.y*normal.y;\r\n\t\tx2 = u_AmbientSHC.rgb * vC;\r\n\r\n\t\treturn x1 + x2;\r\n\t}\r\n\t\r\n\tmediump vec3 shadeSHPerPixel(mediump vec3 normal)\r\n\t{\r\n\t\tmediump vec3 ambientContrib;\r\n\t\tmediump vec4 normalV4=vec4(-normal.x,normal.yz, 1.0);//Note:SH Data is left-hand,so x need inverse\r\n\t\tambientContrib = shEvalLinearL0L1(normalV4);\r\n\t\tambientContrib += shEvalLinearL2(normalV4);\r\n\t\tmediump vec3 ambient = max(vec3(0.0), ambientContrib);\r\n\t\tambient = layaLinearToGammaSpace(ambient);\r\n\t\treturn ambient;\r\n\t}\r\n#endif\r\n\r\nmediump vec3 layaDecodeDirectionalLightmap (mediump vec3 color, lowp vec4 dirTex, mediump vec3 normalWorld)\r\n{\r\n // In directional (non-specular) mode Enlighten bakes dominant light direction\r\n // in a way, that using it for half Lambert and then dividing by a \"rebalancing coefficient\"\r\n // gives a result close to plain diffuse response lightmaps, but normalmapped.\r\n\r\n // Note that dir is not unit length on purpose. Its length is \"directionality\", like\r\n // for the directional specular lightmaps.\r\n\tlowp vec3 directional=dirTex.xyz - 0.5;\r\n\tdirectional.x=-directional.x;//NOTE:because coord System\r\n mediump float halfLambert = dot(normalWorld,directional) + 0.5;\r\n\r\n return color * halfLambert / max(1e-4, dirTex.w);\r\n}\r\n\r\nvec3 layaGIBase(LayaGIInput giInput,mediump float occlusion, mediump vec3 normalWorld)\r\n{\r\n\tvec3 indirectDiffuse;\r\n\t#ifdef LIGHTMAP\t\r\n\t\tmediump vec3 bakedColor =decodeHDR(texture2D(u_LightMap, giInput.lightmapUV),5.0);\r\n\t\t#ifdef LIGHTMAP_DIRECTIONAL\r\n\t\t\tlowp vec4 bakedDirTex = texture2D (u_LightMapDirection, giInput.lightmapUV);\r\n indirectDiffuse = layaDecodeDirectionalLightmap (bakedColor, bakedDirTex, normalWorld);\r\n\t\t#else //unDirectional lightmap\r\n\t\t\tindirectDiffuse = bakedColor;\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef GI_AMBIENT_SH\r\n\t\t\tindirectDiffuse = shadeSHPerPixel(normalWorld);\r\n\t\t#else\r\n\t\t\tindirectDiffuse = u_AmbientColor; //already in gamma space\r\n\t\t#endif\r\n\t#endif\r\n\r\n\tindirectDiffuse*=occlusion;\r\n\treturn indirectDiffuse;\r\n}\r\n\r\nmediump vec3 layaGlossyEnvironment(mediump vec4 glossIn)\r\n{\r\n\tmediump float perceptualRoughness = glossIn.a;\r\n\r\n\t// use approximation to solve,below is more reasonable,but maybe slow. \r\n\t// float m = perceptualRoughnessToRoughness(perceptualRoughness); // m is the real roughness parameter\r\n // const float fEps = 1.192092896e-07F; // smallest such that 1.0+FLT_EPSILON != 1.0 (+1e-4h is NOT good here. is visibly very wrong)\r\n // float n = (2.0/max(fEps, m*m))-2.0; // remap to spec power. See eq. 21 in --> https://dl.dropboxusercontent.com/u/55891920/papers/mm_brdf.pdf\r\n // n /= 4; // remap from n_dot_h formulatino to n_dot_r. See section \"Pre-convolved Cube Maps vs Path Tracers\" --> https://s3.amazonaws.com/docs.knaldtech.com/knald/1.0.0/lys_power_drops.html\r\n // perceptualRoughness = pow( 2/(n+2), 0.25); // remap back to square root of real roughness (0.25 include both the sqrt root of the conversion and sqrt for going from roughness to perceptualRoughness)\r\n\tperceptualRoughness = perceptualRoughness * (1.7 - 0.7*perceptualRoughness);//just a approximation,but fast.\r\n \r\n\tmediump float mip = perceptualRoughness * LAYA_SPECCUBE_LOD_STEPS;\r\n\tmediump vec3 uvw = glossIn.rgb;\r\n\tuvw.x=-uvw.x;//Note:reflectCube is left-hand,so x need inverse\r\n\tmediump vec4 rgbm=textureCubeLodEXT(u_ReflectTexture,uvw,mip);\r\n\treturn decodeHDR(rgbm,u_ReflectCubeHDRParams.x);\r\n}\r\n\r\nmediump vec3 layaGIIndirectSpecular(LayaGIInput giInput,mediump float occlusion, vec4 glossIn)\r\n{\r\n\tmediump vec3 specular = layaGlossyEnvironment(glossIn);\r\n\treturn specular * occlusion;\r\n}\r\n\r\n\r\nLayaGI layaGlobalIllumination(LayaGIInput giInput,mediump float occlusion, mediump vec3 normalWorld,mediump vec4 uvwRoughness)\r\n{\r\n\tLayaGI gi;\r\n\tgi.diffuse = layaGIBase(giInput,occlusion, normalWorld);\r\n\tgi.specular = layaGIIndirectSpecular(giInput,occlusion, uvwRoughness);\r\n\treturn gi;\r\n}\r\n\r\n\r\n";
  29639. var LightingGLSL = "#ifdef GRAPHICS_API_GLES3\r\n\t#define INVERSE_MAT(mat) inverse(mat)\r\n#else\r\n\t#define INVERSE_MAT(mat) inverseMat(mat)\r\n#endif\r\n\r\nstruct 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\nstruct LayaGI{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nstruct LayaLight{\r\n\tvec3 color;\r\n\tvec3 dir;\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\n#ifndef GRAPHICS_API_GLES3\r\n\tmat3 inverseMat(mat3 m) {\r\n\t\tfloat a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\r\n\t\tfloat a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\r\n\t\tfloat a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\r\n\r\n\t\tfloat b01 = a22 * a11 - a12 * a21;\r\n\t\tfloat b11 = -a22 * a10 + a12 * a20;\r\n\t\tfloat b21 = a21 * a10 - a11 * a20;\r\n\r\n\t\tfloat det = a00 * b01 + a01 * b11 + a02 * b21;\r\n\r\n\t\treturn mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\r\n\t\t\t\t\tb11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\r\n\t\t\t\t\tb21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\r\n\t}\r\n#endif\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 //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// 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\tmediump vec3 N = unitNormal;\r\n\tmediump vec3 T = tangent;\r\n\tmediump vec3 B = 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 =normalize(TBN*normalT);\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\nvec3 decodeHDR(vec4 color,float range) {\r\n\treturn color.rgb*color.a*range;\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\nmediump vec3 layaLinearToGammaSpace (mediump vec3 linRGB)\r\n{\r\n linRGB = max(linRGB, vec3(0.0));\r\n // An almost-perfect approximation from http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1\r\n return max(1.055 * pow(linRGB,vec3(0.416666667)) - 0.055, 0.0); \r\n}\r\n\r\nLayaLight layaDirectionLightToLight(in DirectionLight light,in float attenuate)\r\n{\r\n\tLayaLight relight;\r\n\trelight.color = light.color*attenuate;\r\n\trelight.dir = light.direction;\r\n\treturn relight;\r\n}\r\n\r\nLayaLight layaPointLightToLight(in vec3 pos,in vec3 normal, in PointLight light,in float attenuate)\r\n{\r\n\tLayaLight relight;\r\n\tvec3 lightVec = pos-light.position;\r\n\tattenuate *= LayaAttenuation(lightVec, 1.0/light.range);\r\n\trelight.color = light.color*attenuate;\r\n\trelight.dir = normalize(lightVec);\r\n\treturn relight;\r\n}\r\n\r\nLayaLight layaSpotLightToLight(in vec3 pos,in vec3 normal, in SpotLight light,in float attenuate)\r\n{\r\n\tLayaLight relight;\r\n\tvec3 lightVec = pos-light.position;\r\n\tvec3 normalLightVec=lightVec/length(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\tattenuate *= LayaAttenuation(lightVec, 1.0/light.range)*dl;\r\n\trelight.dir = lightVec;\r\n\trelight.color = light.color*attenuate;\r\n\treturn relight;\r\n}\r\n\r\n";
  29640. var ShadowSampleTentGLSL = "// ------------------------------------------------------------------\r\n// PCF Filtering Tent Functions\r\n// ------------------------------------------------------------------\r\n\r\n// Assuming a isoceles right angled triangle of height \"triangleHeight\" (as drawn below).\r\n// This function return the area of the triangle above the first texel(in Y the first texel).\r\n//\r\n// |\\ <-- 45 degree slop isosceles right angled triangle\r\n// | \\\r\n// ---- <-- length of this side is \"triangleHeight\"\r\n// _ _ _ _ <-- texels\r\nfloat sampleShadowGetIRTriangleTexelArea(float triangleHeight)\r\n{\r\n return triangleHeight - 0.5;\r\n}\r\n\r\n// Assuming a isoceles triangle of 1.5 texels height and 3 texels wide lying on 4 texels.\r\n// This function return the area of the triangle above each of those texels.\r\n// | <-- offset from -0.5 to 0.5, 0 meaning triangle is exactly in the center\r\n// / \\ <-- 45 degree slop isosceles triangle (ie tent projected in 2D)\r\n// / \\\r\n// _ _ _ _ <-- texels\r\n// X Y Z W <-- result indices (in computedArea.xyzw and computedAreaUncut.xyzw)\r\n// Top point at (right,top) in a texel,left bottom point at (middle,middle) in a texel,right bottom point at (middle,middle) in a texel.\r\nvoid sampleShadowGetTexelAreasTent3x3(float offset, out vec4 computedArea, out vec4 computedAreaUncut)\r\n{\r\n // Compute the exterior areas,a and h is same.\r\n float a = offset + 0.5;\r\n float offsetSquaredHalved = a * a * 0.5;\r\n computedAreaUncut.x = computedArea.x = offsetSquaredHalved - offset;\r\n computedAreaUncut.w = computedArea.w = offsetSquaredHalved;\r\n\r\n // Compute the middle areas\r\n // For Y : We find the area in Y of as if the left section of the isoceles triangle would\r\n // intersect the axis between Y and Z (ie where offset = 0).\r\n computedAreaUncut.y = sampleShadowGetIRTriangleTexelArea(1.5 - offset);\r\n // This area is superior to the one we are looking for if (offset < 0) thus we need to\r\n // subtract the area of the triangle defined by (0,1.5-offset), (0,1.5+offset), (-offset,1.5).\r\n float clampedOffsetLeft = min(offset,0.0);\r\n float areaOfSmallLeftTriangle = clampedOffsetLeft * clampedOffsetLeft;\r\n computedArea.y = computedAreaUncut.y - areaOfSmallLeftTriangle;\r\n\r\n // We do the same for the Z but with the right part of the isoceles triangle\r\n computedAreaUncut.z = sampleShadowGetIRTriangleTexelArea(1.5 + offset);\r\n float clampedOffsetRight = max(offset,0.0);\r\n float areaOfSmallRightTriangle = clampedOffsetRight * clampedOffsetRight;\r\n computedArea.z = computedAreaUncut.z - areaOfSmallRightTriangle;\r\n}\r\n\r\n// Assuming a isoceles triangle of 2.5 texel height and 5 texels wide lying on 6 texels.\r\n// This function return the weight of each texels area relative to the full triangle area.\r\n// / \\\r\n// _ _ _ _ _ _ <-- texels\r\n// 0 1 2 3 4 5 <-- computed area indices (in texelsWeights[])\r\n// Top point at (right,top) in a texel,left bottom point at (middle,middle) in a texel,right bottom point at (middle,middle) in a texel.\r\nvoid sampleShadowGetTexelWeightsTent5x5(float offset, out vec3 texelsWeightsA, out vec3 texelsWeightsB)\r\n{\r\n vec4 areaFrom3texelTriangle;\r\n vec4 areaUncutFrom3texelTriangle;\r\n sampleShadowGetTexelAreasTent3x3(offset, areaFrom3texelTriangle, areaUncutFrom3texelTriangle);\r\n\r\n // Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation.\r\n // the 5 texel wide triangle can be seen as the 3 texel wide one but shifted up by one unit/texel.\r\n // 0.16 is 1/(the triangle area)\r\n texelsWeightsA.x = 0.16 * (areaFrom3texelTriangle.x);\r\n texelsWeightsA.y = 0.16 * (areaUncutFrom3texelTriangle.y);\r\n texelsWeightsA.z = 0.16 * (areaFrom3texelTriangle.y + 1.0);\r\n texelsWeightsB.x = 0.16 * (areaFrom3texelTriangle.z + 1.0);\r\n texelsWeightsB.y = 0.16 * (areaUncutFrom3texelTriangle.z);\r\n texelsWeightsB.z = 0.16 * (areaFrom3texelTriangle.w);\r\n}\r\n\r\n// 5x5 Tent filter (45 degree sloped triangles in U and V)\r\nvoid sampleShadowComputeSamplesTent5x5(vec4 shadowMapTextureTexelSize, vec2 coord, out float fetchesWeights[9], out vec2 fetchesUV[9])\r\n{\r\n // tent base is 5x5 base thus covering from 25 to 36 texels, thus we need 9 bilinear PCF fetches\r\n vec2 tentCenterInTexelSpace = coord.xy * shadowMapTextureTexelSize.zw;\r\n vec2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);\r\n vec2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;\r\n\r\n // find the weight of each texel based on the area of a 45 degree slop tent above each of them.\r\n vec3 texelsWeightsUA, texelsWeightsUB;\r\n vec3 texelsWeightsVA, texelsWeightsVB;\r\n sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsUA, texelsWeightsUB);\r\n sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsVA, texelsWeightsVB);\r\n\r\n // each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels\r\n vec3 fetchesWeightsU = vec3(texelsWeightsUA.xz, texelsWeightsUB.y) + vec3(texelsWeightsUA.y, texelsWeightsUB.xz);\r\n vec3 fetchesWeightsV = vec3(texelsWeightsVA.xz, texelsWeightsVB.y) + vec3(texelsWeightsVA.y, texelsWeightsVB.xz);\r\n\r\n // move the PCF bilinear fetches to respect texels weights\r\n vec3 fetchesOffsetsU = vec3(texelsWeightsUA.y, texelsWeightsUB.xz) / fetchesWeightsU.xyz + vec3(-2.5,-0.5,1.5);\r\n vec3 fetchesOffsetsV = vec3(texelsWeightsVA.y, texelsWeightsVB.xz) / fetchesWeightsV.xyz + vec3(-2.5,-0.5,1.5);\r\n fetchesOffsetsU *= shadowMapTextureTexelSize.xxx;\r\n fetchesOffsetsV *= shadowMapTextureTexelSize.yyy;\r\n\r\n vec2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTextureTexelSize.xy;\r\n fetchesUV[0] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.x);\r\n fetchesUV[1] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.x);\r\n fetchesUV[2] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.x);\r\n fetchesUV[3] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.y);\r\n fetchesUV[4] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.y);\r\n fetchesUV[5] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.y);\r\n fetchesUV[6] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.z);\r\n fetchesUV[7] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.z);\r\n fetchesUV[8] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.z);\r\n\r\n fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;\r\n fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;\r\n fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x;\r\n fetchesWeights[3] = fetchesWeightsU.x * fetchesWeightsV.y;\r\n fetchesWeights[4] = fetchesWeightsU.y * fetchesWeightsV.y;\r\n fetchesWeights[5] = fetchesWeightsU.z * fetchesWeightsV.y;\r\n fetchesWeights[6] = fetchesWeightsU.x * fetchesWeightsV.z;\r\n fetchesWeights[7] = fetchesWeightsU.y * fetchesWeightsV.z;\r\n fetchesWeights[8] = fetchesWeightsU.z * fetchesWeightsV.z;\r\n}";
  29641. 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";
  29642. 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}";
  29643. 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#include \"Shadow.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\nvarying vec3 v_Normal;\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\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#endif\r\n\r\n#ifdef NORMALMAP \r\n\tuniform sampler2D u_NormalTexture;\r\n\tvarying vec3 v_Tangent;\r\n\tvarying vec3 v_Binormal;\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(POINTLIGHT)||defined(SPOTLIGHT)||(defined(CALCULATE_SHADOWS)&&defined(SHADOW_CASCADE))||defined(CALCULATE_SPOTSHADOWS)\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n\r\n#include \"GlobalIllumination.glsl\";//\"GlobalIllumination.glsl use uniform should at front of this\r\n\r\n#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\n#ifdef CALCULATE_SPOTSHADOWS\r\n\tvarying vec4 v_SpotShadowCoord;\r\n#endif\r\n\r\n\r\nvoid main()\r\n{\r\n\tvec3 normal;//light and SH maybe use normal\r\n\t#if defined(NORMALMAP)\r\n\t\tvec3 normalMapSample = texture2D(u_NormalTexture, v_Texcoord0).rgb;\r\n\t\tnormal = normalize(NormalSampleToWorldSpace(normalMapSample, v_Normal, v_Tangent,v_Binormal));\r\n\t#else\r\n\t\tnormal = normalize(v_Normal);\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tvec3 viewDir= normalize(v_ViewDir);\r\n\t#endif\r\n\r\n\tLayaGIInput giInput;\r\n\t#ifdef LIGHTMAP\t\r\n\t\tgiInput.lightmapUV=v_LightMapUV;\r\n\t#endif\r\n\tvec3 globalDiffuse=layaGIBase(giInput,1.0,normal);\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\r\n\t\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\t#ifdef CALCULATE_SHADOWS\r\n\t\t\t\t#ifdef SHADOW_CASCADE\r\n\t\t\t\t\tvec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t\t\t\t#else\r\n\t\t\t\t\tvec4 shadowCoord = v_ShadowCoord;\r\n\t\t\t\t#endif\r\n\t\t\t\tfloat shadowAttenuation=sampleShadowmap(shadowCoord);\r\n\t\t\t\tdif *= shadowAttenuation;\r\n\t\t\t\tspe *= shadowAttenuation;\r\n\t\t\t#endif\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\t#ifdef CALCULATE_SPOTSHADOWS\r\n\t\t\t\tvec4 spotShadowcoord = v_SpotShadowCoord;\r\n\t\t\t\tfloat spotShadowAttenuation = sampleSpotShadowmap(spotShadowcoord);\r\n\t\t\t\tdif *= shadowAttenuation;\r\n\t\t\t\tspe *= shadowAttenuation;\r\n\t\t\t#endif\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\t#ifdef CALCULATE_SHADOWS\r\n\t\t\t\t\tif(i == 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t#ifdef SHADOW_CASCADE\r\n\t\t\t\t\t\t\tvec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t\t\t\t\t\t#else\r\n\t\t\t\t\t\t\tvec4 shadowCoord = v_ShadowCoord;\r\n\t\t\t\t\t\t#endif\r\n\t\t\t\t\t\tdirectionLight.color *= sampleShadowmap(shadowCoord);\r\n\t\t\t\t\t}\r\n\t\t\t\t#endif\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\t#ifdef CALCULATE_SPOTSHADOWS\r\n\t\t\t\t\t\tif(i == 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tvec4 spotShadowcoord = v_SpotShadowCoord;\r\n\t\t\t\t\t\t\tspotLight.color *= sampleSpotShadowmap(spotShadowcoord);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t#endif\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\tgl_FragColor =vec4(mainColor.rgb*(globalDiffuse + diffuse),mainColor.a);\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tgl_FragColor.rgb+=specular;\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\n";
  29644. var MeshBlinnPhongVS = "#include \"Lighting.glsl\";\r\n#include \"Shadow.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#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\nattribute vec3 a_Normal;\r\nvarying vec3 v_Normal; \r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\tuniform vec3 u_CameraPos;\r\n\tvarying vec3 v_ViewDir; \r\n#endif\r\n\r\n#if 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#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\n\r\n#if defined(POINTLIGHT)||defined(SPOTLIGHT)||(defined(CALCULATE_SHADOWS)&&defined(SHADOW_CASCADE))||defined(CALCULATE_SPOTSHADOWS)\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\n#ifdef CALCULATE_SPOTSHADOWS\r\n\tvarying vec4 v_SpotShadowCoord;\r\n#endif\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\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\tmat4 worldMat;\r\n\t#ifdef GPU_INSTANCE\r\n\t\tworldMat = a_WorldMat;\r\n\t#else\r\n\t\tworldMat = u_WorldMat;\r\n\t#endif\r\n\r\n\tmat3 worldInvMat;\r\n\t#ifdef BONE\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));\r\n\t#else\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat));\r\n\t#endif \r\n\tv_Normal=normalize(a_Normal*worldInvMat);\r\n\t#if defined(NORMALMAP)\r\n\t\tv_Tangent=normalize(a_Tangent0.xyz*worldInvMat);\r\n\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||(defined(CALCULATE_SHADOWS)&&defined(SHADOW_CASCADE))||defined(CALCULATE_SPOTSHADOWS)\r\n\t\tvec3 positionWS=(worldMat*position).xyz;\r\n\t\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tv_ViewDir = u_CameraPos-positionWS;\r\n\t\t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)||(defined(CALCULATE_SHADOWS)&&defined(SHADOW_CASCADE))||defined(CALCULATE_SPOTSHADOWS)\r\n\t\t\tv_PositionWorld = positionWS;\r\n\t\t#endif\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 UV1\r\n\t\t\tv_LightMapUV=vec2(a_Texcoord1.x,1.0-a_Texcoord1.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;\r\n\t\t#else\r\n\t\t\tv_LightMapUV=vec2(a_Texcoord0.x,1.0-a_Texcoord0.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;\r\n\t\t#endif \r\n\t\tv_LightMapUV.y=1.0-v_LightMapUV.y;\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#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\t\tv_ShadowCoord =getShadowCoord(vec4(positionWS,1.0));\r\n\t#endif\r\n\r\n\t#ifdef CALCULATE_SPOTSHADOWS\r\n\t\tv_SpotShadowCoord = u_SpotViewProjectMatrix*vec4(positionWS,1.0);\r\n\t#endif\r\n\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  29645. var MeshBlinnPhongShadowCasterPS = "#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 \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
  29646. var MeshBlinnPhongShadowCasterVS = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS = shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
  29647. 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}";
  29648. 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\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\t\tvec3 velocity;\r\n\t\t\t#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n\t\t\t\tif(u_VOLSpaceType==0)\r\n\t\t\t\tvelocity=rotationByQuaternions(u_SizeScale*(startVelocity+lifeVelocity),worldRotation)+gravityVelocity;\r\n\t\t\t\telse\r\n\t\t\t\tvelocity=rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+lifeVelocity+gravityVelocity;\r\n\t\t\t#else\r\n\t\t\t\tvelocity= rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+gravityVelocity;\r\n\t\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";
  29649. var LayaPBRBRDF = "// allow to explicitly override LAYA_BRDF_GI and LAYA_BRDF_LIGHT in custom shader,default is layaBRDFHighGI and layaBRDFHighLight\r\n#if !defined (LAYA_BRDF_GI) \r\n\t#if defined(LAYA_PBR_BRDF_LOW)\r\n\t\t#define LAYA_BRDF_GI layaBRDFLowGI\r\n\t#elif defined(LAYA_PBR_BRDF_HIGH)\r\n\t\t#define LAYA_BRDF_GI layaBRDFHighGI\r\n\t#endif\r\n#endif\r\n#if !defined (LAYA_BRDF_LIGHT)\r\n\t#if defined(LAYA_PBR_BRDF_LOW)\r\n\t\t#define LAYA_BRDF_LIGHT layaBRDFLowLight\r\n\t#elif defined(LAYA_PBR_BRDF_HIGH)\r\n\t\t#define LAYA_BRDF_LIGHT layaBRDFHighLight\r\n\t#endif\r\n#endif\r\n\r\n#define PI 3.14159265359\r\n#define INV_PI 0.31830988618\r\n\r\nmediump float pow4(mediump float x)\r\n{\r\n\treturn x * x * x * x;\r\n}\r\n\r\nmediump float pow5(mediump float x)\r\n{\r\n\treturn x * x * x * x * x;\r\n}\r\n\r\nmediump vec3 fresnelLerp(mediump vec3 F0,mediump vec3 F90,mediump float cosA)\r\n{\r\n\tfloat t = pow5(1.0 - cosA); // ala Schlick interpoliation\r\n\treturn mix(F0, F90, t);\r\n}\r\n\r\nmediump vec3 fresnelTerm(mediump vec3 F0,mediump float cosA)\r\n{\r\n\tfloat t = pow5(1.0 - cosA); // ala Schlick interpoliation\r\n\treturn F0 + (vec3(1.0) - F0) * t;\r\n}\r\n\r\n// approximage Schlick with ^4 instead of ^5\r\nmediump vec3 fresnelLerpFast (mediump vec3 F0, mediump vec3 F90,mediump float cosA)\r\n{\r\n mediump float t = pow4 (1.0 - cosA);\r\n return mix (F0, F90, t);\r\n}\r\n\r\nfloat smoothnessToPerceptualRoughness(float smoothness)\r\n{\r\n return 1.0 - smoothness;\r\n}\r\n\r\nfloat perceptualRoughnessToRoughness(float perceptualRoughness)\r\n{\r\n return perceptualRoughness * perceptualRoughness;\r\n}\r\n\r\nvec3 safeNormalize(vec3 inVec)\r\n{\r\n\tfloat dp3 = max(0.001,dot(inVec,inVec));\r\n\treturn inVec * inversesqrt(dp3);\r\n}\r\n\r\n// Note: Disney diffuse must be multiply by diffuseAlbedo / PI. This is done outside of this function.\r\nmediump float disneyDiffuse(mediump float NdotV,mediump float NdotL,mediump float LdotH,mediump float perceptualRoughness)\r\n{\r\n\t//https://www.cnblogs.com/herenzhiming/articles/5790389.html\r\n\tmediump float fd90 = 0.5 + 2.0 * LdotH * LdotH * perceptualRoughness;\r\n\t// Two schlick fresnel term\r\n\tmediump float lightScatter = (1.0 + (fd90 - 1.0) * pow5(1.0 - NdotL));\r\n\tmediump float viewScatter = (1.0 + (fd90 - 1.0) * pow5(1.0 - NdotV));\r\n\r\n\treturn lightScatter * viewScatter;\r\n}\r\n\r\n// Ref: http://jcgt.org/published/0003/02/03/paper.pdf\r\nfloat smithJointGGXVisibilityTerm(float NdotL, float NdotV, float roughness)\r\n{\r\n\t// Original formulation:\r\n // lambda_v = (-1 + sqrt(a2 * (1 - NdotL2) / NdotL2 + 1)) * 0.5f;\r\n // lambda_l = (-1 + sqrt(a2 * (1 - NdotV2) / NdotV2 + 1)) * 0.5f;\r\n // G = 1 / (1 + lambda_v + lambda_l);\r\n\r\n\t// scientific code implement:\r\n\t// Reorder code to be more optimal\r\n // half a = roughness;\r\n // half a2 = a * a;\r\n\r\n // half lambdaV = NdotL * sqrt((-NdotV * a2 + NdotV) * NdotV + a2);\r\n // half lambdaL = NdotV * sqrt((-NdotL * a2 + NdotL) * NdotL + a2);\r\n\r\n // Simplify visibility term: (2.0f * NdotL * NdotV) / ((4.0f * NdotL * NdotV) * (lambda_v + lambda_l + 1e-5f));\r\n // return 0.5f / (lambdaV + lambdaL + 1e-5f); \r\n\t// This function is not intended to be running on Mobile,therefore epsilon is smaller than can be represented by half\r\n\r\n\t// Approximation of the above formulation (simplify the sqrt, not mathematically correct but close enough)\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\treturn 0.5 / (lambdaV + lambdaL + 1e-5);\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; // 2 mad\r\n\treturn INV_PI * a2 / (d * d + 1e-7); // This function is not intended to be running on Mobile,therefore epsilon is smaller than what can be represented by half//返回值小用half来返回\r\n}\r\n\r\n// BRDF1-------------------------------------------------------------------------------------\r\n\r\n// Note: BRDF entry points use smoothness and oneMinusReflectivity for optimization purposes,\r\n// mostly for DX9 SM2.0 level. Most of the math is being done on these (1-x) values, and that saves a few precious ALU slots.\r\n\r\n// Main Physically Based BRDF\r\n// Derived from Disney work and based on Torrance-Sparrow micro-facet model\r\n//\r\n// BRDF = kD / pi + kS * (D * V * F) / 4\r\n// I = BRDF * NdotL\r\n//\r\n// *NDF GGX:\r\n// *Smith for Visiblity term\r\n// *Schlick approximation for Fresnel\r\nmediump vec4 layaBRDFHighLight(mediump vec3 diffColor, mediump vec3 specColor, mediump float oneMinusReflectivity, float perceptualRoughness,float roughness,mediump float nv,vec3 normal, vec3 viewDir,LayaLight light)\r\n{\r\n\tvec3 halfDir = safeNormalize(viewDir-light.dir);\r\n\r\n\tfloat nl = clamp(dot(normal, -light.dir),0.0,1.0);\r\n\tfloat nh = clamp(dot(normal, halfDir),0.0,1.0);\r\n\tmediump float lv = clamp(dot(light.dir, viewDir),0.0,1.0);\r\n\tmediump float lh = clamp(dot(light.dir, -halfDir),0.0,1.0);\r\n\r\n\t// Diffuse term\r\n\tmediump float diffuseTerm = disneyDiffuse(nv, nl, lh, perceptualRoughness) * nl;\r\n\r\n\t// Specular term\r\n // HACK: theoretically we should divide diffuseTerm by Pi and not multiply specularTerm!\r\n // BUT that will make shader look significantly darker than Legacy ones\r\n\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.002);\r\n\tfloat V = smithJointGGXVisibilityTerm(nl, nv, roughness);\r\n\tfloat D = ggxTerm(nh, roughness);\r\n\r\n\tfloat specularTerm = V * D * PI; // Torrance-Sparrow model, Fresnel is applied later\r\n\r\n\t//#ifdef LAYA_COLORSPACE_GAMMA\r\n\tspecularTerm = sqrt(max(1e-4, specularTerm));\r\n\t//#endif\r\n\tspecularTerm = max(0.0, specularTerm * nl);\r\n\t\t\r\n\tmediump vec3 color = diffColor * light.color * diffuseTerm + specularTerm * light.color * fresnelTerm(specColor, lh);\r\n\treturn vec4(color, 1.0);\r\n}\r\n\r\nvec4 layaBRDFHighGI(mediump vec3 diffColor,mediump vec3 specColor,mediump float oneMinusReflectivity,float smoothness ,float perceptualRoughness,float roughness,mediump float nv,vec3 normal, vec3 viewDir,LayaGI gi)\r\n{\r\n\t// surfaceReduction = Int D(NdotH) * NdotH * Id(NdotL>0) dH = 1/(roughness^2+1)\r\n\tfloat surfaceReduction;\r\n\tsurfaceReduction = 1.0 - 0.28*roughness*perceptualRoughness;// 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1]\r\n\tfloat grazingTerm = clamp(smoothness + (1.0 - oneMinusReflectivity),0.0,1.0);\r\n\tmediump vec3 color =diffColor * gi.diffuse + surfaceReduction * gi.specular * fresnelLerp(specColor,vec3(grazingTerm), nv);\r\n\treturn vec4(color,1.0);\r\n}\r\n// BRDF1-------------------------------------------------------------------------------------\r\n\r\n\r\n// BRDF2-------------------------------------------------------------------------------------\r\n// Based on Minimalist CookTorrance BRDF\r\n// Implementation is slightly different from original derivation: http://www.thetenthplanet.de/archives/255\r\n//\r\n// *NDF [Modified] GGX:\r\n// *Modified Kelemen and Szirmay-​Kalos for Visibility term\r\n// *Fresnel approximated with 1/LdotH\r\nmediump vec4 layaBRDFLowLight (mediump vec3 diffColor, mediump vec3 specColor,mediump float oneMinusReflectivity,float perceptualRoughness,float roughness,mediump float nv,vec3 normal,vec3 viewDir,LayaLight light)\r\n{\r\n vec3 halfDir = safeNormalize (viewDir-light.dir);\r\n mediump float nl = clamp(dot(normal, -light.dir),0.0,1.0);\r\n float nh = clamp(dot(normal, halfDir),0.0,1.0);\r\n float lh = clamp(dot(-light.dir, halfDir),0.0,1.0);\r\n\r\n // GGX Distribution multiplied by combined approximation of Visibility and Fresnel\r\n // See \"Optimizing PBR for Mobile\" from Siggraph 2015 moving mobile graphics course\r\n // https://community.arm.com/events/1155\r\n mediump float a = roughness;\r\n float a2 = a*a;\r\n\r\n float d = nh * nh * (a2 - 1.0) + 1.00001;\r\n\t// #ifdef LAYA_COLORSPACE_GAMMA\r\n\t\t// Tighter approximation for Gamma only rendering mode!\r\n\t\t// DVF = sqrt(DVF);\r\n\t\t// DVF = (a * sqrt(.25)) / (max(sqrt(0.1), lh)*sqrt(roughness + .5) * d);\r\n\t\tfloat specularTerm = a / (max(0.32, lh) * (1.5 + roughness) * d);\r\n\t// #else\r\n\t// \tfloat specularTerm = a2 / (max(0.1f, lh*lh) * (roughness + 0.5f) * (d * d) * 4);\r\n\t// #endif\r\n\r\n // on mobiles (where half actually means something) denominator have risk of overflow\r\n // clamp below was added specifically to \"fix\" that, but dx compiler (we convert bytecode to metal/gles)\r\n // sees that specularTerm have only non-negative terms, so it skips max(0,..) in clamp (leaving only min(100,...))\r\n\r\n\t//#if defined (SHADER_API_MOBILE)\r\n specularTerm = specularTerm - 1e-4;\r\n\t//#endif\r\n\r\n\t// #else\r\n\t\t// // Legacy\r\n\t\t// half specularPower = PerceptualRoughnessToSpecPower(perceptualRoughness);\r\n\t\t// // Modified with approximate Visibility function that takes roughness into account\r\n\t\t// // Original ((n+1)*N.H^n) / (8*Pi * L.H^3) didn't take into account roughness\r\n\t\t// // and produced extremely bright specular at grazing angles\r\n\r\n\t\t// half invV = lh * lh * smoothness + perceptualRoughness * perceptualRoughness; // approx ModifiedKelemenVisibilityTerm(lh, perceptualRoughness);\r\n\t\t// half invF = lh;\r\n\r\n\t\t// half specularTerm = ((specularPower + 1) * pow (nh, specularPower)) / (8 * invV * invF + 1e-4h);\r\n\r\n\t\t// #ifdef LAYA_COLORSPACE_GAMMA\r\n\t\t// \tspecularTerm = sqrt(max(1e-4f, specularTerm));\r\n\t\t// #endif\r\n\t// #endif\r\n\r\n\t// #if defined (SHADER_API_MOBILE)\r\n\t\tspecularTerm = clamp(specularTerm, 0.0, 100.0); // Prevent FP16 overflow on mobiles\r\n\t// #endif\r\n \r\n mediump vec3 color = (diffColor + specularTerm * specColor) * light.color * nl;\r\n\r\n return vec4(color, 1.0);\r\n}\r\n\r\nmediump vec4 layaBRDFLowGI (mediump vec3 diffColor, mediump vec3 specColor,mediump float oneMinusReflectivity,mediump float smoothness,float perceptualRoughness,float roughness,mediump float nv,vec3 normal,vec3 viewDir,LayaGI gi)\r\n{\r\n\t// surfaceReduction = Int D(NdotH) * NdotH * Id(NdotL>0) dH = 1/(realRoughness^2+1)\r\n\r\n // 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1]\r\n // 1-x^3*(0.6-0.08*x) approximation for 1/(x^4+1)\r\n\t// #ifdef LAYA_COLORSPACE_GAMMA\r\n\t\tmediump float surfaceReduction = 0.28;\r\n\t// #else\r\n\t\t// mediump float surfaceReduction = (0.6-0.08*perceptualRoughness);\r\n\t// #endif\r\n\r\n surfaceReduction = 1.0 - roughness*perceptualRoughness*surfaceReduction;\r\n\r\n\tmediump float grazingTerm = clamp(smoothness + (1.0-oneMinusReflectivity),0.0,1.0);\r\n\tmediump vec3 color =gi.diffuse * diffColor+ surfaceReduction * gi.specular * fresnelLerpFast (specColor, vec3(grazingTerm), nv);\r\n\r\n return vec4(color, 1.0);\r\n}\r\n// BRDF2-------------------------------------------------------------------------------------";
  29650. var PBRCore = "struct FragmentCommonData{\r\n\tvec3 diffColor;\r\n\tvec3 specColor;\r\n\tfloat oneMinusReflectivity;\r\n\tfloat smoothness;\r\n\t//vec3 eyeVec;TODO:maybe can remove\r\n\t//float alpha;\r\n\t//vec3 reflUVW;\r\n};\r\n\r\n#ifndef SETUP_BRDF_INPUT\r\n #define SETUP_BRDF_INPUT metallicSetup//default is metallicSetup,also can be other. \r\n#endif\r\n\r\nconst mediump vec4 dielectricSpecularColor = vec4(0.220916301, 0.220916301, 0.220916301, 1.0 - 0.220916301);\r\n\r\nmediump vec3 diffuseAndSpecularFromMetallic(mediump vec3 albedo,mediump float metallic, out mediump vec3 specColor, out mediump float oneMinusReflectivity)\r\n{\r\n\tspecColor = mix(dielectricSpecularColor.rgb, albedo, metallic);\r\n\toneMinusReflectivity= dielectricSpecularColor.a*(1.0-metallic);//diffuse proportion\r\n\treturn albedo * oneMinusReflectivity;\r\n}\r\n\r\nmediump float specularStrength(mediump vec3 specular)\r\n{\r\n return max (max (specular.r, specular.g), specular.b);\r\n}\r\n\r\n// Diffuse/Spec Energy conservation\r\nmediump vec3 energyConservationBetweenDiffuseAndSpecular (mediump vec3 albedo, mediump vec3 specColor, out mediump float oneMinusReflectivity)\r\n{\r\n\toneMinusReflectivity = 1.0 - specularStrength(specColor);\r\n return albedo * (vec3(1.0) - specColor);\r\n}\r\n\r\n#ifdef TRANSPARENTBLEND\r\n\tmediump vec3 preMultiplyAlpha (mediump vec3 diffColor, mediump float alpha, mediump float oneMinusReflectivity,out mediump float modifiedAlpha)\r\n\t{\r\n\t\t// Transparency 'removes' from Diffuse component\r\n\t\tdiffColor *= alpha;\r\n\t\t// Reflectivity 'removes' from the rest of components, including Transparency\r\n\t\t// modifiedAlpha = 1.0-(1.0-alpha)*(1.0-reflectivity) = 1.0-(oneMinusReflectivity - alpha*oneMinusReflectivity) = 1.0-oneMinusReflectivity + alpha*oneMinusReflectivity\r\n\t\tmodifiedAlpha = 1.0 - oneMinusReflectivity + alpha*oneMinusReflectivity;\r\n\t\treturn diffColor;\r\n\t}\r\n#endif\r\n\r\nFragmentCommonData metallicSetup(vec2 uv)\r\n{\r\n\tmediump vec2 metallicGloss = getMetallicGloss(uv);\r\n\tmediump float metallic = metallicGloss.x;\r\n\tmediump float smoothness = metallicGloss.y; // this is 1 minus the square root of real roughness m.\r\n\tmediump float oneMinusReflectivity;\r\n\tmediump vec3 specColor;\r\n\tmediump vec3 diffColor = diffuseAndSpecularFromMetallic(albedo(uv), metallic,/*out*/specColor,/*out*/oneMinusReflectivity);\r\n\r\n\tFragmentCommonData o;\r\n\to.diffColor = diffColor;\r\n\to.specColor = specColor;\r\n\to.oneMinusReflectivity = oneMinusReflectivity;\r\n\to.smoothness = smoothness;\r\n\treturn o;\r\n}\r\n\r\nFragmentCommonData specularSetup(vec2 uv)\r\n{\r\n mediump vec4 specGloss = specularGloss(uv);\r\n mediump vec3 specColor = specGloss.rgb;\r\n mediump float smoothness = specGloss.a;\r\n\r\n mediump float oneMinusReflectivity;\r\n mediump vec3 diffColor = energyConservationBetweenDiffuseAndSpecular (albedo(uv), specColor, /*out*/ oneMinusReflectivity);\r\n\r\n FragmentCommonData o;\r\n o.diffColor = diffColor;\r\n o.specColor = specColor;\r\n o.oneMinusReflectivity = oneMinusReflectivity;\r\n o.smoothness = smoothness;\r\n return o;\r\n}\r\n\r\nLayaGI fragmentGI(float smoothness,vec3 eyeVec,mediump float occlusion,mediump vec2 lightmapUV,vec3 worldnormal)\r\n{\r\n\tLayaGIInput giInput;\r\n\t#ifdef LIGHTMAP\r\n\t\tgiInput.lightmapUV=lightmapUV;\r\n\t#endif\r\n\r\n\tvec3 worldViewDir = -eyeVec;\r\n\tmediump vec4 uvwRoughness;\r\n\tuvwRoughness.rgb = reflect(worldViewDir, worldnormal);//reflectUVW\r\n\tuvwRoughness.a= smoothnessToPerceptualRoughness(smoothness);//perceptualRoughness\r\n\r\n\treturn layaGlobalIllumination(giInput,occlusion, worldnormal, uvwRoughness);\r\n}\r\n\r\n\r\nvec3 perPixelWorldNormal(vec2 uv,vec3 normal,vec3 binormal,vec3 tangent)\r\n{\r\n\t#ifdef NORMALTEXTURE\r\n\t\tmediump vec3 normalTangent=normalInTangentSpace(uv);\r\n\t\tvec3 normalWorld = normalize(tangent * normalTangent.x + binormal * normalTangent.y + normal * normalTangent.z);\r\n\t#else\r\n\t\tvec3 normalWorld = normalize(normal);\r\n\t#endif\r\n\t\treturn normalWorld;\r\n}\r\n\r\nvoid fragmentForward()\r\n{\r\n\tvec2 uv;\r\n\t#if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)\r\n\t\t#ifdef PARALLAXTEXTURE\r\n\t\t\tuv = parallax(v_Texcoord0,normalize(v_ViewDirForParallax));\r\n\t\t#else\r\n\t\t\tuv = v_Texcoord0;\r\n\t\t#endif\r\n\t#endif\r\n\r\n\tmediump float alpha = getAlpha(uv);\r\n\t#ifdef ALPHATEST\r\n\t\tif(alpha<u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n\r\n\tFragmentCommonData o = SETUP_BRDF_INPUT(uv);\r\n\t\r\n\tvec3 binormal;\r\n\tvec3 tangent;\r\n\t#ifdef NORMALTEXTURE\r\n\t\ttangent = v_Tangent;\r\n\t\tbinormal = v_Binormal;\r\n\t#endif\r\n\r\n\tvec3 normal = v_Normal;\r\n\tvec3 normalWorld = perPixelWorldNormal(uv,normal,binormal,tangent);//In FS if the normal use mediump before normalize will cause precision prolem in mobile device.\r\n\tvec3 eyeVec = normalize(v_EyeVec);\r\n\tvec3 posworld = v_PositionWorld;\r\n\r\n\t#ifdef TRANSPARENTBLEND\r\n\t\to.diffColor=preMultiplyAlpha(o.diffColor,alpha,o.oneMinusReflectivity,/*out*/alpha);// shader relies on pre-multiply alpha-blend (srcBlend = One, dstBlend = OneMinusSrcAlpha)\r\n\t#endif\r\n\r\n\tmediump float occlusion = getOcclusion(uv);\r\n\tmediump vec2 lightMapUV;\r\n\t#ifdef LIGHTMAP\r\n\t\tlightMapUV=v_LightMapUV;\r\n\t#endif\r\n\tfloat perceptualRoughness = smoothnessToPerceptualRoughness(o.smoothness);\r\n\tfloat roughness = perceptualRoughnessToRoughness(perceptualRoughness);\r\n\tfloat nv = abs(dot(normalWorld, eyeVec));\r\n\tLayaGI gi =fragmentGI(o.smoothness,eyeVec,occlusion,lightMapUV,normalWorld);\r\n\tvec4 color = LAYA_BRDF_GI(o.diffColor,o.specColor,o.oneMinusReflectivity,o.smoothness,perceptualRoughness,roughness,nv,normalWorld,eyeVec,gi);\r\n\t\r\n\tfloat shadowAttenuation = 1.0;\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\t#ifdef CALCULATE_SHADOWS\r\n\t\t\t\t#ifdef SHADOW_CASCADE\r\n\t\t\t\t\tvec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t\t\t\t#else\r\n\t\t\t\t\tvec4 shadowCoord = v_ShadowCoord;\r\n\t\t\t\t#endif\r\n\t\t\t\tshadowAttenuation=sampleShadowmap(shadowCoord);\r\n\t\t\t#endif\r\n\t\t\tLayaLight dirLight = layaDirectionLightToLight(u_DirectionLight,shadowAttenuation);\r\n\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tshadowAttenuation = 1.0;\r\n\t\t\tLayaLight poiLight = layaPointLightToLight(posworld,normalWorld,u_PointLight,shadowAttenuation);\r\n\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,poiLight);\r\n\t\t#endif\r\n\t\t\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tshadowAttenuation = 1.0;\r\n\t\t\t#ifdef CALCULATE_SPOTSHADOWS\r\n\t\t\t\tvec4 spotShadowcoord = v_SpotShadowCoord;\r\n\t\t\t\tshadowAttenuation = sampleSpotShadowmap(spotShadowcoord);\r\n\t\t\t#endif\r\n\t\t LayaLight spoLight = layaSpotLightToLight(posworld,normalWorld,u_SpotLight,shadowAttenuation);\r\n\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,spoLight);\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\tshadowAttenuation = 1.0;\r\n\t\t\t\tif(i >= u_DirationLightCount)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t#ifdef CALCULATE_SHADOWS\r\n\t\t\t\t\tif(i == 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t#ifdef SHADOW_CASCADE\r\n\t\t\t\t\t\t\tvec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t\t\t\t\t\t#else\r\n\t\t\t\t\t\t\tvec4 shadowCoord = v_ShadowCoord;\r\n\t\t\t\t\t\t#endif\r\n\t\t\t\t\t\tshadowAttenuation *= sampleShadowmap(shadowCoord);\r\n\t\t\t\t\t}\r\n\t\t\t\t#endif\r\n\t\t\t\tDirectionLight directionLight = getDirectionLight(u_LightBuffer,i);\r\n\t\t\t\tLayaLight dirLight = layaDirectionLightToLight(directionLight,shadowAttenuation);\r\n\t\t\t \tcolor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);\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\tshadowAttenuation = 1.0;\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\tLayaLight poiLight = layaPointLightToLight(posworld,normalWorld,pointLight,shadowAttenuation);\r\n\t\t\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,poiLight);\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\tshadowAttenuation = 1.0;\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\t#ifdef CALCULATE_SPOTSHADOWS\r\n\t\t\t\t\t\tif(i == 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tvec4 spotShadowcoord = v_SpotShadowCoord;\r\n\t\t\t\t\t\t\tshadowAttenuation= sampleSpotShadowmap(spotShadowcoord);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t#endif\r\n\t\t\t\t\tSpotLight spotLight = getSpotLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaLight spoLight = layaSpotLightToLight(posworld,normalWorld,spotLight,shadowAttenuation);\r\n\t\t\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,spoLight);\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 EMISSION\r\n\t\tcolor.rgb += emission(uv);\r\n\t#endif\r\n\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\tcolor.rgb=mix(color.rgb,u_FogColor,lerpFact);\r\n\t#endif\r\n\t\r\n\tgl_FragColor=vec4(color.rgb,alpha);\r\n}\r\n\r\n\r\n";
  29651. var PBRVSInput = "attribute vec4 a_Position;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n\tuniform mat4 u_WorldMat;\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\nattribute vec3 a_Normal;\r\nvarying vec3 v_Normal; \r\n\r\n#if defined(NORMALTEXTURE)||defined(PARALLAXTEXTURE)\r\n\tattribute vec4 a_Tangent0;\r\n\tvarying vec3 v_Tangent;\r\n\tvarying vec3 v_Binormal;\r\n #ifdef PARALLAXTEXTURE\r\n\t varying vec3 v_ViewDirForParallax;\r\n #endif\r\n#endif\r\n\r\n#if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)||(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\nuniform vec3 u_CameraPos;\r\nvarying vec3 v_EyeVec;\r\nvarying vec3 v_PositionWorld;\r\nvarying float v_posViewZ;\r\n\r\n#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\n#ifdef CALCULATE_SPOTSHADOWS\r\n\tvarying vec4 v_SpotShadowCoord;\r\n#endif\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif";
  29652. var PBRFSInput = "#ifdef ALPHATEST\r\n\tuniform float u_AlphaTestValue;\r\n#endif\r\n\r\nuniform vec4 u_AlbedoColor;\r\n\r\n#ifdef NORMALTEXTURE\r\n\tuniform sampler2D u_NormalTexture;\r\n\tuniform float u_NormalScale;\r\n#endif\r\n\r\n#ifdef ALBEDOTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n#endif\r\n\r\n#ifdef METALLICGLOSSTEXTURE\r\n\tuniform sampler2D u_MetallicGlossTexture;\r\n#endif\r\nuniform float u_Metallic;\r\n\r\n#ifdef SPECULARGLOSSTEXTURE\r\n\tuniform sampler2D u_SpecGlossTexture;\r\n#endif\r\nuniform vec3 u_SpecularColor;\r\n\r\nuniform float u_Smoothness;\r\nuniform float u_SmoothnessScale;\r\n\r\n#ifdef PARALLAXTEXTURE\r\n\tuniform sampler2D u_ParallaxTexture;\r\n\tuniform float u_ParallaxScale;\r\n\tvarying vec3 v_ViewDirForParallax;\r\n#endif\r\n\r\n#ifdef OCCLUSIONTEXTURE\r\n\tuniform sampler2D u_OcclusionTexture;\r\n\tuniform float u_occlusionStrength;\r\n#endif\r\n\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\r\n#if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)\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\t#ifdef LIGHTMAP_DIRECTIONAL\r\n\t\tuniform sampler2D u_LightMapDirection;\r\n\t#endif\r\n#endif\r\n\r\nvarying vec3 v_Normal; \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\nvarying vec3 v_EyeVec;\r\n\r\n#ifdef NORMALTEXTURE\r\n\tvarying vec3 v_Tangent;\r\n\tvarying vec3 v_Binormal;\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\n//后面考虑宏TODO\r\nvarying vec3 v_PositionWorld;\r\n\r\n#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\n#ifdef CALCULATE_SPOTSHADOWS\r\n\tvarying vec4 v_SpotShadowCoord;\r\n#endif\r\n\r\nmediump float lerpOneTo(mediump float b, mediump float t)\r\n{\r\n mediump float oneMinusT = 1.0 - t;\r\n return oneMinusT + b * t;\r\n}\r\n\r\n#ifdef EMISSION \r\n\tvec3 emission(vec2 uv)\r\n\t{\r\n\t\t#ifdef EMISSIONTEXTURE\r\n\t\t\treturn texture2D(u_EmissionTexture, uv).rgb * u_EmissionColor.rgb;\r\n\t\t#else\r\n\t\t\treturn u_EmissionColor.rgb;\r\n\t\t#endif\r\n\t}\r\n#endif\r\n\r\nmediump float getAlpha(vec2 uv)\r\n{\r\n\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\treturn u_AlbedoColor.a;\r\n\t#else\r\n\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\treturn texture2D(u_AlbedoTexture, uv).a * u_AlbedoColor.a;\r\n\t\t#else\r\n\t\t\treturn u_AlbedoColor.a;\r\n\t\t#endif\r\n\t#endif\r\n}\r\n\r\nmediump float getOcclusion(vec2 uv)\r\n{\r\n\t#ifdef OCCLUSIONTEXTURE\r\n\t\tmediump float occ = texture2D(u_OcclusionTexture, uv).g;\r\n\t\treturn lerpOneTo(occ, u_occlusionStrength);\r\n\t#else\r\n\t\treturn 1.0;\r\n\t#endif\r\n}\r\n\r\nmediump vec3 albedo(vec2 uv)\r\n{\r\n\t#ifdef ALBEDOTEXTURE\r\n\t\treturn u_AlbedoColor.rgb * texture2D(u_AlbedoTexture, uv).rgb;\r\n\t#else\r\n\t\treturn u_AlbedoColor.rgb;\r\n\t#endif\r\n\t//TODO:Detail Texture\r\n}\r\n\r\nmediump vec2 getMetallicGloss(vec2 uv)\r\n{\r\n\tmediump vec2 ms;//x is metallic,y is smoothness\r\n\t#ifdef METALLICGLOSSTEXTURE\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tms.x = texture2D(u_MetallicGlossTexture, uv).r;\r\n\t\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\t\tms.y = texture2D(u_AlbedoTexture, uv).a*u_SmoothnessScale;\r\n\t\t\t#else\r\n\t\t\t\tms.y = u_SmoothnessScale;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\tms = texture2D(u_MetallicGlossTexture, uv).ra;\r\n\t\t\tms.y *= u_SmoothnessScale;\r\n\t\t#endif\r\n\t#else\r\n\t\tms.x = u_Metallic;\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\t\tms.y = texture2D(u_AlbedoTexture, uv).a * u_SmoothnessScale;\r\n\t\t\t#else\r\n\t\t\t\tms.y = u_SmoothnessScale;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\tms.y = u_Smoothness;\r\n\t\t#endif\r\n\t#endif\r\n\treturn ms;\r\n}\r\n\r\nmediump vec4 specularGloss(vec2 uv)\r\n{\r\n\tmediump vec4 sg;\r\n\t#ifdef SPECULARGLOSSTEXTURE\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tsg.rgb = texture2D(u_SpecGlossTexture, uv).rgb;\r\n\t\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\t\tsg.a = texture2D(u_AlbedoTexture, uv).a*u_SmoothnessScale;\r\n\t\t\t#else\r\n\t\t\t\tsg.a = u_SmoothnessScale;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\tsg = texture2D(u_SpecGlossTexture, uv);\r\n\t\t\tsg.a *= u_SmoothnessScale;\r\n\t\t#endif\r\n\t#else\r\n\t\tsg.rgb = u_SpecularColor.rgb;\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\t\tsg.a = texture2D(u_AlbedoTexture, uv).a * u_SmoothnessScale;\r\n\t\t\t#else\r\n\t\t\t\tsg.a = u_SmoothnessScale;\r\n\t\t\t#endif\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\treturn sg;\r\n}\r\n\r\n\r\n#ifdef NORMALTEXTURE\r\n\tmediump vec3 unpackScaleNormal(mediump vec3 packednormal, mediump float bumpScale)\r\n\t{\r\n\t\tmediump vec3 normal = packednormal.xyz * 2.0 - 1.0;\r\n\t\tnormal.y=-normal.y;//NOTE:because unity to LayaAir coordSystem.\r\n\t\tnormal.xy *= bumpScale;\r\n\t\treturn normal;\r\n\t}\r\n\t\r\n\tmediump vec3 normalInTangentSpace(vec2 texcoords)\r\n\t{\r\n\t\tmediump vec3 normalTangent = unpackScaleNormal(texture2D(u_NormalTexture, texcoords).rgb,u_NormalScale);\r\n\t\treturn normalTangent;\r\n\t}\r\n#endif\r\n\r\n#ifdef PARALLAXTEXTURE\r\n\tmediump vec2 parallaxOffset1Step(mediump float h, mediump float height, mediump vec3 viewDir)\r\n\t{\r\n\t\th = h * height - height / 2.0;\r\n\t\tviewDir.z += 0.42;\r\n\t\treturn h * (viewDir.xy / viewDir.z);\r\n\t}\r\n\r\n\tvec2 parallax(vec2 texcoords, mediump vec3 viewDir)\r\n\t{\r\n\t\tmediump float h = texture2D(u_ParallaxTexture, texcoords.xy).g;\r\n\t\tvec2 offset = parallaxOffset1Step(h, u_ParallaxScale, viewDir);\r\n\t\treturn texcoords+offset;\r\n\t}\r\n#endif\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n";
  29653. var PBRVertex = "vec2 transformLightMapUV(in vec2 texcoord,in vec4 lightmapScaleOffset)\r\n{\r\n\tvec2 lightMapUV=vec2(texcoord.x,1.0-texcoord.y)*lightmapScaleOffset.xy+lightmapScaleOffset.zw;\r\n\tlightMapUV.y=1.0-lightMapUV.y;\r\n\treturn lightMapUV; \r\n}\r\n\r\nvoid vertexForward()\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\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\tmat4 worldMat;\r\n\t#ifdef GPU_INSTANCE\r\n\t\tworldMat = a_WorldMat;\r\n\t#else\r\n\t\tworldMat = u_WorldMat;\r\n\t#endif\r\n\r\n\tv_PositionWorld=(worldMat*position).xyz;\r\n\r\n\t#if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)\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\tv_EyeVec =u_CameraPos-v_PositionWorld;//will normalize per-pixel\r\n\r\n\t#ifdef LIGHTMAP\r\n\t\tvec2 texcoord;\r\n\t\t#ifdef UV1\r\n\t\t\ttexcoord=a_Texcoord1;\r\n\t\t#else\r\n\t\t\ttexcoord=a_Texcoord0;\r\n\t\t#endif\r\n\t\tv_LightMapUV=transformLightMapUV(texcoord,u_LightmapScaleOffset);\r\n\t#endif\r\n\r\n\tmat3 worldInvMat;\r\n\t#ifdef BONE\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));\r\n\t#else\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat));\r\n\t#endif\r\n\r\n\tv_Normal=normalize(a_Normal*worldInvMat);//if no normalize will cause precision problem.\r\n\r\n\t#ifdef NORMALTEXTURE\r\n\t\tv_Tangent=normalize(a_Tangent0.xyz*worldInvMat);\r\n\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t#endif\r\n\r\n\t#ifdef PARALLAXTEXTURE\r\n\t\tvec3 binormal = cross(a_Normal, a_Tangent0.xyz)*a_Tangent0.w;\r\n\t\tmat3 objectTBN = mat3(a_Tangent0.xyz, binormal, a_Normal);\r\n\t\tv_ViewDirForParallax=(worldInvMat*u_CameraPos-position.xyz)*objectTBN;\r\n\t#endif\r\n\r\n\t#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\t\tv_ShadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t#endif\r\n\r\n\t#ifdef CALCULATE_SPOTSHADOWS\r\n\t\tv_SpotShadowCoord = u_SpotViewProjectMatrix*vec4(positionWS,1.0);\r\n\t#endif\r\n}";
  29654. 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}";
  29655. 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}";
  29656. 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}";
  29657. 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}";
  29658. 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}";
  29659. 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}";
  29660. 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}";
  29661. 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}";
  29662. 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}";
  29663. 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}";
  29664. 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}";
  29665. 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}";
  29666. var ShadowGLSL = "#ifndef GRAPHICS_API_GLES3\r\n\t#define NO_NATIVE_SHADOWMAP\r\n#endif\r\n\r\n#ifdef NO_NATIVE_SHADOWMAP\r\n\t#define TEXTURE2D_SHADOW(textureName) uniform mediump sampler2D textureName\r\n\t#define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) (texture2D(textureName,coord3.xy).r<coord3.z?0.0:1.0)\r\n\t#define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2D shadowMap\r\n#else\r\n\t#define TEXTURE2D_SHADOW(textureName) uniform mediump sampler2DShadow textureName\r\n\t#define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) textureLod(textureName,coord3,0.0)\r\n\t#define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2DShadow shadowMap\r\n#endif\r\n\r\n#if defined(RECEIVESHADOW)&&defined(SHADOW)\r\n #define CALCULATE_SHADOWS\r\n#endif\r\n\r\n#if defined(RECEIVESHADOW)&&defined(SHADOW_SPOT)\r\n\t#define CALCULATE_SPOTSHADOWS\r\n#endif\r\n\r\nuniform vec4 u_ShadowBias; // x: depth bias, y: normal bias\r\n\r\n#if defined(CALCULATE_SHADOWS)||defined(CALCULATE_SPOTSHADOWS)\r\n\t#include \"ShadowSampleTent.glsl\"\r\n\tuniform vec4 u_ShadowMapSize;\r\n\tuniform vec4 u_ShadowParams; // x: shadowStrength y: ShadowSpotLightStrength\r\n\r\n\t\r\n\tfloat sampleShdowMapFiltered4(TEXTURE2D_SHADOW_PARAM(shadowMap),vec3 shadowCoord,vec4 shadowMapSize)\r\n\t{\r\n\t\tfloat attenuation;\r\n\t\tvec4 attenuation4;\r\n\t\tvec2 offset=shadowMapSize.xy/2.0;\r\n\t\tvec3 shadowCoord0=shadowCoord + vec3(-offset,0.0);\r\n\t\tvec3 shadowCoord1=shadowCoord + vec3(offset.x,-offset.y,0.0);\r\n\t\tvec3 shadowCoord2=shadowCoord + vec3(-offset.x,offset.y,0.0);\r\n\t\tvec3 shadowCoord3=shadowCoord + vec3(offset,0.0);\r\n\t\tattenuation4.x = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord0);\r\n\t\tattenuation4.y = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord1);\r\n\t\tattenuation4.z = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord2);\r\n\t\tattenuation4.w = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord3);\r\n\t\tattenuation = dot(attenuation4, vec4(0.25));\r\n\t\treturn attenuation;\r\n\t}\r\n\r\n\tfloat sampleShdowMapFiltered9(TEXTURE2D_SHADOW_PARAM(shadowMap),vec3 shadowCoord,vec4 shadowmapSize)\r\n\t{\r\n\t\tfloat attenuation;\r\n\t\tfloat fetchesWeights[9];\r\n\t\tvec2 fetchesUV[9];\r\n\t\tsampleShadowComputeSamplesTent5x5(shadowmapSize, shadowCoord.xy, fetchesWeights, fetchesUV);\r\n\t\tattenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[0].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[1].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[2].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[3].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[4].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[5].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[6].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[7].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[8].xy, shadowCoord.z));\r\n\t\treturn attenuation;\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n\r\n\r\n#ifdef CALCULATE_SHADOWS\r\n\r\n\tTEXTURE2D_SHADOW(u_ShadowMap);\r\n\r\n\tuniform mat4 u_ShadowMatrices[4];\r\n\tuniform vec4 u_ShadowSplitSpheres[4];// max cascade is 4\r\n\r\n\tmediump int computeCascadeIndex(vec3 positionWS)\r\n\t{\r\n\t\tvec3 fromCenter0 = positionWS - u_ShadowSplitSpheres[0].xyz;\r\n\t\tvec3 fromCenter1 = positionWS - u_ShadowSplitSpheres[1].xyz;\r\n\t\tvec3 fromCenter2 = positionWS - u_ShadowSplitSpheres[2].xyz;\r\n\t\tvec3 fromCenter3 = positionWS - u_ShadowSplitSpheres[3].xyz;\r\n\r\n\t\tmediump vec4 comparison = vec4(\r\n\t\t\tdot(fromCenter0, fromCenter0)<u_ShadowSplitSpheres[0].w,\r\n\t\t\tdot(fromCenter1, fromCenter1)<u_ShadowSplitSpheres[1].w,\r\n\t\t\tdot(fromCenter2, fromCenter2)<u_ShadowSplitSpheres[2].w,\r\n\t\t\tdot(fromCenter3, fromCenter3)<u_ShadowSplitSpheres[3].w);\r\n\t\tcomparison.yzw = clamp(comparison.yzw - comparison.xyz,0.0,1.0);//keep the nearest\r\n\t\tmediump vec4 indexCoefficient = vec4(4.0,3.0,2.0,1.0);\r\n\t\tmediump int index = 4 - int(dot(comparison, indexCoefficient));\r\n\t\treturn index;\r\n\t}\r\n\r\n\tvec4 getShadowCoord(vec4 positionWS)\r\n\t{\r\n\t\t#ifdef SHADOW_CASCADE\r\n\t\t\tmediump int cascadeIndex = computeCascadeIndex(positionWS.xyz);\r\n\t\t\tif(cascadeIndex > 3)// out of shadow range cascadeIndex is 4.\r\n\t\t\t\treturn vec4(0.0);\r\n\t\t\t\r\n\t\t\t#ifdef GRAPHICS_API_GLES3\r\n\t\t\t\treturn u_ShadowMatrices[cascadeIndex] * positionWS;\r\n\t\t\t#else\r\n\t\t\t\tmat4 shadowMat;\r\n\t\t\t\tif(cascadeIndex == 0)\r\n\t\t\t\t\tshadowMat = u_ShadowMatrices[0];\r\n\t\t\t\telse if(cascadeIndex == 1)\r\n\t\t\t\t\tshadowMat = u_ShadowMatrices[1];\r\n\t\t\t\telse if(cascadeIndex == 2)\r\n\t\t\t\t\tshadowMat = u_ShadowMatrices[2];\r\n\t\t\t\telse\r\n\t\t\t\t\tshadowMat = u_ShadowMatrices[3];\r\n\t\t\t\treturn shadowMat * positionWS;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\treturn u_ShadowMatrices[0] * positionWS;\r\n\t\t#endif\r\n\t}\r\n\r\n\tfloat sampleShadowmap(vec4 shadowCoord)\r\n\t{\r\n\t\tshadowCoord.xyz /= shadowCoord.w;\r\n\t\tfloat attenuation = 1.0;\r\n\t\tif(shadowCoord.z > 0.0 && shadowCoord.z < 1.0)\r\n\t\t{\r\n\t\t\t#if defined(SHADOW_SOFT_SHADOW_HIGH)\r\n\t\t\t\tattenuation = sampleShdowMapFiltered9(u_ShadowMap,shadowCoord.xyz,u_ShadowMapSize);\r\n\t\t\t#elif defined(SHADOW_SOFT_SHADOW_LOW)\r\n\t\t\t\tattenuation = sampleShdowMapFiltered4(u_ShadowMap,shadowCoord.xyz,u_ShadowMapSize);\r\n\t\t\t#else\r\n\t\t\t\tattenuation = SAMPLE_TEXTURE2D_SHADOW(u_ShadowMap,shadowCoord.xyz);\r\n\t\t\t#endif\r\n\t\t\tattenuation = mix(1.0,attenuation,u_ShadowParams.x);//shadowParams.x:shadow strength\r\n\t\t}\r\n\t\treturn attenuation;\r\n\t}\r\n#endif\r\n\r\n#ifdef CALCULATE_SPOTSHADOWS\r\n\tTEXTURE2D_SHADOW(u_SpotShadowMap);\r\n\tuniform mat4 u_SpotViewProjectMatrix;\r\n\tfloat sampleSpotShadowmap(vec4 shadowCoord)\r\n\t{\r\n\t\tshadowCoord.xyz /= shadowCoord.w;\r\n\t\tfloat attenuation = 1.0;\r\n\t\tshadowCoord.xy +=1.0;\r\n\t\tshadowCoord.xy/=2.0; \r\n\t\tif(shadowCoord.z > 0.0 && shadowCoord.z < 1.0)\r\n\t\t{\r\n\t\t\t#if defined(SHADOW_SPOT_SOFT_SHADOW_HIGH)\r\n\t\t\t\tattenuation = sampleShdowMapFiltered9(u_SpotShadowMap,shadowCoord.xyz,u_ShadowMapSize);\r\n\t\t\t#elif defined(SHADOW_SPOT_SOFT_SHADOW_LOW)\r\n\t\t\t\tattenuation = sampleShdowMapFiltered4(u_SpotShadowMap,shadowCoord.xyz,u_ShadowMapSize);\r\n\t\t\t#else\r\n\t\t\t\tattenuation = SAMPLE_TEXTURE2D_SHADOW(u_SpotShadowMap,shadowCoord.xyz);\r\n\t\t\t#endif\r\n\t\t\tattenuation = mix(1.0,attenuation,u_ShadowParams.y);//shadowParams.y:shadow strength\r\n\t\t}\r\n\t\treturn attenuation;\r\n\t}\r\n#endif\r\n\r\nvec3 applyShadowBias(vec3 positionWS, vec3 normalWS, vec3 lightDirection)\r\n{\r\n float invNdotL = 1.0 - clamp(dot(-lightDirection, normalWS),0.0,1.0);\r\n float scale = invNdotL * u_ShadowBias.y;\r\n\r\n // normal bias is negative since we want to apply an inset normal offset\r\n positionWS += -lightDirection * u_ShadowBias.xxx;\r\n positionWS += normalWS * vec3(scale);\r\n return positionWS;\r\n}\r\n";
  29667. var ShadowCasterVSGLSL = "#include \"Lighting.glsl\";\r\n#include \"Shadow.glsl\"\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\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#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 mat4 u_ViewProjection;\r\n\r\n#ifdef SHADOW\r\n\tuniform vec3 u_ShadowLightDirection;\r\n#endif\r\n\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\nvec4 shadowCasterVertex()\r\n{\r\n\tmat4 worldMat;\r\n\t#ifdef GPU_INSTANCE\r\n\t\tworldMat = a_WorldMat;\r\n\t#else\r\n\t\tworldMat = u_WorldMat;\r\n\t#endif\r\n\t\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\tworldMat = worldMat * skinTransform;\r\n\t#endif\r\n\r\n\tvec4 positionWS = worldMat * a_Position;\r\n\tvec3 normalWS = normalize(a_Normal*INVERSE_MAT(mat3(worldMat)));//if no normalize will cause precision problem\r\n\r\n\t#ifdef SHADOW\r\n\t\tpositionWS.xyz = applyShadowBias(positionWS.xyz,normalWS,u_ShadowLightDirection);\r\n\t#endif\r\n\r\n\tvec4 positionCS = u_ViewProjection * positionWS;\r\n\t#ifdef SHADOW_SPOT\r\n\t\tpositionCS.z = positionCS.z-u_ShadowBias.x/positionCS.w;\r\n\t#endif\r\n\tpositionCS.z = max(positionCS.z, 0.0);//min ndc z is 0.0\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 return positionCS;\r\n}\r\n";
  29668. var ShadowCasterFSGLSL = "// #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// #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\nvec4 shadowCasterFragment()\r\n{\r\n return vec4(0.0);\r\n // #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\n";
  29669. 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";
  29670. 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";
  29671. 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";
  29672. 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";
  29673. 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 ";
  29674. 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";
  29675. 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";
  29676. 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}";
  29677. 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\r\n#include \"Lighting.glsl\"\r\n\r\n\r\n\r\nvec3 NormalSampleToWorldSpace(vec4 normalMapSample) {\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 bumpedNormal = normalize(normalT);\r\n\r\n\treturn bumpedNormal;\r\n}\r\n\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\r\n\tvec3 normal1 = NormalSampleToWorldSpace(bumpColor1);\r\n\tvec3 normal2 = NormalSampleToWorldSpace(bumpColor2);\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\r\n";
  29678. 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}";
  29679. class ShaderInit3D {
  29680. constructor() {
  29681. }
  29682. static __init__() {
  29683. Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING = Shader3D.getDefineByName("LEGACYSINGLELIGHTING");
  29684. Shader3D.SHADERDEFINE_GRAPHICS_API_GLES2 = Shader3D.getDefineByName("GRAPHICS_API_GLES2");
  29685. Shader3D.SHADERDEFINE_GRAPHICS_API_GLES3 = Shader3D.getDefineByName("GRAPHICS_API_GLES3");
  29686. Shader3D.addInclude("Lighting.glsl", LightingGLSL);
  29687. Shader3D.addInclude("ShadowSampleTent.glsl", ShadowSampleTentGLSL);
  29688. Shader3D.addInclude("GlobalIllumination.glsl", GlobalIllumination);
  29689. Shader3D.addInclude("Shadow.glsl", ShadowGLSL);
  29690. Shader3D.addInclude("ShadowCasterVS.glsl", ShadowCasterVSGLSL);
  29691. Shader3D.addInclude("ShadowCasterFS.glsl", ShadowCasterFSGLSL);
  29692. Shader3D.addInclude("Colors.glsl", ColorsGLSL);
  29693. Shader3D.addInclude("Sampling.glsl", SamplingGLSL);
  29694. Shader3D.addInclude("StdLib.glsl", StdLibGLSL);
  29695. Shader3D.addInclude("PBRVSInput.glsl", PBRVSInput);
  29696. Shader3D.addInclude("PBRFSInput.glsl", PBRFSInput);
  29697. Shader3D.addInclude("LayaPBRBRDF.glsl", LayaPBRBRDF);
  29698. Shader3D.addInclude("PBRCore.glsl", PBRCore);
  29699. Shader3D.addInclude("PBRVertex.glsl", PBRVertex);
  29700. var attributeMap = {
  29701. 'a_Position': VertexMesh.MESH_POSITION0,
  29702. 'a_Color': VertexMesh.MESH_COLOR0,
  29703. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29704. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29705. 'a_Texcoord1': VertexMesh.MESH_TEXTURECOORDINATE1,
  29706. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29707. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29708. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  29709. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  29710. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  29711. };
  29712. var uniformMap = {
  29713. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29714. 'u_DiffuseTexture': Shader3D.PERIOD_MATERIAL,
  29715. 'u_SpecularTexture': Shader3D.PERIOD_MATERIAL,
  29716. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  29717. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29718. 'u_DiffuseColor': Shader3D.PERIOD_MATERIAL,
  29719. 'u_MaterialSpecular': Shader3D.PERIOD_MATERIAL,
  29720. 'u_Shininess': Shader3D.PERIOD_MATERIAL,
  29721. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29722. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29723. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29724. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  29725. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  29726. 'u_LightMapDirection': Shader3D.PERIOD_SPRITE,
  29727. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29728. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29729. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29730. 'u_View': Shader3D.PERIOD_CAMERA,
  29731. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  29732. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  29733. 'u_ReflectIntensity': Shader3D.PERIOD_SCENE,
  29734. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29735. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29736. 'u_FogColor': Shader3D.PERIOD_SCENE,
  29737. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  29738. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  29739. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  29740. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  29741. 'u_ShadowBias': Shader3D.PERIOD_SCENE,
  29742. 'u_ShadowLightDirection': Shader3D.PERIOD_SCENE,
  29743. 'u_ShadowMap': Shader3D.PERIOD_SCENE,
  29744. 'u_ShadowParams': Shader3D.PERIOD_SCENE,
  29745. 'u_ShadowSplitSpheres': Shader3D.PERIOD_SCENE,
  29746. 'u_ShadowMatrices': Shader3D.PERIOD_SCENE,
  29747. 'u_ShadowMapSize': Shader3D.PERIOD_SCENE,
  29748. 'u_SpotShadowMap': Shader3D.PERIOD_SCENE,
  29749. 'u_SpotViewProjectMatrix': Shader3D.PERIOD_SCENE,
  29750. 'u_ShadowLightPosition': Shader3D.PERIOD_SCENE,
  29751. 'u_AmbientSHAr': Shader3D.PERIOD_SCENE,
  29752. 'u_AmbientSHAg': Shader3D.PERIOD_SCENE,
  29753. 'u_AmbientSHAb': Shader3D.PERIOD_SCENE,
  29754. 'u_AmbientSHBr': Shader3D.PERIOD_SCENE,
  29755. 'u_AmbientSHBg': Shader3D.PERIOD_SCENE,
  29756. 'u_AmbientSHBb': Shader3D.PERIOD_SCENE,
  29757. 'u_AmbientSHC': Shader3D.PERIOD_SCENE,
  29758. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  29759. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  29760. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  29761. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  29762. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  29763. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  29764. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  29765. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  29766. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  29767. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  29768. };
  29769. var stateMap = {
  29770. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29771. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29772. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29773. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29774. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29775. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29776. };
  29777. var shader = Shader3D.add("BLINNPHONG", null, null, true);
  29778. var subShader = new SubShader(attributeMap, uniformMap);
  29779. shader.addSubShader(subShader);
  29780. subShader.addShaderPass(MeshBlinnPhongVS, MeshBlinnPhongPS, stateMap, "Forward");
  29781. var shaderPass = subShader.addShaderPass(MeshBlinnPhongShadowCasterVS, MeshBlinnPhongShadowCasterPS, stateMap, "ShadowCaster");
  29782. attributeMap = {
  29783. 'a_Position': VertexMesh.MESH_POSITION0,
  29784. 'a_Color': VertexMesh.MESH_COLOR0
  29785. };
  29786. uniformMap = {
  29787. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29788. 'u_Color': Shader3D.PERIOD_MATERIAL
  29789. };
  29790. stateMap = {
  29791. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29792. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29793. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29794. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29795. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29796. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29797. };
  29798. shader = Shader3D.add("LineShader");
  29799. subShader = new SubShader(attributeMap, uniformMap);
  29800. shader.addSubShader(subShader);
  29801. subShader.addShaderPass(lineVS, linePS, stateMap);
  29802. attributeMap = {
  29803. 'a_Position': VertexMesh.MESH_POSITION0,
  29804. 'a_Color': VertexMesh.MESH_COLOR0,
  29805. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29806. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29807. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29808. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0
  29809. };
  29810. uniformMap = {
  29811. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29812. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29813. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29814. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29815. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29816. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29817. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29818. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29819. 'u_FogColor': Shader3D.PERIOD_SCENE
  29820. };
  29821. stateMap = {
  29822. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29823. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29824. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29825. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29826. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29827. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29828. };
  29829. shader = Shader3D.add("Unlit", null, null, true);
  29830. subShader = new SubShader(attributeMap, uniformMap);
  29831. shader.addSubShader(subShader);
  29832. subShader.addShaderPass(UnlitVS, UnlitPS, stateMap);
  29833. attributeMap = {
  29834. 'a_Position': VertexMesh.MESH_POSITION0,
  29835. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29836. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29837. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29838. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0
  29839. };
  29840. uniformMap = {
  29841. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29842. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29843. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29844. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29845. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29846. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29847. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29848. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29849. 'u_FogColor': 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("Effect", null, null, true);
  29860. subShader = new SubShader(attributeMap, uniformMap);
  29861. shader.addSubShader(subShader);
  29862. subShader.addShaderPass(EffectVS, EffectPS, stateMap);
  29863. attributeMap = {
  29864. 'a_CornerTextureCoordinate': VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0,
  29865. 'a_MeshPosition': VertexShuriKenParticle.PARTICLE_POSITION0,
  29866. 'a_MeshColor': VertexShuriKenParticle.PARTICLE_COLOR0,
  29867. 'a_MeshTextureCoordinate': VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0,
  29868. 'a_ShapePositionStartLifeTime': VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME,
  29869. 'a_DirectionTime': VertexShuriKenParticle.PARTICLE_DIRECTIONTIME,
  29870. 'a_StartColor': VertexShuriKenParticle.PARTICLE_STARTCOLOR0,
  29871. 'a_EndColor': VertexShuriKenParticle.PARTICLE_ENDCOLOR0,
  29872. 'a_StartSize': VertexShuriKenParticle.PARTICLE_STARTSIZE,
  29873. 'a_StartRotation0': VertexShuriKenParticle.PARTICLE_STARTROTATION,
  29874. 'a_StartSpeed': VertexShuriKenParticle.PARTICLE_STARTSPEED,
  29875. 'a_Random0': VertexShuriKenParticle.PARTICLE_RANDOM0,
  29876. 'a_Random1': VertexShuriKenParticle.PARTICLE_RANDOM1,
  29877. 'a_SimulationWorldPostion': VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION,
  29878. 'a_SimulationWorldRotation': VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION
  29879. };
  29880. uniformMap = {
  29881. 'u_Tintcolor': Shader3D.PERIOD_MATERIAL,
  29882. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29883. 'u_texture': Shader3D.PERIOD_MATERIAL,
  29884. 'u_WorldPosition': Shader3D.PERIOD_SPRITE,
  29885. 'u_WorldRotation': Shader3D.PERIOD_SPRITE,
  29886. 'u_PositionScale': Shader3D.PERIOD_SPRITE,
  29887. 'u_SizeScale': Shader3D.PERIOD_SPRITE,
  29888. 'u_ScalingMode': Shader3D.PERIOD_SPRITE,
  29889. 'u_Gravity': Shader3D.PERIOD_SPRITE,
  29890. 'u_ThreeDStartRotation': Shader3D.PERIOD_SPRITE,
  29891. 'u_StretchedBillboardLengthScale': Shader3D.PERIOD_SPRITE,
  29892. 'u_StretchedBillboardSpeedScale': Shader3D.PERIOD_SPRITE,
  29893. 'u_SimulationSpace': Shader3D.PERIOD_SPRITE,
  29894. 'u_CurrentTime': Shader3D.PERIOD_SPRITE,
  29895. 'u_ColorOverLifeGradientAlphas': Shader3D.PERIOD_SPRITE,
  29896. 'u_ColorOverLifeGradientColors': Shader3D.PERIOD_SPRITE,
  29897. 'u_MaxColorOverLifeGradientAlphas': Shader3D.PERIOD_SPRITE,
  29898. 'u_MaxColorOverLifeGradientColors': Shader3D.PERIOD_SPRITE,
  29899. 'u_VOLVelocityConst': Shader3D.PERIOD_SPRITE,
  29900. 'u_VOLVelocityGradientX': Shader3D.PERIOD_SPRITE,
  29901. 'u_VOLVelocityGradientY': Shader3D.PERIOD_SPRITE,
  29902. 'u_VOLVelocityGradientZ': Shader3D.PERIOD_SPRITE,
  29903. 'u_VOLVelocityConstMax': Shader3D.PERIOD_SPRITE,
  29904. 'u_VOLVelocityGradientMaxX': Shader3D.PERIOD_SPRITE,
  29905. 'u_VOLVelocityGradientMaxY': Shader3D.PERIOD_SPRITE,
  29906. 'u_VOLVelocityGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29907. 'u_VOLSpaceType': Shader3D.PERIOD_SPRITE,
  29908. 'u_SOLSizeGradient': Shader3D.PERIOD_SPRITE,
  29909. 'u_SOLSizeGradientX': Shader3D.PERIOD_SPRITE,
  29910. 'u_SOLSizeGradientY': Shader3D.PERIOD_SPRITE,
  29911. 'u_SOLSizeGradientZ': Shader3D.PERIOD_SPRITE,
  29912. 'u_SOLSizeGradientMax': Shader3D.PERIOD_SPRITE,
  29913. 'u_SOLSizeGradientMaxX': Shader3D.PERIOD_SPRITE,
  29914. 'u_SOLSizeGradientMaxY': Shader3D.PERIOD_SPRITE,
  29915. 'u_SOLSizeGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29916. 'u_ROLAngularVelocityConst': Shader3D.PERIOD_SPRITE,
  29917. 'u_ROLAngularVelocityConstSeprarate': Shader3D.PERIOD_SPRITE,
  29918. 'u_ROLAngularVelocityGradient': Shader3D.PERIOD_SPRITE,
  29919. 'u_ROLAngularVelocityGradientX': Shader3D.PERIOD_SPRITE,
  29920. 'u_ROLAngularVelocityGradientY': Shader3D.PERIOD_SPRITE,
  29921. 'u_ROLAngularVelocityGradientZ': Shader3D.PERIOD_SPRITE,
  29922. 'u_ROLAngularVelocityConstMax': Shader3D.PERIOD_SPRITE,
  29923. 'u_ROLAngularVelocityConstMaxSeprarate': Shader3D.PERIOD_SPRITE,
  29924. 'u_ROLAngularVelocityGradientMax': Shader3D.PERIOD_SPRITE,
  29925. 'u_ROLAngularVelocityGradientMaxX': Shader3D.PERIOD_SPRITE,
  29926. 'u_ROLAngularVelocityGradientMaxY': Shader3D.PERIOD_SPRITE,
  29927. 'u_ROLAngularVelocityGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29928. 'u_ROLAngularVelocityGradientMaxW': Shader3D.PERIOD_SPRITE,
  29929. 'u_TSACycles': Shader3D.PERIOD_SPRITE,
  29930. 'u_TSASubUVLength': Shader3D.PERIOD_SPRITE,
  29931. 'u_TSAGradientUVs': Shader3D.PERIOD_SPRITE,
  29932. 'u_TSAMaxGradientUVs': Shader3D.PERIOD_SPRITE,
  29933. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29934. 'u_CameraDirection': Shader3D.PERIOD_CAMERA,
  29935. 'u_CameraUp': Shader3D.PERIOD_CAMERA,
  29936. 'u_View': Shader3D.PERIOD_CAMERA,
  29937. 'u_Projection': Shader3D.PERIOD_CAMERA,
  29938. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29939. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29940. 'u_FogColor': Shader3D.PERIOD_SCENE
  29941. };
  29942. stateMap = {
  29943. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29944. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29945. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29946. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29947. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29948. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29949. };
  29950. shader = Shader3D.add("PARTICLESHURIKEN");
  29951. subShader = new SubShader(attributeMap, uniformMap);
  29952. shader.addSubShader(subShader);
  29953. subShader.addShaderPass(ParticleShuriKenVS, ParticleShuriKenPS, stateMap);
  29954. attributeMap = {
  29955. 'a_Position': VertexMesh.MESH_POSITION0
  29956. };
  29957. uniformMap = {
  29958. 'u_TintColor': Shader3D.PERIOD_MATERIAL,
  29959. 'u_Exposure': Shader3D.PERIOD_MATERIAL,
  29960. 'u_Rotation': Shader3D.PERIOD_MATERIAL,
  29961. 'u_CubeTexture': Shader3D.PERIOD_MATERIAL,
  29962. 'u_ViewProjection': Shader3D.PERIOD_CAMERA
  29963. };
  29964. shader = Shader3D.add("SkyBox");
  29965. subShader = new SubShader(attributeMap, uniformMap);
  29966. shader.addSubShader(subShader);
  29967. subShader.addShaderPass(SkyBoxVS, SkyBoxPS);
  29968. attributeMap = {
  29969. 'a_Position': VertexMesh.MESH_POSITION0
  29970. };
  29971. uniformMap = {
  29972. 'u_SunSize': Shader3D.PERIOD_MATERIAL,
  29973. 'u_SunSizeConvergence': Shader3D.PERIOD_MATERIAL,
  29974. 'u_AtmosphereThickness': Shader3D.PERIOD_MATERIAL,
  29975. 'u_SkyTint': Shader3D.PERIOD_MATERIAL,
  29976. 'u_GroundTint': Shader3D.PERIOD_MATERIAL,
  29977. 'u_Exposure': Shader3D.PERIOD_MATERIAL,
  29978. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  29979. 'u_SunLight.direction': Shader3D.PERIOD_SCENE,
  29980. 'u_SunLight.color': Shader3D.PERIOD_SCENE,
  29981. };
  29982. shader = Shader3D.add("SkyBoxProcedural");
  29983. subShader = new SubShader(attributeMap, uniformMap);
  29984. shader.addSubShader(subShader);
  29985. subShader.addShaderPass(SkyBoxProceduralVS, SkyBoxProceduralPS);
  29986. attributeMap = {
  29987. 'a_Position': VertexMesh.MESH_POSITION0,
  29988. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29989. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0
  29990. };
  29991. uniformMap = {
  29992. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29993. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29994. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29995. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29996. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29997. 'u_View': Shader3D.PERIOD_CAMERA,
  29998. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  29999. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  30000. 'u_SplatAlphaTexture': Shader3D.PERIOD_MATERIAL,
  30001. 'u_DiffuseTexture1': Shader3D.PERIOD_MATERIAL,
  30002. 'u_DiffuseTexture2': Shader3D.PERIOD_MATERIAL,
  30003. 'u_DiffuseTexture3': Shader3D.PERIOD_MATERIAL,
  30004. 'u_DiffuseTexture4': Shader3D.PERIOD_MATERIAL,
  30005. 'u_DiffuseTexture5': Shader3D.PERIOD_MATERIAL,
  30006. 'u_DiffuseScaleOffset1': Shader3D.PERIOD_MATERIAL,
  30007. 'u_DiffuseScaleOffset2': Shader3D.PERIOD_MATERIAL,
  30008. 'u_DiffuseScaleOffset3': Shader3D.PERIOD_MATERIAL,
  30009. 'u_DiffuseScaleOffset4': Shader3D.PERIOD_MATERIAL,
  30010. 'u_DiffuseScaleOffset5': Shader3D.PERIOD_MATERIAL,
  30011. 'u_FogStart': Shader3D.PERIOD_SCENE,
  30012. 'u_FogRange': Shader3D.PERIOD_SCENE,
  30013. 'u_FogColor': Shader3D.PERIOD_SCENE,
  30014. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  30015. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  30016. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  30017. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  30018. 'u_ShadowMap': Shader3D.PERIOD_SCENE,
  30019. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  30020. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  30021. 'u_ShadowSplitSpheres': Shader3D.PERIOD_SCENE,
  30022. 'u_ShadowMatrices': Shader3D.PERIOD_SCENE,
  30023. 'u_ShadowMapSize': Shader3D.PERIOD_SCENE,
  30024. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  30025. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  30026. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  30027. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  30028. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  30029. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  30030. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  30031. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  30032. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  30033. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  30034. };
  30035. stateMap = {
  30036. 's_Cull': Shader3D.RENDER_STATE_CULL,
  30037. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  30038. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  30039. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  30040. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  30041. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  30042. };
  30043. shader = Shader3D.add("ExtendTerrain");
  30044. subShader = new SubShader(attributeMap, uniformMap);
  30045. shader.addSubShader(subShader);
  30046. subShader.addShaderPass(extendTerrainVS, extendTerrainPS, stateMap);
  30047. attributeMap = {
  30048. 'a_Position': VertexTrail.TRAIL_POSITION0,
  30049. 'a_OffsetVector': VertexTrail.TRAIL_OFFSETVECTOR,
  30050. 'a_Texcoord0X': VertexTrail.TRAIL_TEXTURECOORDINATE0X,
  30051. 'a_Texcoord0Y': VertexTrail.TRAIL_TEXTURECOORDINATE0Y,
  30052. 'a_BirthTime': VertexTrail.TRAIL_TIME0,
  30053. 'a_Color': VertexTrail.TRAIL_COLOR
  30054. };
  30055. uniformMap = {
  30056. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  30057. 'u_View': Shader3D.PERIOD_CAMERA,
  30058. 'u_Projection': Shader3D.PERIOD_CAMERA,
  30059. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  30060. 'u_MainTexture': Shader3D.PERIOD_MATERIAL,
  30061. 'u_MainColor': Shader3D.PERIOD_MATERIAL,
  30062. 'u_CurTime': Shader3D.PERIOD_SPRITE,
  30063. 'u_LifeTime': Shader3D.PERIOD_SPRITE,
  30064. 'u_WidthCurve': Shader3D.PERIOD_SPRITE,
  30065. 'u_WidthCurveKeyLength': Shader3D.PERIOD_SPRITE,
  30066. 'u_GradientColorkey': Shader3D.PERIOD_SPRITE,
  30067. 'u_GradientAlphakey': Shader3D.PERIOD_SPRITE
  30068. };
  30069. stateMap = {
  30070. 's_Cull': Shader3D.RENDER_STATE_CULL,
  30071. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  30072. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  30073. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  30074. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  30075. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  30076. };
  30077. shader = Shader3D.add("Trail");
  30078. subShader = new SubShader(attributeMap, uniformMap);
  30079. shader.addSubShader(subShader);
  30080. subShader.addShaderPass(TrailVS, TrailPS, stateMap);
  30081. attributeMap = {
  30082. 'a_Position': VertexMesh.MESH_POSITION0,
  30083. 'a_Normal': VertexMesh.MESH_NORMAL0,
  30084. 'a_Tangent0': VertexMesh.MESH_TANGENT0
  30085. };
  30086. uniformMap = {
  30087. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  30088. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  30089. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  30090. 'u_Time': Shader3D.PERIOD_SCENE,
  30091. 'u_MainTexture': Shader3D.PERIOD_MATERIAL,
  30092. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  30093. 'u_HorizonColor': Shader3D.PERIOD_MATERIAL,
  30094. 'u_WaveScale': Shader3D.PERIOD_MATERIAL,
  30095. 'u_WaveSpeed': Shader3D.PERIOD_MATERIAL
  30096. };
  30097. shader = Shader3D.add("WaterPrimary");
  30098. subShader = new SubShader(attributeMap, uniformMap);
  30099. shader.addSubShader(subShader);
  30100. subShader.addShaderPass(WaterPrimaryVS, WaterPrimaryPS);
  30101. attributeMap = {
  30102. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  30103. };
  30104. uniformMap = {
  30105. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  30106. 'u_OffsetScale': Shader3D.PERIOD_MATERIAL
  30107. };
  30108. shader = Shader3D.add("BlitScreen");
  30109. subShader = new SubShader(attributeMap, uniformMap);
  30110. shader.addSubShader(subShader);
  30111. var shaderPass = subShader.addShaderPass(BlitScreenVS, BlitScreenPS);
  30112. var renderState = shaderPass.renderState;
  30113. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30114. renderState.depthWrite = false;
  30115. renderState.cull = RenderState.CULL_NONE;
  30116. renderState.blend = RenderState.BLEND_DISABLE;
  30117. attributeMap = {
  30118. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  30119. };
  30120. uniformMap = {
  30121. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  30122. 'u_BloomTex': Shader3D.PERIOD_MATERIAL,
  30123. 'u_AutoExposureTex': Shader3D.PERIOD_MATERIAL,
  30124. 'u_MainTex_TexelSize': Shader3D.PERIOD_MATERIAL,
  30125. 'u_SampleScale': Shader3D.PERIOD_MATERIAL,
  30126. 'u_Threshold': Shader3D.PERIOD_MATERIAL,
  30127. 'u_Params': Shader3D.PERIOD_MATERIAL
  30128. };
  30129. shader = Shader3D.add("PostProcessBloom");
  30130. subShader = new SubShader(attributeMap, uniformMap);
  30131. shader.addSubShader(subShader);
  30132. shaderPass = subShader.addShaderPass(BloomVS, BloomPrefilter13PS);
  30133. renderState = shaderPass.renderState;
  30134. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30135. renderState.depthWrite = false;
  30136. renderState.cull = RenderState.CULL_NONE;
  30137. renderState.blend = RenderState.BLEND_DISABLE;
  30138. subShader = new SubShader(attributeMap, uniformMap);
  30139. shader.addSubShader(subShader);
  30140. shaderPass = subShader.addShaderPass(BloomVS, BloomPrefilter4PS);
  30141. renderState = shaderPass.renderState;
  30142. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30143. renderState.depthWrite = false;
  30144. renderState.cull = RenderState.CULL_NONE;
  30145. renderState.blend = RenderState.BLEND_DISABLE;
  30146. subShader = new SubShader(attributeMap, uniformMap);
  30147. shader.addSubShader(subShader);
  30148. shaderPass = subShader.addShaderPass(BloomVS, BloomDownsample13PS);
  30149. renderState = shaderPass.renderState;
  30150. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30151. renderState.depthWrite = false;
  30152. renderState.cull = RenderState.CULL_NONE;
  30153. renderState.blend = RenderState.BLEND_DISABLE;
  30154. subShader = new SubShader(attributeMap, uniformMap);
  30155. shader.addSubShader(subShader);
  30156. shaderPass = subShader.addShaderPass(BloomVS, BloomDownsample4PS);
  30157. renderState = shaderPass.renderState;
  30158. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30159. renderState.depthWrite = false;
  30160. renderState.cull = RenderState.CULL_NONE;
  30161. renderState.blend = RenderState.BLEND_DISABLE;
  30162. subShader = new SubShader(attributeMap, uniformMap);
  30163. shader.addSubShader(subShader);
  30164. shaderPass = subShader.addShaderPass(BloomVS, BloomUpsampleTentPS);
  30165. renderState = shaderPass.renderState;
  30166. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30167. renderState.depthWrite = false;
  30168. renderState.cull = RenderState.CULL_NONE;
  30169. renderState.blend = RenderState.BLEND_DISABLE;
  30170. subShader = new SubShader(attributeMap, uniformMap);
  30171. shader.addSubShader(subShader);
  30172. shaderPass = subShader.addShaderPass(BloomVS, BloomUpsampleBoxPS);
  30173. renderState = shaderPass.renderState;
  30174. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30175. renderState.depthWrite = false;
  30176. renderState.cull = RenderState.CULL_NONE;
  30177. renderState.blend = RenderState.BLEND_DISABLE;
  30178. attributeMap = {
  30179. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  30180. };
  30181. uniformMap = {
  30182. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  30183. 'u_BloomTex': Shader3D.PERIOD_MATERIAL,
  30184. 'u_AutoExposureTex': Shader3D.PERIOD_MATERIAL,
  30185. 'u_Bloom_DirtTileOffset': Shader3D.PERIOD_MATERIAL,
  30186. 'u_Bloom_DirtTex': Shader3D.PERIOD_MATERIAL,
  30187. 'u_BloomTex_TexelSize': Shader3D.PERIOD_MATERIAL,
  30188. 'u_Bloom_Settings': Shader3D.PERIOD_MATERIAL,
  30189. 'u_Bloom_Color': Shader3D.PERIOD_MATERIAL
  30190. };
  30191. shader = Shader3D.add("PostProcessComposite");
  30192. subShader = new SubShader(attributeMap, uniformMap);
  30193. shader.addSubShader(subShader);
  30194. shaderPass = subShader.addShaderPass(CompositeVS, CompositePS);
  30195. renderState = shaderPass.renderState;
  30196. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30197. renderState.depthWrite = false;
  30198. renderState.cull = RenderState.CULL_NONE;
  30199. renderState.blend = RenderState.BLEND_DISABLE;
  30200. }
  30201. }
  30202. class DirectionLight extends LightSprite {
  30203. constructor() {
  30204. super();
  30205. this._direction = new Vector3();
  30206. this._shadowCascadesMode = exports.ShadowCascadesMode.NoCascades;
  30207. this._shadowTwoCascadeSplits = 1.0 / 3.0;
  30208. this._shadowFourCascadeSplits = new Vector3(1.0 / 15, 3.0 / 15.0, 7.0 / 15.0);
  30209. this._lightType = exports.LightType.Directional;
  30210. }
  30211. get shadowCascadesMode() {
  30212. return this._shadowCascadesMode;
  30213. }
  30214. set shadowCascadesMode(value) {
  30215. this._shadowCascadesMode = value;
  30216. }
  30217. get shadowTwoCascadeSplits() {
  30218. return this._shadowTwoCascadeSplits;
  30219. }
  30220. set shadowTwoCascadeSplits(value) {
  30221. this._shadowTwoCascadeSplits = value;
  30222. }
  30223. get shadowFourCascadeSplits() {
  30224. return this._shadowFourCascadeSplits;
  30225. }
  30226. set shadowFourCascadeSplits(value) {
  30227. if (value.x > value.y || value.y > value.z || value.z > 1.0)
  30228. throw "DiretionLight:Invalid value.";
  30229. value.cloneTo(this._shadowFourCascadeSplits);
  30230. }
  30231. _addToLightQueue() {
  30232. this._scene._directionLights.add(this);
  30233. }
  30234. _removeFromLightQueue() {
  30235. this._scene._directionLights.remove(this);
  30236. }
  30237. }
  30238. class PointLight extends LightSprite {
  30239. constructor() {
  30240. super();
  30241. this._range = 6.0;
  30242. this._lightType = exports.LightType.Point;
  30243. }
  30244. get range() {
  30245. return this._range;
  30246. }
  30247. set range(value) {
  30248. this._range = value;
  30249. }
  30250. _addToLightQueue() {
  30251. this._scene._pointLights.add(this);
  30252. }
  30253. _removeFromLightQueue() {
  30254. this._scene._pointLights.remove(this);
  30255. }
  30256. _parse(data, spriteMap) {
  30257. super._parse(data, spriteMap);
  30258. this.range = data.range;
  30259. }
  30260. }
  30261. class SpotLight extends LightSprite {
  30262. constructor() {
  30263. super();
  30264. this._spotAngle = 30.0;
  30265. this._range = 10.0;
  30266. this._direction = new Vector3();
  30267. this._lightType = exports.LightType.Spot;
  30268. }
  30269. get spotAngle() {
  30270. return this._spotAngle;
  30271. }
  30272. set spotAngle(value) {
  30273. this._spotAngle = Math.max(Math.min(value, 179), 0);
  30274. }
  30275. get range() {
  30276. return this._range;
  30277. }
  30278. set range(value) {
  30279. this._range = value;
  30280. }
  30281. _addToLightQueue() {
  30282. this._scene._spotLights.add(this);
  30283. }
  30284. _removeFromLightQueue() {
  30285. this._scene._spotLights.remove(this);
  30286. }
  30287. _parse(data, spriteMap) {
  30288. super._parse(data, spriteMap);
  30289. this.range = data.range;
  30290. this.spotAngle = data.spotAngle;
  30291. }
  30292. }
  30293. class Scene3DUtils {
  30294. static _createSprite3DInstance(nodeData, spriteMap, outBatchSprites) {
  30295. var node;
  30296. switch (nodeData.type) {
  30297. case "Scene3D":
  30298. node = new Scene3D();
  30299. break;
  30300. case "Sprite3D":
  30301. node = new Sprite3D();
  30302. break;
  30303. case "MeshSprite3D":
  30304. node = new MeshSprite3D();
  30305. (outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(node));
  30306. break;
  30307. case "SkinnedMeshSprite3D":
  30308. node = new SkinnedMeshSprite3D();
  30309. break;
  30310. case "ShuriKenParticle3D":
  30311. node = new ShuriKenParticle3D();
  30312. break;
  30313. case "Camera":
  30314. node = new Camera();
  30315. break;
  30316. case "DirectionLight":
  30317. node = new DirectionLight();
  30318. break;
  30319. case "PointLight":
  30320. node = new PointLight();
  30321. break;
  30322. case "SpotLight":
  30323. node = new SpotLight();
  30324. break;
  30325. case "TrailSprite3D":
  30326. node = new TrailSprite3D();
  30327. break;
  30328. default:
  30329. throw new Error("Utils3D:unidentified class type in (.lh) file.");
  30330. }
  30331. var childData = nodeData.child;
  30332. if (childData) {
  30333. for (var i = 0, n = childData.length; i < n; i++) {
  30334. var child = Scene3DUtils._createSprite3DInstance(childData[i], spriteMap, outBatchSprites);
  30335. node.addChild(child);
  30336. }
  30337. }
  30338. spriteMap[nodeData.instanceID] = node;
  30339. return node;
  30340. }
  30341. static _createComponentInstance(nodeData, spriteMap, interactMap) {
  30342. var node = spriteMap[nodeData.instanceID];
  30343. node._parse(nodeData.props, spriteMap);
  30344. var childData = nodeData.child;
  30345. if (childData) {
  30346. for (var i = 0, n = childData.length; i < n; i++)
  30347. Scene3DUtils._createComponentInstance(childData[i], spriteMap, interactMap);
  30348. }
  30349. var componentsData = nodeData.components;
  30350. if (componentsData) {
  30351. for (var j = 0, m = componentsData.length; j < m; j++) {
  30352. var data = componentsData[j];
  30353. var clas = Laya.ClassUtils.getRegClass(data.type);
  30354. if (clas) {
  30355. var component = node.addComponent(clas);
  30356. component._parse(data, interactMap);
  30357. }
  30358. else {
  30359. console.warn("Unkown component type.");
  30360. }
  30361. }
  30362. }
  30363. }
  30364. static _createNodeByJson02(nodeData, outBatchSprites) {
  30365. var spriteMap = {};
  30366. var interactMap = { component: [], data: [] };
  30367. var node = Scene3DUtils._createSprite3DInstance(nodeData, spriteMap, outBatchSprites);
  30368. Scene3DUtils._createComponentInstance(nodeData, spriteMap, interactMap);
  30369. Scene3DUtils._createInteractInstance(interactMap, spriteMap);
  30370. return node;
  30371. }
  30372. static _createInteractInstance(interatMap, spriteMap) {
  30373. var components = interatMap.component;
  30374. var data = interatMap.data;
  30375. for (var i = 0, n = components.length; i < n; i++) {
  30376. components[i]._parseInteractive(data[i], spriteMap);
  30377. }
  30378. }
  30379. static _parse(data, propertyParams = null, constructParams = null) {
  30380. var json = data.data;
  30381. var outBatchSprits = [];
  30382. var sprite;
  30383. switch (data.version) {
  30384. case "LAYAHIERARCHY:02":
  30385. sprite = Scene3DUtils._createNodeByJson02(json, outBatchSprits);
  30386. break;
  30387. default:
  30388. sprite = Scene3DUtils._createNodeByJson(json, outBatchSprits);
  30389. }
  30390. StaticBatchManager.combine(sprite, outBatchSprits);
  30391. return sprite;
  30392. }
  30393. static _parseScene(data, propertyParams = null, constructParams = null) {
  30394. var json = data.data;
  30395. var outBatchSprits = [];
  30396. var scene;
  30397. switch (data.version) {
  30398. case "LAYASCENE3D:02":
  30399. scene = Scene3DUtils._createNodeByJson02(json, outBatchSprits);
  30400. break;
  30401. default:
  30402. scene = Scene3DUtils._createNodeByJson(json, outBatchSprits);
  30403. }
  30404. StaticBatchManager.combine(null, outBatchSprits);
  30405. return scene;
  30406. }
  30407. static _createNodeByJson(nodeData, outBatchSprites) {
  30408. var node;
  30409. switch (nodeData.type) {
  30410. case "Scene3D":
  30411. node = new Scene3D();
  30412. break;
  30413. case "Sprite3D":
  30414. node = new Sprite3D();
  30415. break;
  30416. case "MeshSprite3D":
  30417. node = new MeshSprite3D();
  30418. (outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(node));
  30419. break;
  30420. case "SkinnedMeshSprite3D":
  30421. node = new SkinnedMeshSprite3D();
  30422. break;
  30423. case "ShuriKenParticle3D":
  30424. node = new ShuriKenParticle3D();
  30425. break;
  30426. case "Camera":
  30427. node = new Camera();
  30428. break;
  30429. case "DirectionLight":
  30430. node = new DirectionLight();
  30431. break;
  30432. case "PointLight":
  30433. node = new PointLight();
  30434. break;
  30435. case "SpotLight":
  30436. node = new SpotLight();
  30437. break;
  30438. case "TrailSprite3D":
  30439. node = new TrailSprite3D();
  30440. break;
  30441. default:
  30442. throw new Error("Utils3D:unidentified class type in (.lh) file.");
  30443. }
  30444. var childData = nodeData.child;
  30445. if (childData) {
  30446. for (var i = 0, n = childData.length; i < n; i++) {
  30447. var child = Scene3DUtils._createNodeByJson(childData[i], outBatchSprites);
  30448. node.addChild(child);
  30449. }
  30450. }
  30451. var componentsData = nodeData.components;
  30452. if (componentsData) {
  30453. for (var j = 0, m = componentsData.length; j < m; j++) {
  30454. var data = componentsData[j];
  30455. var clas = Laya.ClassUtils.getRegClass(data.type);
  30456. if (clas) {
  30457. var component = node.addComponent(clas);
  30458. component._parse(data);
  30459. }
  30460. else {
  30461. console.warn("Unkown component type.");
  30462. }
  30463. }
  30464. }
  30465. node._parse(nodeData.props, null);
  30466. return node;
  30467. }
  30468. }
  30469. class LoadModelV04 {
  30470. static parse(readData, version, mesh, subMeshes) {
  30471. LoadModelV04._mesh = mesh;
  30472. LoadModelV04._subMeshes = subMeshes;
  30473. LoadModelV04._version = version;
  30474. LoadModelV04._readData = readData;
  30475. LoadModelV04.READ_DATA();
  30476. LoadModelV04.READ_BLOCK();
  30477. LoadModelV04.READ_STRINGS();
  30478. for (var i = 0, n = LoadModelV04._BLOCK.count; i < n; i++) {
  30479. LoadModelV04._readData.pos = LoadModelV04._BLOCK.blockStarts[i];
  30480. var index = LoadModelV04._readData.getUint16();
  30481. var blockName = LoadModelV04._strings[index];
  30482. var fn = LoadModelV04["READ_" + blockName];
  30483. if (fn == null)
  30484. throw new Error("model file err,no this function:" + index + " " + blockName);
  30485. else
  30486. fn.call(null);
  30487. }
  30488. LoadModelV04._strings.length = 0;
  30489. LoadModelV04._readData = null;
  30490. LoadModelV04._version = null;
  30491. LoadModelV04._mesh = null;
  30492. LoadModelV04._subMeshes = null;
  30493. }
  30494. static _readString() {
  30495. return LoadModelV04._strings[LoadModelV04._readData.getUint16()];
  30496. }
  30497. static READ_DATA() {
  30498. LoadModelV04._DATA.offset = LoadModelV04._readData.getUint32();
  30499. LoadModelV04._DATA.size = LoadModelV04._readData.getUint32();
  30500. }
  30501. static READ_BLOCK() {
  30502. var count = LoadModelV04._BLOCK.count = LoadModelV04._readData.getUint16();
  30503. var blockStarts = LoadModelV04._BLOCK.blockStarts = [];
  30504. var blockLengths = LoadModelV04._BLOCK.blockLengths = [];
  30505. for (var i = 0; i < count; i++) {
  30506. blockStarts.push(LoadModelV04._readData.getUint32());
  30507. blockLengths.push(LoadModelV04._readData.getUint32());
  30508. }
  30509. }
  30510. static READ_STRINGS() {
  30511. var offset = LoadModelV04._readData.getUint32();
  30512. var count = LoadModelV04._readData.getUint16();
  30513. var prePos = LoadModelV04._readData.pos;
  30514. LoadModelV04._readData.pos = offset + LoadModelV04._DATA.offset;
  30515. for (var i = 0; i < count; i++)
  30516. LoadModelV04._strings[i] = LoadModelV04._readData.readUTFString();
  30517. LoadModelV04._readData.pos = prePos;
  30518. }
  30519. static READ_MESH() {
  30520. var gl = Laya.LayaGL.instance;
  30521. var name = LoadModelV04._readString();
  30522. var arrayBuffer = LoadModelV04._readData.__getBuffer();
  30523. var i;
  30524. var memorySize = 0;
  30525. var vertexBufferCount = LoadModelV04._readData.getInt16();
  30526. var offset = LoadModelV04._DATA.offset;
  30527. for (i = 0; i < vertexBufferCount; i++) {
  30528. var vbStart = offset + LoadModelV04._readData.getUint32();
  30529. var vbLength = LoadModelV04._readData.getUint32();
  30530. var vbArrayBuffer = arrayBuffer.slice(vbStart, vbStart + vbLength);
  30531. var vbDatas = new Float32Array(vbArrayBuffer);
  30532. var bufferAttribute = LoadModelV04._readString();
  30533. var vertexDeclaration;
  30534. switch (LoadModelV04._version) {
  30535. case "LAYAMODEL:0301":
  30536. case "LAYAMODEL:0400":
  30537. vertexDeclaration = VertexMesh.getVertexDeclaration(bufferAttribute);
  30538. break;
  30539. case "LAYAMODEL:0401":
  30540. vertexDeclaration = VertexMesh.getVertexDeclaration(bufferAttribute, false);
  30541. break;
  30542. default:
  30543. throw new Error("LoadModelV03: unknown version.");
  30544. }
  30545. if (!vertexDeclaration)
  30546. throw new Error("LoadModelV03: unknown vertexDeclaration.");
  30547. var vertexBuffer = new VertexBuffer3D(vbDatas.length * 4, gl.STATIC_DRAW, true);
  30548. vertexBuffer.vertexDeclaration = vertexDeclaration;
  30549. vertexBuffer.setData(vbDatas.buffer);
  30550. LoadModelV04._mesh._vertexBuffer = vertexBuffer;
  30551. LoadModelV04._mesh._vertexCount += vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  30552. memorySize += vbDatas.length * 4;
  30553. }
  30554. var ibStart = offset + LoadModelV04._readData.getUint32();
  30555. var ibLength = LoadModelV04._readData.getUint32();
  30556. var ibDatas = new Uint16Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  30557. var indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, ibLength / 2, gl.STATIC_DRAW, true);
  30558. indexBuffer.setData(ibDatas);
  30559. LoadModelV04._mesh._indexBuffer = indexBuffer;
  30560. memorySize += indexBuffer.indexCount * 2;
  30561. LoadModelV04._mesh._setBuffer(LoadModelV04._mesh._vertexBuffer, indexBuffer);
  30562. LoadModelV04._mesh._setCPUMemory(memorySize);
  30563. LoadModelV04._mesh._setGPUMemory(memorySize);
  30564. var boneNames = LoadModelV04._mesh._boneNames = [];
  30565. var boneCount = LoadModelV04._readData.getUint16();
  30566. boneNames.length = boneCount;
  30567. for (i = 0; i < boneCount; i++)
  30568. boneNames[i] = LoadModelV04._strings[LoadModelV04._readData.getUint16()];
  30569. LoadModelV04._readData.pos += 8;
  30570. var bindPoseDataStart = LoadModelV04._readData.getUint32();
  30571. var bindPoseDataLength = LoadModelV04._readData.getUint32();
  30572. var bindPoseDatas = new Float32Array(arrayBuffer.slice(offset + bindPoseDataStart, offset + bindPoseDataStart + bindPoseDataLength));
  30573. var bindPoseFloatCount = bindPoseDatas.length;
  30574. var bindPoseBuffer = LoadModelV04._mesh._inverseBindPosesBuffer = new ArrayBuffer(bindPoseFloatCount * 4);
  30575. LoadModelV04._mesh._inverseBindPoses = [];
  30576. for (i = 0; i < bindPoseFloatCount; i += 16) {
  30577. 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));
  30578. LoadModelV04._mesh._inverseBindPoses[i / 16] = inverseGlobalBindPose;
  30579. }
  30580. return true;
  30581. }
  30582. static READ_SUBMESH() {
  30583. var arrayBuffer = LoadModelV04._readData.__getBuffer();
  30584. var subMesh = new SubMesh(LoadModelV04._mesh);
  30585. LoadModelV04._readData.getInt16();
  30586. LoadModelV04._readData.getUint32();
  30587. LoadModelV04._readData.getUint32();
  30588. var ibStart = LoadModelV04._readData.getUint32();
  30589. var ibCount = LoadModelV04._readData.getUint32();
  30590. var indexBuffer = LoadModelV04._mesh._indexBuffer;
  30591. subMesh._indexBuffer = indexBuffer;
  30592. subMesh._setIndexRange(ibStart, ibCount);
  30593. var vertexBuffer = LoadModelV04._mesh._vertexBuffer;
  30594. subMesh._vertexBuffer = vertexBuffer;
  30595. var offset = LoadModelV04._DATA.offset;
  30596. var subIndexBufferStart = subMesh._subIndexBufferStart;
  30597. var subIndexBufferCount = subMesh._subIndexBufferCount;
  30598. var boneIndicesList = subMesh._boneIndicesList;
  30599. var drawCount = LoadModelV04._readData.getUint16();
  30600. subIndexBufferStart.length = drawCount;
  30601. subIndexBufferCount.length = drawCount;
  30602. boneIndicesList.length = drawCount;
  30603. var skinnedCache = LoadModelV04._mesh._skinnedMatrixCaches;
  30604. var subMeshIndex = LoadModelV04._subMeshes.length;
  30605. skinnedCache.length = LoadModelV04._mesh._inverseBindPoses.length;
  30606. for (var i = 0; i < drawCount; i++) {
  30607. subIndexBufferStart[i] = LoadModelV04._readData.getUint32();
  30608. subIndexBufferCount[i] = LoadModelV04._readData.getUint32();
  30609. var boneDicofs = LoadModelV04._readData.getUint32();
  30610. var boneDicCount = LoadModelV04._readData.getUint32();
  30611. var boneIndices = boneIndicesList[i] = new Uint16Array(arrayBuffer.slice(offset + boneDicofs, offset + boneDicofs + boneDicCount));
  30612. var boneIndexCount = boneIndices.length;
  30613. for (var j = 0; j < boneIndexCount; j++) {
  30614. var index = boneIndices[j];
  30615. skinnedCache[index] || (skinnedCache[index] = new skinnedMatrixCache(subMeshIndex, i, j));
  30616. }
  30617. }
  30618. LoadModelV04._subMeshes.push(subMesh);
  30619. return true;
  30620. }
  30621. }
  30622. LoadModelV04._BLOCK = { count: 0 };
  30623. LoadModelV04._DATA = { offset: 0, size: 0 };
  30624. LoadModelV04._strings = [];
  30625. class LoadModelV05 {
  30626. static parse(readData, version, mesh, subMeshes) {
  30627. LoadModelV05._mesh = mesh;
  30628. LoadModelV05._subMeshes = subMeshes;
  30629. LoadModelV05._version = version;
  30630. LoadModelV05._readData = readData;
  30631. LoadModelV05.READ_DATA();
  30632. LoadModelV05.READ_BLOCK();
  30633. LoadModelV05.READ_STRINGS();
  30634. for (var i = 0, n = LoadModelV05._BLOCK.count; i < n; i++) {
  30635. LoadModelV05._readData.pos = LoadModelV05._BLOCK.blockStarts[i];
  30636. var index = LoadModelV05._readData.getUint16();
  30637. var blockName = LoadModelV05._strings[index];
  30638. var fn = LoadModelV05["READ_" + blockName];
  30639. if (fn == null)
  30640. throw new Error("model file err,no this function:" + index + " " + blockName);
  30641. else
  30642. fn.call(null);
  30643. }
  30644. LoadModelV05._strings.length = 0;
  30645. LoadModelV05._readData = null;
  30646. LoadModelV05._version = null;
  30647. LoadModelV05._mesh = null;
  30648. LoadModelV05._subMeshes = null;
  30649. }
  30650. static _readString() {
  30651. return LoadModelV05._strings[LoadModelV05._readData.getUint16()];
  30652. }
  30653. static READ_DATA() {
  30654. LoadModelV05._DATA.offset = LoadModelV05._readData.getUint32();
  30655. LoadModelV05._DATA.size = LoadModelV05._readData.getUint32();
  30656. }
  30657. static READ_BLOCK() {
  30658. var count = LoadModelV05._BLOCK.count = LoadModelV05._readData.getUint16();
  30659. var blockStarts = LoadModelV05._BLOCK.blockStarts = [];
  30660. var blockLengths = LoadModelV05._BLOCK.blockLengths = [];
  30661. for (var i = 0; i < count; i++) {
  30662. blockStarts.push(LoadModelV05._readData.getUint32());
  30663. blockLengths.push(LoadModelV05._readData.getUint32());
  30664. }
  30665. }
  30666. static READ_STRINGS() {
  30667. var offset = LoadModelV05._readData.getUint32();
  30668. var count = LoadModelV05._readData.getUint16();
  30669. var prePos = LoadModelV05._readData.pos;
  30670. LoadModelV05._readData.pos = offset + LoadModelV05._DATA.offset;
  30671. for (var i = 0; i < count; i++)
  30672. LoadModelV05._strings[i] = LoadModelV05._readData.readUTFString();
  30673. LoadModelV05._readData.pos = prePos;
  30674. }
  30675. static READ_MESH() {
  30676. var gl = Laya.LayaGL.instance;
  30677. var i;
  30678. var memorySize = 0;
  30679. var name = LoadModelV05._readString();
  30680. var reader = LoadModelV05._readData;
  30681. var arrayBuffer = reader.__getBuffer();
  30682. var vertexBufferCount = reader.getInt16();
  30683. var offset = LoadModelV05._DATA.offset;
  30684. for (i = 0; i < vertexBufferCount; i++) {
  30685. var vbStart = offset + reader.getUint32();
  30686. var vertexCount = reader.getUint32();
  30687. var vertexFlag = LoadModelV05._readString();
  30688. var vertexDeclaration = VertexMesh.getVertexDeclaration(vertexFlag, false);
  30689. var vertexStride = vertexDeclaration.vertexStride;
  30690. var vertexData;
  30691. var floatData;
  30692. var uint8Data;
  30693. var subVertexFlags = vertexFlag.split(",");
  30694. var subVertexCount = subVertexFlags.length;
  30695. var mesh = LoadModelV05._mesh;
  30696. switch (LoadModelV05._version) {
  30697. case "LAYAMODEL:05":
  30698. case "LAYAMODEL:0501":
  30699. vertexData = arrayBuffer.slice(vbStart, vbStart + vertexCount * vertexStride);
  30700. floatData = new Float32Array(vertexData);
  30701. uint8Data = new Uint8Array(vertexData);
  30702. break;
  30703. case "LAYAMODEL:COMPRESSION_05":
  30704. case "LAYAMODEL:COMPRESSION_0501":
  30705. vertexData = new ArrayBuffer(vertexStride * vertexCount);
  30706. floatData = new Float32Array(vertexData);
  30707. uint8Data = new Uint8Array(vertexData);
  30708. var lastPosition = reader.pos;
  30709. reader.pos = vbStart;
  30710. for (var j = 0; j < vertexCount; j++) {
  30711. var subOffset;
  30712. var verOffset = j * vertexStride;
  30713. for (var k = 0; k < subVertexCount; k++) {
  30714. switch (subVertexFlags[k]) {
  30715. case "POSITION":
  30716. subOffset = verOffset / 4;
  30717. floatData[subOffset] = HalfFloatUtils.convertToNumber(reader.getUint16());
  30718. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(reader.getUint16());
  30719. floatData[subOffset + 2] = HalfFloatUtils.convertToNumber(reader.getUint16());
  30720. verOffset += 12;
  30721. break;
  30722. case "NORMAL":
  30723. subOffset = verOffset / 4;
  30724. floatData[subOffset] = reader.getUint8() / 127.5 - 1;
  30725. floatData[subOffset + 1] = reader.getUint8() / 127.5 - 1;
  30726. floatData[subOffset + 2] = reader.getUint8() / 127.5 - 1;
  30727. verOffset += 12;
  30728. break;
  30729. case "COLOR":
  30730. subOffset = verOffset / 4;
  30731. floatData[subOffset] = reader.getUint8() / 255;
  30732. floatData[subOffset + 1] = reader.getUint8() / 255;
  30733. floatData[subOffset + 2] = reader.getUint8() / 255;
  30734. floatData[subOffset + 3] = reader.getUint8() / 255;
  30735. verOffset += 16;
  30736. break;
  30737. case "UV":
  30738. subOffset = verOffset / 4;
  30739. floatData[subOffset] = HalfFloatUtils.convertToNumber(reader.getUint16());
  30740. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(reader.getUint16());
  30741. verOffset += 8;
  30742. break;
  30743. case "UV1":
  30744. subOffset = verOffset / 4;
  30745. floatData[subOffset] = HalfFloatUtils.convertToNumber(reader.getUint16());
  30746. floatData[subOffset + 1] = HalfFloatUtils.convertToNumber(reader.getUint16());
  30747. verOffset += 8;
  30748. break;
  30749. case "BLENDWEIGHT":
  30750. subOffset = verOffset / 4;
  30751. floatData[subOffset] = reader.getUint8() / 255;
  30752. floatData[subOffset + 1] = reader.getUint8() / 255;
  30753. floatData[subOffset + 2] = reader.getUint8() / 255;
  30754. floatData[subOffset + 3] = reader.getUint8() / 255;
  30755. verOffset += 16;
  30756. break;
  30757. case "BLENDINDICES":
  30758. uint8Data[verOffset] = reader.getUint8();
  30759. uint8Data[verOffset + 1] = reader.getUint8();
  30760. uint8Data[verOffset + 2] = reader.getUint8();
  30761. uint8Data[verOffset + 3] = reader.getUint8();
  30762. verOffset += 4;
  30763. break;
  30764. case "TANGENT":
  30765. subOffset = verOffset / 4;
  30766. floatData[subOffset] = reader.getUint8() / 127.5 - 1;
  30767. floatData[subOffset + 1] = reader.getUint8() / 127.5 - 1;
  30768. floatData[subOffset + 2] = reader.getUint8() / 127.5 - 1;
  30769. floatData[subOffset + 3] = reader.getUint8() / 127.5 - 1;
  30770. verOffset += 16;
  30771. break;
  30772. }
  30773. }
  30774. }
  30775. reader.pos = lastPosition;
  30776. break;
  30777. }
  30778. var vertexBuffer = new VertexBuffer3D(vertexData.byteLength, gl.STATIC_DRAW, true);
  30779. vertexBuffer.vertexDeclaration = vertexDeclaration;
  30780. vertexBuffer.setData(vertexData);
  30781. var vertexCount = vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  30782. if (vertexCount > 65535)
  30783. mesh._indexFormat = exports.IndexFormat.UInt32;
  30784. else
  30785. mesh._indexFormat = exports.IndexFormat.UInt16;
  30786. mesh._vertexBuffer = vertexBuffer;
  30787. mesh._vertexCount += vertexCount;
  30788. memorySize += floatData.length * 4;
  30789. }
  30790. var ibStart = offset + reader.getUint32();
  30791. var ibLength = reader.getUint32();
  30792. var ibDatas;
  30793. if (mesh.indexFormat == exports.IndexFormat.UInt32)
  30794. ibDatas = new Uint32Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  30795. else
  30796. ibDatas = new Uint16Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  30797. var indexBuffer = new IndexBuffer3D(mesh.indexFormat, ibDatas.length, gl.STATIC_DRAW, true);
  30798. indexBuffer.setData(ibDatas);
  30799. mesh._indexBuffer = indexBuffer;
  30800. mesh._setBuffer(mesh._vertexBuffer, indexBuffer);
  30801. memorySize += indexBuffer.indexCount * 2;
  30802. mesh._setCPUMemory(memorySize);
  30803. mesh._setGPUMemory(memorySize);
  30804. if (LoadModelV05._version == "LAYAMODEL:0501" || LoadModelV05._version == "LAYAMODEL:COMPRESSION_0501") {
  30805. var bounds = mesh.bounds;
  30806. var min = bounds.getMin();
  30807. var max = bounds.getMax();
  30808. min.setValue(reader.getFloat32(), reader.getFloat32(), reader.getFloat32());
  30809. max.setValue(reader.getFloat32(), reader.getFloat32(), reader.getFloat32());
  30810. bounds.setMin(min);
  30811. bounds.setMax(max);
  30812. mesh.bounds = bounds;
  30813. }
  30814. var boneNames = mesh._boneNames = [];
  30815. var boneCount = reader.getUint16();
  30816. boneNames.length = boneCount;
  30817. for (i = 0; i < boneCount; i++)
  30818. boneNames[i] = LoadModelV05._strings[reader.getUint16()];
  30819. var bindPoseDataStart = reader.getUint32();
  30820. var bindPoseDataLength = reader.getUint32();
  30821. var bindPoseDatas = new Float32Array(arrayBuffer.slice(offset + bindPoseDataStart, offset + bindPoseDataStart + bindPoseDataLength));
  30822. var bindPoseFloatCount = bindPoseDatas.length;
  30823. var bindPoseBuffer = mesh._inverseBindPosesBuffer = new ArrayBuffer(bindPoseFloatCount * 4);
  30824. mesh._inverseBindPoses = [];
  30825. for (i = 0; i < bindPoseFloatCount; i += 16) {
  30826. 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));
  30827. mesh._inverseBindPoses[i / 16] = inverseGlobalBindPose;
  30828. }
  30829. return true;
  30830. }
  30831. static READ_SUBMESH() {
  30832. var reader = LoadModelV05._readData;
  30833. var arrayBuffer = reader.__getBuffer();
  30834. var subMesh = new SubMesh(LoadModelV05._mesh);
  30835. reader.getInt16();
  30836. var ibStart = reader.getUint32();
  30837. var ibCount = reader.getUint32();
  30838. var indexBuffer = LoadModelV05._mesh._indexBuffer;
  30839. subMesh._indexBuffer = indexBuffer;
  30840. subMesh._setIndexRange(ibStart, ibCount);
  30841. var vertexBuffer = LoadModelV05._mesh._vertexBuffer;
  30842. subMesh._vertexBuffer = vertexBuffer;
  30843. var offset = LoadModelV05._DATA.offset;
  30844. var subIndexBufferStart = subMesh._subIndexBufferStart;
  30845. var subIndexBufferCount = subMesh._subIndexBufferCount;
  30846. var boneIndicesList = subMesh._boneIndicesList;
  30847. var drawCount = reader.getUint16();
  30848. subIndexBufferStart.length = drawCount;
  30849. subIndexBufferCount.length = drawCount;
  30850. boneIndicesList.length = drawCount;
  30851. var skinnedCache = LoadModelV05._mesh._skinnedMatrixCaches;
  30852. var subMeshIndex = LoadModelV05._subMeshes.length;
  30853. skinnedCache.length = LoadModelV05._mesh._inverseBindPoses.length;
  30854. for (var i = 0; i < drawCount; i++) {
  30855. subIndexBufferStart[i] = reader.getUint32();
  30856. subIndexBufferCount[i] = reader.getUint32();
  30857. var boneDicofs = reader.getUint32();
  30858. var boneDicCount = reader.getUint32();
  30859. var boneIndices = boneIndicesList[i] = new Uint16Array(arrayBuffer.slice(offset + boneDicofs, offset + boneDicofs + boneDicCount));
  30860. for (var j = 0, m = boneIndices.length; j < m; j++) {
  30861. var index = boneIndices[j];
  30862. skinnedCache[index] || (skinnedCache[index] = new skinnedMatrixCache(subMeshIndex, i, j));
  30863. }
  30864. }
  30865. LoadModelV05._subMeshes.push(subMesh);
  30866. return true;
  30867. }
  30868. }
  30869. LoadModelV05._BLOCK = { count: 0 };
  30870. LoadModelV05._DATA = { offset: 0, size: 0 };
  30871. LoadModelV05._strings = [];
  30872. class MeshReader {
  30873. static _parse(data, propertyParams = null, constructParams = null) {
  30874. var mesh = new Mesh();
  30875. MeshReader.read(data, mesh, mesh._subMeshes);
  30876. return mesh;
  30877. }
  30878. static read(data, mesh, subMeshes) {
  30879. var readData = new Laya.Byte(data);
  30880. readData.pos = 0;
  30881. var version = readData.readUTFString();
  30882. switch (version) {
  30883. case "LAYAMODEL:0301":
  30884. case "LAYAMODEL:0400":
  30885. case "LAYAMODEL:0401":
  30886. LoadModelV04.parse(readData, version, mesh, subMeshes);
  30887. break;
  30888. case "LAYAMODEL:05":
  30889. case "LAYAMODEL:COMPRESSION_05":
  30890. case "LAYAMODEL:0501":
  30891. case "LAYAMODEL:COMPRESSION_0501":
  30892. LoadModelV05.parse(readData, version, mesh, subMeshes);
  30893. break;
  30894. default:
  30895. throw new Error("MeshReader: unknown mesh version.");
  30896. }
  30897. mesh._setSubMeshes(subMeshes);
  30898. if (version != "LAYAMODEL:0501" && version != "LAYAMODEL:COMPRESSION_0501")
  30899. mesh.calculateBounds();
  30900. }
  30901. }
  30902. var SkyPanoramicFS = "#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#define PI 3.14159265359\r\n#include \"Lighting.glsl\";\r\n\r\nuniform sampler2D u_Texture;\r\nuniform vec4 u_TextureHDRParams;\r\nuniform vec4 u_TintColor;\r\n\r\nvarying vec3 v_Texcoord;\r\nvarying vec2 v_Image180ScaleAndCutoff;\r\nvarying vec4 v_Layout3DScaleAndOffset;\r\n\r\nvec2 ToRadialCoords(vec3 coords)\r\n{\r\n\tvec3 normalizedCoords = normalize(coords);\r\n\tfloat latitude = acos(normalizedCoords.y);\r\n\tfloat longitude = atan(normalizedCoords.z,normalizedCoords.x);\r\n\tvec2 sphereCoords = vec2(longitude, latitude) * vec2(0.5/PI, 1.0/PI);\r\n\treturn vec2(0.5,1.0) - sphereCoords;\r\n}\r\n\r\n\r\nvoid main()\r\n{\t\r\n\tvec2 tc = ToRadialCoords(v_Texcoord);\r\n\tif (tc.x > v_Image180ScaleAndCutoff.y)\r\n\t\tgl_FragColor=vec4(0,0,0,1);\r\n\ttc.x = mod(tc.x*v_Image180ScaleAndCutoff.x, 1.0);\r\n\ttc = (tc + v_Layout3DScaleAndOffset.xy) * v_Layout3DScaleAndOffset.zw;\r\n\r\n\tmediump vec4 tex = texture2D (u_Texture, tc);\r\n\tmediump vec3 c = decodeHDR (tex, u_TextureHDRParams.x);\r\n\tc = c * u_TintColor.rgb * 2.0;//Gamma Space is 2.0,linear space is 4.59479380\r\n\tgl_FragColor=vec4(c, 1.0);\r\n}\r\n\r\n";
  30903. var SkyPanoramicVS = "#include \"Lighting.glsl\";\r\n\r\n#define PI 3.14159265359\r\n\r\nattribute vec4 a_Position;\r\n\r\nuniform mat4 u_ViewProjection;\r\nuniform float u_Rotation;\r\n\r\nvarying vec3 v_Texcoord;\r\nvarying vec2 v_Image180ScaleAndCutoff;\r\nvarying vec4 v_Layout3DScaleAndOffset;\r\n\r\nvec4 rotateAroundYInDegrees (vec4 vertex, float degrees)\r\n{\r\n\tfloat angle = degrees * PI / 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\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\r\n\tv_Texcoord=vec3(-a_Position.x,-a_Position.y,a_Position.z);// NOTE: -a_Position.x convert coords system\r\n\r\n\t// Calculate constant horizontal scale and cutoff for 180 (vs 360) image type\r\n\tv_Image180ScaleAndCutoff = vec2(1.0, 1.0);// 360 degree mode\r\n\r\n\t// Calculate constant scale and offset for 3D layouts\r\n\tv_Layout3DScaleAndOffset = vec4(0,0,1,1);\r\n}\r\n";
  30904. class SkyPanoramicMaterial extends Material {
  30905. constructor() {
  30906. super();
  30907. this._exposure = 1.0;
  30908. this._textureDecodeFormat = Laya.TextureDecodeFormat.Normal;
  30909. this._textureHDRParams = new Vector4(1.0, 0.0, 0.0, 1.0);
  30910. this.setShaderName("SkyPanoramic");
  30911. var shaderValues = this._shaderValues;
  30912. shaderValues.setVector(SkyPanoramicMaterial.TINTCOLOR, new Vector4(0.5, 0.5, 0.5, 0.5));
  30913. shaderValues.setNumber(SkyPanoramicMaterial.ROTATION, 0.0);
  30914. shaderValues.setVector(SkyPanoramicMaterial.TEXTURE_HDR_PARAMS, this._textureHDRParams);
  30915. }
  30916. static __init__() {
  30917. var attributeMap = {
  30918. 'a_Position': VertexMesh.MESH_POSITION0
  30919. };
  30920. var uniformMap = {
  30921. 'u_TintColor': Shader3D.PERIOD_MATERIAL,
  30922. 'u_TextureHDRParams': Shader3D.PERIOD_MATERIAL,
  30923. 'u_Rotation': Shader3D.PERIOD_MATERIAL,
  30924. 'u_Texture': Shader3D.PERIOD_MATERIAL,
  30925. 'u_ViewProjection': Shader3D.PERIOD_CAMERA
  30926. };
  30927. var shader = Shader3D.add("SkyPanoramic");
  30928. var subShader = new SubShader(attributeMap, uniformMap);
  30929. shader.addSubShader(subShader);
  30930. subShader.addShaderPass(SkyPanoramicVS, SkyPanoramicFS);
  30931. }
  30932. get tintColor() {
  30933. return this._shaderValues.getVector(SkyPanoramicMaterial.TINTCOLOR);
  30934. }
  30935. set tintColor(value) {
  30936. this._shaderValues.setVector(SkyPanoramicMaterial.TINTCOLOR, value);
  30937. }
  30938. get exposure() {
  30939. return this._exposure;
  30940. }
  30941. set exposure(value) {
  30942. if (this._exposure !== value) {
  30943. this._exposure = value;
  30944. if (this._textureDecodeFormat == Laya.TextureDecodeFormat.RGBM)
  30945. this._textureHDRParams.x = value * Laya.BaseTexture._rgbmRange;
  30946. else
  30947. this._textureHDRParams.x = value;
  30948. }
  30949. }
  30950. get rotation() {
  30951. return this._shaderValues.getNumber(SkyPanoramicMaterial.ROTATION);
  30952. }
  30953. set rotation(value) {
  30954. this._shaderValues.setNumber(SkyPanoramicMaterial.ROTATION, value);
  30955. }
  30956. get panoramicTexture() {
  30957. return this._shaderValues.getTexture(SkyPanoramicMaterial.TEXTURE);
  30958. }
  30959. set panoramicTexture(value) {
  30960. this._shaderValues.setTexture(SkyPanoramicMaterial.TEXTURE, value);
  30961. }
  30962. get panoramicTextureDecodeFormat() {
  30963. return this._textureDecodeFormat;
  30964. }
  30965. set panoramicTextureDecodeFormat(value) {
  30966. if (this._textureDecodeFormat !== value) {
  30967. this._textureDecodeFormat = value;
  30968. if (value == Laya.TextureDecodeFormat.RGBM)
  30969. this._textureHDRParams.x = this._exposure * Laya.BaseTexture._rgbmRange;
  30970. else
  30971. this._textureHDRParams.x = this._exposure;
  30972. }
  30973. }
  30974. }
  30975. SkyPanoramicMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_TintColor");
  30976. SkyPanoramicMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  30977. SkyPanoramicMaterial.ROTATION = Shader3D.propertyNameToID("u_Rotation");
  30978. SkyPanoramicMaterial.TEXTURE = Shader3D.propertyNameToID("u_Texture");
  30979. SkyPanoramicMaterial.TEXTURE_HDR_PARAMS = Shader3D.propertyNameToID("u_TextureHDRParams");
  30980. class ConstraintComponent extends Laya.Component {
  30981. constructor(constraintType) {
  30982. super();
  30983. this._anchor = new Vector3();
  30984. this._connectAnchor = new Vector3();
  30985. this._feedbackEnabled = false;
  30986. this._getJointFeedBack = false;
  30987. this._currentForce = new Vector3();
  30988. this._currentTorque = new Vector3();
  30989. this._constraintType = constraintType;
  30990. var bt = Physics3D._bullet;
  30991. this._btframATrans = bt.btTransform_create();
  30992. this._btframBTrans = bt.btTransform_create();
  30993. bt.btTransform_setIdentity(this._btframATrans);
  30994. bt.btTransform_setIdentity(this._btframBTrans);
  30995. this._btframAPos = bt.btVector3_create(0, 0, 0);
  30996. this._btframBPos = bt.btVector3_create(0, 0, 0);
  30997. bt.btTransform_setOrigin(this._btframATrans, this._btframAPos);
  30998. bt.btTransform_setOrigin(this._btframBTrans, this._btframBPos);
  30999. this._breakForce = -1;
  31000. this._breakTorque = -1;
  31001. }
  31002. get enabled() {
  31003. return super.enabled;
  31004. }
  31005. set enabled(value) {
  31006. super.enabled = value;
  31007. }
  31008. get appliedImpulse() {
  31009. if (!this._feedbackEnabled) {
  31010. this._btConstraint.EnableFeedback(true);
  31011. this._feedbackEnabled = true;
  31012. }
  31013. return this._btConstraint.AppliedImpulse;
  31014. }
  31015. set connectedBody(value) {
  31016. this._connectedBody = value;
  31017. value.constaintRigidbodyB = this;
  31018. }
  31019. get connectedBody() {
  31020. return this._connectedBody;
  31021. }
  31022. get ownBody() {
  31023. return this._ownBody;
  31024. }
  31025. set ownBody(value) {
  31026. this._ownBody = value;
  31027. value.constaintRigidbodyA = this;
  31028. }
  31029. get currentForce() {
  31030. if (!this._getJointFeedBack)
  31031. this._getFeedBackInfo();
  31032. return this._currentForce;
  31033. }
  31034. get currentTorque() {
  31035. if (!this._getJointFeedBack)
  31036. this._getFeedBackInfo();
  31037. return this._currentTorque;
  31038. }
  31039. get breakForce() {
  31040. return this._breakForce;
  31041. }
  31042. set breakForce(value) {
  31043. this._breakForce = value;
  31044. }
  31045. get breakTorque() {
  31046. return this._breakTorque;
  31047. }
  31048. set breakTorque(value) {
  31049. this._breakTorque = value;
  31050. }
  31051. set anchor(value) {
  31052. value.cloneTo(this._anchor);
  31053. this.setFrames();
  31054. }
  31055. get anchor() {
  31056. return this._anchor;
  31057. }
  31058. set connectAnchor(value) {
  31059. value.cloneTo(this._connectAnchor);
  31060. this.setFrames();
  31061. }
  31062. get connectAnchor() {
  31063. return this._connectAnchor;
  31064. }
  31065. setOverrideNumSolverIterations(overideNumIterations) {
  31066. var bt = Physics3D._bullet;
  31067. bt.btTypedConstraint_setOverrideNumSolverIterations(this._btConstraint, overideNumIterations);
  31068. }
  31069. setConstraintEnabled(enable) {
  31070. var bt = Physics3D._bullet;
  31071. bt.btTypedConstraint_setEnabled(this._btConstraint, enable);
  31072. }
  31073. _onEnable() {
  31074. super._onEnable();
  31075. this.enabled = true;
  31076. }
  31077. _onDisable() {
  31078. super._onDisable();
  31079. this.enabled = false;
  31080. }
  31081. setFrames() {
  31082. var bt = Physics3D._bullet;
  31083. bt.btVector3_setValue(this._btframAPos, -this._anchor.x, this.anchor.y, this.anchor.z);
  31084. bt.btVector3_setValue(this._btframBPos, -this._connectAnchor.x, this._connectAnchor.y, this._connectAnchor.z);
  31085. bt.btTransform_setOrigin(this._btframATrans, this._btframAPos);
  31086. bt.btTransform_setOrigin(this._btframBTrans, this._btframBPos);
  31087. }
  31088. _addToSimulation() {
  31089. }
  31090. _removeFromSimulation() {
  31091. }
  31092. _createConstraint() {
  31093. }
  31094. setConnectRigidBody(ownerRigid, connectRigidBody) {
  31095. var ownerCanInSimulation = (ownerRigid) && (!!(ownerRigid._simulation && ownerRigid._enabled && ownerRigid.colliderShape));
  31096. var connectCanInSimulation = (connectRigidBody) && (!!(connectRigidBody._simulation && connectRigidBody._enabled && connectRigidBody.colliderShape));
  31097. if (!(ownerCanInSimulation && connectCanInSimulation))
  31098. throw "ownerRigid or connectRigidBody is not in Simulation";
  31099. if (ownerRigid != this._ownBody || connectRigidBody != this._connectedBody) {
  31100. var canInSimulation = !!(this.enabled && this._simulation);
  31101. canInSimulation && this._removeFromSimulation();
  31102. this._ownBody = ownerRigid;
  31103. this._connectedBody = connectRigidBody;
  31104. this._ownBody.constaintRigidbodyA = this;
  31105. this._connectedBody.constaintRigidbodyB = this;
  31106. this._createConstraint();
  31107. }
  31108. }
  31109. getcurrentForce(out) {
  31110. if (!this._btJointFeedBackObj)
  31111. throw "this Constraint is not simulation";
  31112. var bt = Physics3D._bullet;
  31113. var applyForce = bt.btJointFeedback_getAppliedForceBodyA(this._btJointFeedBackObj);
  31114. out.setValue(bt.btVector3_x(applyForce), bt.btVector3_y(applyForce), bt.btVector3_z(applyForce));
  31115. return;
  31116. }
  31117. getcurrentTorque(out) {
  31118. if (!this._btJointFeedBackObj)
  31119. throw "this Constraint is not simulation";
  31120. var bt = Physics3D._bullet;
  31121. var applyTorque = bt.btJointFeedback_getAppliedTorqueBodyA(this._btJointFeedBackObj);
  31122. out.setValue(bt.btVector3_x(applyTorque), bt.btVector3_y(applyTorque), bt.btVector3_z(applyTorque));
  31123. return;
  31124. }
  31125. _onDestroy() {
  31126. var physics3D = Physics3D._bullet;
  31127. this._removeFromSimulation();
  31128. if (this._btConstraint && this._btJointFeedBackObj && this._simulation) {
  31129. physics3D.btTypedConstraint_destroy(this._btConstraint);
  31130. physics3D.btJointFeedback_destroy(this._btJointFeedBackObj);
  31131. this._btJointFeedBackObj = null;
  31132. this._btConstraint = null;
  31133. }
  31134. super._onDisable();
  31135. }
  31136. _isBreakConstrained() {
  31137. this._getJointFeedBack = false;
  31138. if (this.breakForce == -1 && this.breakTorque == -1)
  31139. return false;
  31140. this._getFeedBackInfo();
  31141. var isBreakForce = this._breakForce != -1 && (Vector3.scalarLength(this._currentForce) > this._breakForce);
  31142. var isBreakTorque = this._breakTorque != -1 && (Vector3.scalarLength(this._currentTorque) > this._breakTorque);
  31143. if (isBreakForce || isBreakTorque) {
  31144. this._breakConstrained();
  31145. return true;
  31146. }
  31147. return false;
  31148. }
  31149. _parse(data) {
  31150. this._anchor.fromArray(data.anchor);
  31151. this._connectAnchor.fromArray(data.connectAnchor);
  31152. this.setFrames();
  31153. }
  31154. _getFeedBackInfo() {
  31155. var bt = Physics3D._bullet;
  31156. var applyForce = bt.btJointFeedback_getAppliedForceBodyA(this._btJointFeedBackObj);
  31157. var applyTorque = bt.btJointFeedback_getAppliedTorqueBodyA(this._btJointFeedBackObj);
  31158. this._currentTorque.setValue(bt.btVector3_x(applyTorque), bt.btVector3_y(applyTorque), bt.btVector3_z(applyTorque));
  31159. this._currentForce.setValue(bt.btVector3_x(applyForce), bt.btVector3_y(applyForce), bt.btVector3_z(applyForce));
  31160. this._getJointFeedBack = true;
  31161. }
  31162. _breakConstrained() {
  31163. this.ownBody.constaintRigidbodyA = null;
  31164. this.connectedBody.constaintRigidbodyB = null;
  31165. this.destroy();
  31166. }
  31167. }
  31168. ConstraintComponent.CONSTRAINT_POINT2POINT_CONSTRAINT_TYPE = 3;
  31169. ConstraintComponent.CONSTRAINT_HINGE_CONSTRAINT_TYPE = 4;
  31170. ConstraintComponent.CONSTRAINT_CONETWIST_CONSTRAINT_TYPE = 5;
  31171. ConstraintComponent.CONSTRAINT_D6_CONSTRAINT_TYPE = 6;
  31172. ConstraintComponent.CONSTRAINT_SLIDER_CONSTRAINT_TYPE = 7;
  31173. ConstraintComponent.CONSTRAINT_CONTACT_CONSTRAINT_TYPE = 8;
  31174. ConstraintComponent.CONSTRAINT_D6_SPRING_CONSTRAINT_TYPE = 9;
  31175. ConstraintComponent.CONSTRAINT_GEAR_CONSTRAINT_TYPE = 10;
  31176. ConstraintComponent.CONSTRAINT_FIXED_CONSTRAINT_TYPE = 11;
  31177. ConstraintComponent.CONSTRAINT_MAX_CONSTRAINT_TYPE = 12;
  31178. ConstraintComponent.CONSTRAINT_CONSTRAINT_ERP = 1;
  31179. ConstraintComponent.CONSTRAINT_CONSTRAINT_STOP_ERP = 2;
  31180. ConstraintComponent.CONSTRAINT_CONSTRAINT_CFM = 3;
  31181. ConstraintComponent.CONSTRAINT_CONSTRAINT_STOP_CFM = 4;
  31182. ConstraintComponent.tempForceV3 = new Vector3();
  31183. class FixedConstraint extends ConstraintComponent {
  31184. constructor() {
  31185. super(ConstraintComponent.CONSTRAINT_FIXED_CONSTRAINT_TYPE);
  31186. this.breakForce = -1;
  31187. this.breakTorque = -1;
  31188. }
  31189. _addToSimulation() {
  31190. this._simulation && this._simulation.addConstraint(this, this.enabled);
  31191. }
  31192. _removeFromSimulation() {
  31193. this._simulation.removeConstraint(this);
  31194. this._simulation = null;
  31195. }
  31196. _createConstraint() {
  31197. if (this.ownBody && this.ownBody._simulation && this.connectedBody && this.connectedBody._simulation) {
  31198. var bt = Physics3D._bullet;
  31199. this._btConstraint = bt.btFixedConstraint_create(this.ownBody.btColliderObject, this._btframATrans, this.connectedBody.btColliderObject, this._btframBTrans);
  31200. this._btJointFeedBackObj = bt.btJointFeedback_create(this._btConstraint);
  31201. bt.btTypedConstraint_setJointFeedback(this._btConstraint, this._btJointFeedBackObj);
  31202. this._simulation = this.owner._scene.physicsSimulation;
  31203. this._addToSimulation();
  31204. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, true);
  31205. }
  31206. }
  31207. _onAdded() {
  31208. super._onAdded();
  31209. }
  31210. _onEnable() {
  31211. if (!this._btConstraint)
  31212. return;
  31213. super._onEnable();
  31214. if (this._btConstraint)
  31215. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, true);
  31216. }
  31217. _onDisable() {
  31218. super._onDisable();
  31219. if (!this.connectedBody)
  31220. this._removeFromSimulation();
  31221. if (this._btConstraint)
  31222. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, false);
  31223. }
  31224. _onDestroy() {
  31225. super._onDestroy();
  31226. }
  31227. _parse(data, interactMap = null) {
  31228. super._parse(data);
  31229. if (data.rigidbodyID != -1 && data.connectRigidbodyID != -1) {
  31230. interactMap.component.push(this);
  31231. interactMap.data.push(data);
  31232. }
  31233. (data.breakForce != undefined) && (this.breakForce = data.breakForce);
  31234. (data.breakTorque != undefined) && (this.breakTorque = data.breakTorque);
  31235. }
  31236. _parseInteractive(data = null, spriteMap = null) {
  31237. var rigidBodySprite = spriteMap[data.rigidbodyID];
  31238. var rigidBody = rigidBodySprite.getComponent(Rigidbody3D);
  31239. var connectSprite = spriteMap[data.connectRigidbodyID];
  31240. var connectRigidbody = connectSprite.getComponent(Rigidbody3D);
  31241. this.ownBody = rigidBody;
  31242. this.connectedBody = connectRigidbody;
  31243. }
  31244. _cloneTo(dest) {
  31245. }
  31246. }
  31247. class ConfigurableConstraint extends ConstraintComponent {
  31248. constructor() {
  31249. super(ConstraintComponent.CONSTRAINT_D6_SPRING_CONSTRAINT_TYPE);
  31250. this._axis = new Vector3();
  31251. this._secondaryAxis = new Vector3();
  31252. this._minLinearLimit = new Vector3();
  31253. this._maxLinearLimit = new Vector3();
  31254. this._minAngularLimit = new Vector3();
  31255. this._maxAngularLimit = new Vector3();
  31256. this._linearLimitSpring = new Vector3();
  31257. this._angularLimitSpring = new Vector3();
  31258. this._linearBounce = new Vector3();
  31259. this._angularBounce = new Vector3();
  31260. this._linearDamp = new Vector3();
  31261. this._angularDamp = new Vector3();
  31262. this._xMotion = 0;
  31263. this._yMotion = 0;
  31264. this._zMotion = 0;
  31265. this._angularXMotion = 0;
  31266. this._angularYMotion = 0;
  31267. this._angularZMotion = 0;
  31268. var bt = Physics3D._bullet;
  31269. this._btAxis = bt.btVector3_create(-1.0, 0.0, 0.0);
  31270. this._btSecondaryAxis = bt.btVector3_create(0.0, 1.0, 0.0);
  31271. }
  31272. get axis() {
  31273. return this._axis;
  31274. }
  31275. get secondaryAxis() {
  31276. return this._secondaryAxis;
  31277. }
  31278. set maxAngularLimit(value) {
  31279. value.cloneTo(this._maxAngularLimit);
  31280. }
  31281. set minAngularLimit(value) {
  31282. value.cloneTo(this._minAngularLimit);
  31283. }
  31284. get maxAngularLimit() {
  31285. return this._maxAngularLimit;
  31286. }
  31287. get minAngularLimit() {
  31288. return this._minAngularLimit;
  31289. }
  31290. set maxLinearLimit(value) {
  31291. value.cloneTo(this._maxLinearLimit);
  31292. }
  31293. set minLinearLimit(value) {
  31294. value.cloneTo(this._minLinearLimit);
  31295. }
  31296. get maxLinearLimit() {
  31297. return this._maxLinearLimit;
  31298. }
  31299. get minLinearLimit() {
  31300. return this._minLinearLimit;
  31301. }
  31302. set XMotion(value) {
  31303. if (this._xMotion != value) {
  31304. this._xMotion = value;
  31305. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, value, -this._maxLinearLimit.x, -this._minLinearLimit.x);
  31306. }
  31307. }
  31308. get XMotion() {
  31309. return this._xMotion;
  31310. }
  31311. set YMotion(value) {
  31312. if (this._yMotion != value) {
  31313. this._yMotion = value;
  31314. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, value, this._minLinearLimit.y, this._maxLinearLimit.y);
  31315. }
  31316. }
  31317. get YMotion() {
  31318. return this._yMotion;
  31319. }
  31320. set ZMotion(value) {
  31321. if (this._zMotion != value) {
  31322. this._zMotion = value;
  31323. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, value, this._minLinearLimit.z, this._maxLinearLimit.z);
  31324. }
  31325. }
  31326. get ZMotion() {
  31327. return this._zMotion;
  31328. }
  31329. set angularXMotion(value) {
  31330. if (this._angularXMotion != value) {
  31331. this._angularXMotion = value;
  31332. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, value, -this._maxAngularLimit.x, -this._minAngularLimit.x);
  31333. }
  31334. }
  31335. get angularXMotion() {
  31336. return this._angularXMotion;
  31337. }
  31338. set angularYMotion(value) {
  31339. if (this._angularYMotion != value) {
  31340. this._angularYMotion = value;
  31341. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, value, this._minAngularLimit.y, this._maxAngularLimit.y);
  31342. }
  31343. }
  31344. get angularYMotion() {
  31345. return this._angularYMotion;
  31346. }
  31347. set angularZMotion(value) {
  31348. if (this._angularZMotion != value) {
  31349. this._angularZMotion = value;
  31350. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, value, this._minAngularLimit.z, this._maxAngularLimit.z);
  31351. }
  31352. }
  31353. get angularZMotion() {
  31354. return this._angularZMotion;
  31355. }
  31356. set linearLimitSpring(value) {
  31357. if (!Vector3.equals(this._linearLimitSpring, value)) {
  31358. value.cloneTo(this._linearLimitSpring);
  31359. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, value.x);
  31360. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, value.y);
  31361. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, value.z);
  31362. }
  31363. }
  31364. get linearLimitSpring() {
  31365. return this._linearLimitSpring;
  31366. }
  31367. set angularLimitSpring(value) {
  31368. if (!Vector3.equals(this._angularLimitSpring, value)) {
  31369. value.cloneTo(this._angularLimitSpring);
  31370. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, value.x);
  31371. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, value.y);
  31372. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, value.z);
  31373. }
  31374. }
  31375. get angularLimitSpring() {
  31376. return this._angularLimitSpring;
  31377. }
  31378. set linearBounce(value) {
  31379. if (!Vector3.equals(this._linearBounce, value)) {
  31380. value.cloneTo(this._linearBounce);
  31381. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, value.x);
  31382. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, value.y);
  31383. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, value.z);
  31384. }
  31385. }
  31386. get linearBounce() {
  31387. return this._linearBounce;
  31388. }
  31389. set angularBounce(value) {
  31390. if (!Vector3.equals(this._angularBounce, value)) {
  31391. value.cloneTo(this._angularBounce);
  31392. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, value.x);
  31393. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, value.y);
  31394. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, value.z);
  31395. }
  31396. }
  31397. get angularBounce() {
  31398. return this._angularBounce;
  31399. }
  31400. set linearDamp(value) {
  31401. if (!Vector3.equals(this._linearDamp, value)) {
  31402. value.cloneTo(this._linearDamp);
  31403. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, value.x);
  31404. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, value.y);
  31405. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, value.z);
  31406. }
  31407. }
  31408. get linearDamp() {
  31409. return this._linearDamp;
  31410. }
  31411. set angularDamp(value) {
  31412. if (!Vector3.equals(this._angularDamp, value)) {
  31413. value.cloneTo(this._angularDamp);
  31414. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, value.x);
  31415. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, value.y);
  31416. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, value.z);
  31417. }
  31418. }
  31419. get angularDamp() {
  31420. return this._angularDamp;
  31421. }
  31422. set anchor(value) {
  31423. value.cloneTo(this._anchor);
  31424. this.setFrames();
  31425. }
  31426. get anchor() {
  31427. return this._anchor;
  31428. }
  31429. set connectAnchor(value) {
  31430. value.cloneTo(this._connectAnchor);
  31431. this.setFrames();
  31432. }
  31433. get connectAnchor() {
  31434. return this._connectAnchor;
  31435. }
  31436. setAxis(axis, secondaryAxis) {
  31437. if (!this._btConstraint)
  31438. return;
  31439. var bt = Physics3D._bullet;
  31440. this._axis.setValue(axis.x, axis.y, axis.y);
  31441. this._secondaryAxis.setValue(secondaryAxis.x, secondaryAxis.y, secondaryAxis.z);
  31442. this._btAxis = bt.btVector3_setValue(-axis.x, axis.y, axis.z);
  31443. this._btSecondaryAxis = bt.btVector3_setValue(-secondaryAxis.x, secondaryAxis.y, secondaryAxis.z);
  31444. bt.btGeneric6DofSpring2Constraint_setAxis(this._btConstraint, this._btAxis, this._btSecondaryAxis);
  31445. }
  31446. setLimit(axis, motionType, low, high) {
  31447. if (!this._btConstraint)
  31448. return;
  31449. var bt = Physics3D._bullet;
  31450. switch (motionType) {
  31451. case ConfigurableConstraint.CONFIG_MOTION_TYPE_LOCKED:
  31452. bt.btGeneric6DofSpring2Constraint_setLimit(this._btConstraint, axis, 0, 0);
  31453. break;
  31454. case ConfigurableConstraint.CONFIG_MOTION_TYPE_LIMITED:
  31455. if (low < high)
  31456. bt.btGeneric6DofSpring2Constraint_setLimit(this._btConstraint, axis, low, high);
  31457. break;
  31458. case ConfigurableConstraint.CONFIG_MOTION_TYPE_FREE:
  31459. bt.btGeneric6DofSpring2Constraint_setLimit(this._btConstraint, axis, 1, 0);
  31460. break;
  31461. default:
  31462. throw "No Type of Axis Motion";
  31463. }
  31464. }
  31465. setSpring(axis, springValue, limitIfNeeded = true) {
  31466. if (!this._btConstraint)
  31467. return;
  31468. var bt = Physics3D._bullet;
  31469. var enableSpring = springValue > 0;
  31470. bt.btGeneric6DofSpring2Constraint_enableSpring(this._btConstraint, axis, enableSpring);
  31471. if (enableSpring)
  31472. bt.btGeneric6DofSpring2Constraint_setStiffness(this._btConstraint, axis, springValue, limitIfNeeded);
  31473. }
  31474. setBounce(axis, bounce) {
  31475. if (!this._btConstraint)
  31476. return;
  31477. var bt = Physics3D._bullet;
  31478. bounce = bounce <= 0 ? 0 : bounce;
  31479. bt.btGeneric6DofSpring2Constraint_setBounce(this._btConstraint, axis, bounce);
  31480. }
  31481. setDamping(axis, damp, limitIfNeeded = true) {
  31482. if (!this._btConstraint)
  31483. return;
  31484. var bt = Physics3D._bullet;
  31485. damp = damp <= 0 ? 0 : damp;
  31486. bt.btGeneric6DofSpring2Constraint_setDamping(this._btConstraint, axis, damp, limitIfNeeded);
  31487. }
  31488. setEquilibriumPoint(axis, equilibriumPoint) {
  31489. var bt = Physics3D._bullet;
  31490. bt.btGeneric6DofSpring2Constraint_setEquilibriumPoint(this._btConstraint, axis, equilibriumPoint);
  31491. }
  31492. enableMotor(axis, isEnableMotor) {
  31493. var bt = Physics3D._bullet;
  31494. bt.btGeneric6DofSpring2Constraint_enableMotor(this._btConstraint, axis, isEnableMotor);
  31495. }
  31496. setServo(axis, onOff) {
  31497. var bt = Physics3D._bullet;
  31498. bt.btGeneric6DofSpring2Constraint_setServo(this._btConstraint, axis, onOff);
  31499. }
  31500. setTargetVelocity(axis, velocity) {
  31501. var bt = Physics3D._bullet;
  31502. bt.btGeneric6DofSpring2Constraint_setTargetVelocity(this._btConstraint, axis, velocity);
  31503. }
  31504. setTargetPosition(axis, target) {
  31505. var bt = Physics3D._bullet;
  31506. bt.btGeneric6DofSpring2Constraint_setServoTarget(this._btConstraint, axis, target);
  31507. }
  31508. setMaxMotorForce(axis, force) {
  31509. var bt = Physics3D._bullet;
  31510. bt.btGeneric6DofSpring2Constraint_setMaxMotorForce(this._btConstraint, axis, force);
  31511. }
  31512. setParam(axis, constraintParams, value) {
  31513. var bt = Physics3D._bullet;
  31514. bt.btTypedConstraint_setParam(this._btConstraint, axis, constraintParams, value);
  31515. }
  31516. setFrames() {
  31517. super.setFrames();
  31518. var bt = Physics3D._bullet;
  31519. if (!this._btConstraint)
  31520. return;
  31521. bt.btGeneric6DofSpring2Constraint_setFrames(this._btConstraint, this._btframATrans, this._btframBTrans);
  31522. }
  31523. _addToSimulation() {
  31524. this._simulation && this._simulation.addConstraint(this, this.enabled);
  31525. }
  31526. _removeFromSimulation() {
  31527. this._simulation.removeConstraint(this);
  31528. this._simulation = null;
  31529. }
  31530. _createConstraint() {
  31531. var bt = Physics3D._bullet;
  31532. this._btConstraint = bt.btGeneric6DofSpring2Constraint_create(this.ownBody.btColliderObject, this._btframAPos, this.connectedBody.btColliderObject, this._btframBPos, ConfigurableConstraint.RO_XYZ);
  31533. this._btJointFeedBackObj = bt.btJointFeedback_create(this._btConstraint);
  31534. bt.btTypedConstraint_setJointFeedback(this._btConstraint, this._btJointFeedBackObj);
  31535. this._simulation = this.owner._scene.physicsSimulation;
  31536. this._initAllConstraintInfo();
  31537. this._addToSimulation();
  31538. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, true);
  31539. }
  31540. _initAllConstraintInfo() {
  31541. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, this._xMotion, -this._maxLinearLimit.x, -this._minLinearLimit.x);
  31542. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, this._yMotion, this._minLinearLimit.y, this._maxLinearLimit.y);
  31543. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, this._zMotion, this._minLinearLimit.z, this._maxLinearLimit.z);
  31544. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, this._angularXMotion, -this._maxAngularLimit.x, -this._minAngularLimit.x);
  31545. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, this._angularYMotion, this._minAngularLimit.y, this._maxAngularLimit.y);
  31546. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, this._angularZMotion, this._minAngularLimit.z, this._maxAngularLimit.z);
  31547. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, this._linearLimitSpring.x);
  31548. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, this._linearLimitSpring.y);
  31549. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, this._linearLimitSpring.z);
  31550. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, this._angularLimitSpring.x);
  31551. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, this._angularLimitSpring.y);
  31552. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, this._angularLimitSpring.z);
  31553. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, this._linearBounce.x);
  31554. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, this._linearBounce.y);
  31555. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, this._linearBounce.z);
  31556. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, this._angularBounce.x);
  31557. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, this._angularBounce.y);
  31558. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, this._angularBounce.z);
  31559. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, this._linearDamp.x);
  31560. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, this._linearDamp.y);
  31561. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, this._linearDamp.z);
  31562. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, this._angularDamp.x);
  31563. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, this._angularDamp.y);
  31564. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, this._angularDamp.z);
  31565. this.setFrames();
  31566. this.setEquilibriumPoint(0, 0);
  31567. }
  31568. _onAdded() {
  31569. super._onAdded();
  31570. }
  31571. _onEnable() {
  31572. if (!this._btConstraint)
  31573. return;
  31574. super._onEnable();
  31575. if (this._btConstraint)
  31576. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, true);
  31577. }
  31578. _onDisable() {
  31579. super._onDisable();
  31580. if (!this.connectedBody)
  31581. this._removeFromSimulation();
  31582. if (this._btConstraint)
  31583. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, false);
  31584. }
  31585. _parse(data, interactMap = null) {
  31586. super._parse(data);
  31587. this._axis.fromArray(data.axis);
  31588. this._secondaryAxis.fromArray(data.secondaryAxis);
  31589. var limitlimit = data.linearLimit;
  31590. this._minLinearLimit.setValue(-limitlimit, -limitlimit, -limitlimit);
  31591. this._maxLinearLimit.setValue(limitlimit, limitlimit, limitlimit);
  31592. var limitSpring = data.linearLimitSpring;
  31593. this._linearLimitSpring.setValue(limitSpring, limitSpring, limitSpring);
  31594. var limitDamp = data.linearLimitDamper;
  31595. this._linearDamp.setValue(limitDamp, limitDamp, limitDamp);
  31596. var limitBounciness = data.linearLimitBounciness;
  31597. this._linearBounce.setValue(limitBounciness, limitBounciness, limitBounciness);
  31598. var xlowAngularLimit = data.lowAngularXLimit;
  31599. var xhighAngularLimit = data.highAngularXLimit;
  31600. var yAngularLimit = data.angularYLimit;
  31601. var zAngularLimit = data.angularZLimit;
  31602. this._minAngularLimit.setValue(xlowAngularLimit, -yAngularLimit, -zAngularLimit);
  31603. this._maxAngularLimit.setValue(xhighAngularLimit, yAngularLimit, zAngularLimit);
  31604. var xhighAngularBounciness = data.highAngularXLimitBounciness;
  31605. var ybounciness = data.angularYLimitBounciness;
  31606. var zbounciness = data.angularZLimitBounciness;
  31607. this._angularBounce.setValue(xhighAngularBounciness, ybounciness, zbounciness);
  31608. var xAngularSpring = data.angularXLimitSpring;
  31609. var yzAngularSpriny = data.angularYZLimitSpring;
  31610. this._angularLimitSpring.setValue(xAngularSpring, yzAngularSpriny, yzAngularSpriny);
  31611. var xAngularDamper = data.angularXLimitDamper;
  31612. var yzAngularDamper = data.angularYZLimitDamper;
  31613. this._angularDamp.setValue(xAngularDamper, yzAngularDamper, yzAngularDamper);
  31614. this.XMotion = data.xMotion;
  31615. this.YMotion = data.yMotion;
  31616. this.ZMotion = data.zMotion;
  31617. this.angularXMotion = data.angularXMotion;
  31618. this.angularYMotion = data.angularYMotion;
  31619. this.angularZMotion = data.angularZMotion;
  31620. if (data.rigidbodyID != -1 && data.connectRigidbodyID != -1) {
  31621. interactMap.component.push(this);
  31622. interactMap.data.push(data);
  31623. }
  31624. (data.breakForce != undefined) && (this.breakForce = data.breakForce);
  31625. (data.breakTorque != undefined) && (this.breakTorque = data.breakTorque);
  31626. }
  31627. _parseInteractive(data = null, spriteMap = null) {
  31628. var rigidBodySprite = spriteMap[data.rigidbodyID];
  31629. var rigidBody = rigidBodySprite.getComponent(Rigidbody3D);
  31630. var connectSprite = spriteMap[data.connectRigidbodyID];
  31631. var connectRigidbody = connectSprite.getComponent(Rigidbody3D);
  31632. this.ownBody = rigidBody;
  31633. this.connectedBody = connectRigidbody;
  31634. }
  31635. _onDestroy() {
  31636. super._onDestroy();
  31637. }
  31638. _cloneTo(dest) {
  31639. }
  31640. }
  31641. ConfigurableConstraint.CONFIG_MOTION_TYPE_LOCKED = 0;
  31642. ConfigurableConstraint.CONFIG_MOTION_TYPE_LIMITED = 1;
  31643. ConfigurableConstraint.CONFIG_MOTION_TYPE_FREE = 2;
  31644. ConfigurableConstraint.MOTION_LINEAR_INDEX_X = 0;
  31645. ConfigurableConstraint.MOTION_LINEAR_INDEX_Y = 1;
  31646. ConfigurableConstraint.MOTION_LINEAR_INDEX_Z = 2;
  31647. ConfigurableConstraint.MOTION_ANGULAR_INDEX_X = 3;
  31648. ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y = 4;
  31649. ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z = 5;
  31650. ConfigurableConstraint.RO_XYZ = 0;
  31651. ConfigurableConstraint.RO_XZY = 1;
  31652. ConfigurableConstraint.RO_YXZ = 2;
  31653. ConfigurableConstraint.RO_YZX = 3;
  31654. ConfigurableConstraint.RO_ZXY = 4;
  31655. ConfigurableConstraint.RO_ZYX = 5;
  31656. class Laya3D {
  31657. constructor() {
  31658. }
  31659. static get enablePhysics() {
  31660. return Physics3D._enablePhysics;
  31661. }
  31662. static _cancelLoadByUrl(url) {
  31663. Laya.Laya.loader.cancelLoadByUrl(url);
  31664. Laya3D._innerFirstLevelLoaderManager.cancelLoadByUrl(url);
  31665. Laya3D._innerSecondLevelLoaderManager.cancelLoadByUrl(url);
  31666. Laya3D._innerThirdLevelLoaderManager.cancelLoadByUrl(url);
  31667. Laya3D._innerFourthLevelLoaderManager.cancelLoadByUrl(url);
  31668. }
  31669. static _changeWebGLSize(width, height) {
  31670. Laya.WebGL.onStageResize(width, height);
  31671. RenderContext3D.clientWidth = width;
  31672. RenderContext3D.clientHeight = height;
  31673. }
  31674. static __init__(width, height, config) {
  31675. Laya.Config.isAntialias = config.isAntialias;
  31676. Laya.Config.isAlpha = config.isAlpha;
  31677. Laya.Config.premultipliedAlpha = config.premultipliedAlpha;
  31678. Laya.Config.isStencil = config.isStencil;
  31679. if (!Laya.WebGL.enable()) {
  31680. alert("Laya3D init error,must support webGL!");
  31681. return;
  31682. }
  31683. Laya.RunDriver.changeWebGLSize = Laya3D._changeWebGLSize;
  31684. Laya.Render.is3DMode = true;
  31685. Laya.Laya.init(width, height);
  31686. if (!Laya.Render.supportWebGLPlusRendering) {
  31687. Laya.LayaGL.instance = Laya.WebGLContext.mainContext;
  31688. Laya.LayaGL.instance.createCommandEncoder = function (reserveSize = 128, adjustSize = 64, isSyncToRenderThread = false) {
  31689. return new Laya.CommandEncoder(this, reserveSize, adjustSize, isSyncToRenderThread);
  31690. };
  31691. }
  31692. config._multiLighting = config.enableMultiLight && Laya.SystemUtils.supportTextureFormat(Laya.TextureFormat.R32G32B32A32);
  31693. ILaya3D.Shader3D = Shader3D;
  31694. ILaya3D.Scene3D = Scene3D;
  31695. ILaya3D.MeshRenderStaticBatchManager = MeshRenderStaticBatchManager;
  31696. ILaya3D.MeshRenderDynamicBatchManager = MeshRenderDynamicBatchManager;
  31697. ILaya3D.SubMeshDynamicBatch = SubMeshDynamicBatch;
  31698. ILaya3D.Laya3D = Laya3D;
  31699. ILaya3D.Matrix4x4 = Matrix4x4;
  31700. ILaya3D.Physics3D = Physics3D;
  31701. ILaya3D.ShadowLightType = exports.ShadowLightType;
  31702. Laya3D.enableNative3D();
  31703. if (config.isUseCannonPhysicsEngine)
  31704. Physics3D.__cannoninit__();
  31705. Physics3D.__bulletinit__();
  31706. VertexElementFormat.__init__();
  31707. VertexMesh.__init__();
  31708. VertexShurikenParticleBillboard.__init__();
  31709. VertexShurikenParticleMesh.__init__();
  31710. VertexPositionTexture0.__init__();
  31711. VertexTrail.__init__();
  31712. VertexPositionTerrain.__init__();
  31713. PixelLineVertex.__init__();
  31714. SubMeshInstanceBatch.__init__();
  31715. SubMeshDynamicBatch.__init__();
  31716. ShaderInit3D.__init__();
  31717. ShadowUtils.init();
  31718. PBRMaterial.__init__();
  31719. PBRStandardMaterial.__init__();
  31720. PBRSpecularMaterial.__init__();
  31721. SkyPanoramicMaterial.__init__();
  31722. Mesh.__init__();
  31723. PrimitiveMesh.__init__();
  31724. Sprite3D.__init__();
  31725. RenderableSprite3D.__init__();
  31726. MeshSprite3D.__init__();
  31727. SkinnedMeshSprite3D.__init__();
  31728. ShuriKenParticle3D.__init__();
  31729. TrailSprite3D.__init__();
  31730. PostProcess.__init__();
  31731. Scene3D.__init__();
  31732. MeshRenderStaticBatchManager.__init__();
  31733. Material.__initDefine__();
  31734. BaseMaterial.__initDefine__();
  31735. BlinnPhongMaterial.__initDefine__();
  31736. SkyProceduralMaterial.__initDefine__();
  31737. UnlitMaterial.__initDefine__();
  31738. TrailMaterial.__initDefine__();
  31739. EffectMaterial.__initDefine__();
  31740. WaterPrimaryMaterial.__initDefine__();
  31741. ShurikenParticleMaterial.__initDefine__();
  31742. ExtendTerrainMaterial.__initDefine__();
  31743. PixelLineMaterial.__initDefine__();
  31744. SkyBoxMaterial.__initDefine__();
  31745. Command.__init__();
  31746. Laya.ClassUtils.regClass("Laya.SkyPanoramicMaterial", SkyPanoramicMaterial);
  31747. Laya.ClassUtils.regClass("Laya.EffectMaterial", EffectMaterial);
  31748. Laya.ClassUtils.regClass("Laya.UnlitMaterial", UnlitMaterial);
  31749. Laya.ClassUtils.regClass("Laya.BlinnPhongMaterial", BlinnPhongMaterial);
  31750. Laya.ClassUtils.regClass("Laya.SkyProceduralMaterial", SkyProceduralMaterial);
  31751. Laya.ClassUtils.regClass("Laya.PBRStandardMaterial", PBRStandardMaterial);
  31752. Laya.ClassUtils.regClass("Laya.PBRSpecularMaterial", PBRSpecularMaterial);
  31753. Laya.ClassUtils.regClass("Laya.SkyBoxMaterial", SkyBoxMaterial);
  31754. Laya.ClassUtils.regClass("Laya.WaterPrimaryMaterial", WaterPrimaryMaterial);
  31755. Laya.ClassUtils.regClass("Laya.ExtendTerrainMaterial", ExtendTerrainMaterial);
  31756. Laya.ClassUtils.regClass("Laya.ShurikenParticleMaterial", ShurikenParticleMaterial);
  31757. Laya.ClassUtils.regClass("Laya.TrailMaterial", TrailMaterial);
  31758. Laya.ClassUtils.regClass("Laya.PhysicsCollider", PhysicsCollider);
  31759. Laya.ClassUtils.regClass("Laya.Rigidbody3D", Rigidbody3D);
  31760. Laya.ClassUtils.regClass("Laya.CharacterController", CharacterController);
  31761. Laya.ClassUtils.regClass("Laya.Animator", Animator);
  31762. Laya.ClassUtils.regClass("PhysicsCollider", PhysicsCollider);
  31763. Laya.ClassUtils.regClass("CharacterController", CharacterController);
  31764. Laya.ClassUtils.regClass("Animator", Animator);
  31765. Laya.ClassUtils.regClass("Rigidbody3D", Rigidbody3D);
  31766. Laya.ClassUtils.regClass("FixedConstraint", FixedConstraint);
  31767. Laya.ClassUtils.regClass("ConfigurableConstraint", ConfigurableConstraint);
  31768. PixelLineMaterial.defaultMaterial = new PixelLineMaterial();
  31769. BlinnPhongMaterial.defaultMaterial = new BlinnPhongMaterial();
  31770. EffectMaterial.defaultMaterial = new EffectMaterial();
  31771. UnlitMaterial.defaultMaterial = new UnlitMaterial();
  31772. ShurikenParticleMaterial.defaultMaterial = new ShurikenParticleMaterial();
  31773. TrailMaterial.defaultMaterial = new TrailMaterial();
  31774. SkyProceduralMaterial.defaultMaterial = new SkyProceduralMaterial();
  31775. SkyBoxMaterial.defaultMaterial = new SkyBoxMaterial();
  31776. WaterPrimaryMaterial.defaultMaterial = new WaterPrimaryMaterial();
  31777. PixelLineMaterial.defaultMaterial.lock = true;
  31778. BlinnPhongMaterial.defaultMaterial.lock = true;
  31779. EffectMaterial.defaultMaterial.lock = true;
  31780. UnlitMaterial.defaultMaterial.lock = true;
  31781. ShurikenParticleMaterial.defaultMaterial.lock = true;
  31782. TrailMaterial.defaultMaterial.lock = true;
  31783. SkyProceduralMaterial.defaultMaterial.lock = true;
  31784. SkyBoxMaterial.defaultMaterial.lock = true;
  31785. WaterPrimaryMaterial.defaultMaterial.lock = true;
  31786. Laya.Texture2D.__init__();
  31787. TextureCube.__init__();
  31788. SkyBox.__init__();
  31789. SkyDome.__init__();
  31790. ScreenQuad.__init__();
  31791. ScreenTriangle.__init__();
  31792. FrustumCulling.__init__();
  31793. HalfFloatUtils.__init__();
  31794. var createMap = Laya.LoaderManager.createMap;
  31795. createMap["lh"] = [Laya3D.HIERARCHY, Scene3DUtils._parse];
  31796. createMap["ls"] = [Laya3D.HIERARCHY, Scene3DUtils._parseScene];
  31797. createMap["lm"] = [Laya3D.MESH, MeshReader._parse];
  31798. createMap["lmat"] = [Laya3D.MATERIAL, Material._parse];
  31799. createMap["jpg"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  31800. createMap["jpeg"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  31801. createMap["bmp"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  31802. createMap["gif"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  31803. createMap["png"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  31804. createMap["dds"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  31805. createMap["ktx"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  31806. createMap["pvr"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  31807. createMap["lani"] = [Laya3D.ANIMATIONCLIP, AnimationClip._parse];
  31808. createMap["lav"] = [Laya3D.AVATAR, Avatar._parse];
  31809. createMap["ltc"] = [Laya3D.TEXTURECUBE, TextureCube._parse];
  31810. createMap["ltcb"] = [Laya3D.TEXTURECUBEBIN, TextureCube._parseBin];
  31811. createMap["ltcb.ls"] = [Laya3D.TEXTURECUBEBIN, TextureCube._parseBin];
  31812. var parserMap = Laya.Loader.parserMap;
  31813. parserMap[Laya3D.HIERARCHY] = Laya3D._loadHierarchy;
  31814. parserMap[Laya3D.MESH] = Laya3D._loadMesh;
  31815. parserMap[Laya3D.MATERIAL] = Laya3D._loadMaterial;
  31816. parserMap[Laya3D.TEXTURECUBE] = Laya3D._loadTextureCube;
  31817. parserMap[Laya3D.TEXTURECUBEBIN] = Laya3D._loadTextureCubeBin;
  31818. parserMap[Laya3D.TEXTURE2D] = Laya3D._loadTexture2D;
  31819. parserMap[Laya3D.ANIMATIONCLIP] = Laya3D._loadAnimationClip;
  31820. parserMap[Laya3D.AVATAR] = Laya3D._loadAvatar;
  31821. Laya3D._innerFirstLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  31822. Laya3D._innerSecondLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  31823. Laya3D._innerThirdLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  31824. Laya3D._innerFourthLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  31825. }
  31826. static enableNative3D() {
  31827. var shaderData = ShaderData;
  31828. var shader3D = ShaderInstance;
  31829. var skinnedMeshRender = SkinnedMeshRenderer;
  31830. var avatar = Avatar;
  31831. var frustumCulling = FrustumCulling;
  31832. if (Laya.Render.supportWebGLPlusRendering) {
  31833. shaderData.prototype._initData = shaderData.prototype._initDataForNative;
  31834. shaderData.prototype.setBool = shaderData.prototype.setBoolForNative;
  31835. shaderData.prototype.getBool = shaderData.prototype.getBoolForNative;
  31836. shaderData.prototype.setInt = shaderData.prototype.setIntForNative;
  31837. shaderData.prototype.getInt = shaderData.prototype.getIntForNative;
  31838. shaderData.prototype.setNumber = shaderData.prototype.setNumberForNative;
  31839. shaderData.prototype.getNumber = shaderData.prototype.getNumberForNative;
  31840. shaderData.prototype.setVector = shaderData.prototype.setVectorForNative;
  31841. shaderData.prototype.getVector = shaderData.prototype.getVectorForNative;
  31842. shaderData.prototype.setVector2 = shaderData.prototype.setVector2ForNative;
  31843. shaderData.prototype.getVector2 = shaderData.prototype.getVector2ForNative;
  31844. shaderData.prototype.setVector3 = shaderData.prototype.setVector3ForNative;
  31845. shaderData.prototype.getVector3 = shaderData.prototype.getVector3ForNative;
  31846. shaderData.prototype.setQuaternion = shaderData.prototype.setQuaternionForNative;
  31847. shaderData.prototype.getQuaternion = shaderData.prototype.getQuaternionForNative;
  31848. shaderData.prototype.setMatrix4x4 = shaderData.prototype.setMatrix4x4ForNative;
  31849. shaderData.prototype.getMatrix4x4 = shaderData.prototype.getMatrix4x4ForNative;
  31850. shaderData.prototype.setBuffer = shaderData.prototype.setBufferForNative;
  31851. shaderData.prototype.getBuffer = shaderData.prototype.getBufferForNative;
  31852. shaderData.prototype.setTexture = shaderData.prototype.setTextureForNative;
  31853. shaderData.prototype.getTexture = shaderData.prototype.getTextureForNative;
  31854. shaderData.prototype.setAttribute = shaderData.prototype.setAttributeForNative;
  31855. shaderData.prototype.getAttribute = shaderData.prototype.getAttributeForNative;
  31856. shaderData.prototype.cloneTo = shaderData.prototype.cloneToForNative;
  31857. shaderData.prototype.getData = shaderData.prototype.getDataForNative;
  31858. shader3D.prototype._uniformMatrix2fv = shader3D.prototype._uniformMatrix2fvForNative;
  31859. shader3D.prototype._uniformMatrix3fv = shader3D.prototype._uniformMatrix3fvForNative;
  31860. shader3D.prototype._uniformMatrix4fv = shader3D.prototype._uniformMatrix4fvForNative;
  31861. Laya.LayaGLRunner.uploadShaderUniforms = Laya.LayaGLRunner.uploadShaderUniformsForNative;
  31862. }
  31863. if (Laya.Render.supportWebGLPlusCulling) {
  31864. frustumCulling.renderObjectCulling = FrustumCulling.renderObjectCullingNative;
  31865. }
  31866. if (Laya.Render.supportWebGLPlusAnimation) {
  31867. avatar.prototype._cloneDatasToAnimator = avatar.prototype._cloneDatasToAnimatorNative;
  31868. var animationClip = AnimationClip;
  31869. animationClip.prototype._evaluateClipDatasRealTime = animationClip.prototype._evaluateClipDatasRealTimeForNative;
  31870. skinnedMeshRender.prototype._computeSkinnedData = skinnedMeshRender.prototype._computeSkinnedDataForNative;
  31871. }
  31872. }
  31873. static formatRelativePath(base, value) {
  31874. var path;
  31875. path = base + value;
  31876. var char1 = value.charAt(0);
  31877. if (char1 === ".") {
  31878. var parts = path.split("/");
  31879. for (var i = 0, len = parts.length; i < len; i++) {
  31880. if (parts[i] == '..') {
  31881. var index = i - 1;
  31882. if (index > 0 && parts[index] !== '..') {
  31883. parts.splice(index, 2);
  31884. i -= 2;
  31885. }
  31886. }
  31887. }
  31888. path = parts.join('/');
  31889. }
  31890. return path;
  31891. }
  31892. static _endLoad(loader, content = null, subResous = null) {
  31893. if (subResous) {
  31894. for (var i = 0, n = subResous.length; i < n; i++) {
  31895. var resou = Laya.Loader.getRes(subResous[i]);
  31896. (resou) && (resou._removeReference());
  31897. }
  31898. }
  31899. loader.endLoad(content);
  31900. }
  31901. static _eventLoadManagerError(msg) {
  31902. Laya.Laya.loader.event(Laya.Event.ERROR, msg);
  31903. }
  31904. static _addHierarchyInnerUrls(urls, urlMap, urlVersion, hierarchyBasePath, path, type, constructParams = null, propertyParams = null) {
  31905. var formatUrl = Laya3D.formatRelativePath(hierarchyBasePath, path);
  31906. (urlVersion) && (formatUrl = formatUrl + urlVersion);
  31907. urls.push({ url: formatUrl, type: type, constructParams: constructParams, propertyParams: propertyParams });
  31908. urlMap.push(formatUrl);
  31909. return formatUrl;
  31910. }
  31911. static _getSprite3DHierarchyInnerUrls(node, firstLevelUrls, secondLevelUrls, thirdLevelUrls, fourthLelUrls, subUrls, urlVersion, hierarchyBasePath) {
  31912. var i, n;
  31913. var props = node.props;
  31914. switch (node.type) {
  31915. case "Scene3D":
  31916. var lightmaps = props.lightmaps;
  31917. for (i = 0, n = lightmaps.length; i < n; i++) {
  31918. var lightMap = lightmaps[i];
  31919. if (lightMap.path) {
  31920. lightMap.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, lightMap.path, Laya3D.TEXTURE2D, lightMap.constructParams, lightMap.propertyParams);
  31921. }
  31922. else {
  31923. var lightmapColorData = lightMap.color;
  31924. lightmapColorData.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, lightmapColorData.path, Laya3D.TEXTURE2D, lightmapColorData.constructParams, lightmapColorData.propertyParams);
  31925. var lightmapDirectionData = lightMap.direction;
  31926. if (lightmapDirectionData)
  31927. lightmapDirectionData.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, lightmapDirectionData.path, Laya3D.TEXTURE2D, lightmapDirectionData.constructParams, lightmapDirectionData.propertyParams);
  31928. }
  31929. }
  31930. var reflectionTextureData = props.reflectionTexture;
  31931. (reflectionTextureData) && (props.reflection = Laya3D._addHierarchyInnerUrls(thirdLevelUrls, subUrls, urlVersion, hierarchyBasePath, reflectionTextureData, Laya3D.TEXTURECUBE));
  31932. var reflectionData = props.reflection;
  31933. (reflectionData) && (props.reflection = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, reflectionData, Laya3D.TEXTURECUBEBIN));
  31934. if (props.sky) {
  31935. var skyboxMaterial = props.sky.material;
  31936. (skyboxMaterial) && (skyboxMaterial.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, skyboxMaterial.path, Laya3D.MATERIAL));
  31937. }
  31938. break;
  31939. case "Camera":
  31940. var skyboxMatData = props.skyboxMaterial;
  31941. (skyboxMatData) && (skyboxMatData.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, skyboxMatData.path, Laya3D.MATERIAL));
  31942. break;
  31943. case "TrailSprite3D":
  31944. case "MeshSprite3D":
  31945. case "SkinnedMeshSprite3D":
  31946. var meshPath = props.meshPath;
  31947. (meshPath) && (props.meshPath = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, meshPath, Laya3D.MESH));
  31948. var materials = props.materials;
  31949. if (materials)
  31950. for (i = 0, n = materials.length; i < n; i++)
  31951. materials[i].path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, materials[i].path, Laya3D.MATERIAL);
  31952. break;
  31953. case "ShuriKenParticle3D":
  31954. if (props.main) {
  31955. var resources = props.renderer.resources;
  31956. var mesh = resources.mesh;
  31957. var material = resources.material;
  31958. (mesh) && (resources.mesh = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, mesh, Laya3D.MESH));
  31959. (material) && (resources.material = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, material, Laya3D.MATERIAL));
  31960. }
  31961. else {
  31962. var parMeshPath = props.meshPath;
  31963. (parMeshPath) && (props.meshPath = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, parMeshPath, Laya3D.MESH));
  31964. props.material.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, props.material.path, Laya3D.MATERIAL);
  31965. }
  31966. break;
  31967. case "Terrain":
  31968. Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, props.dataPath, Laya3D.TERRAINRES);
  31969. break;
  31970. }
  31971. var components = node.components;
  31972. if (components) {
  31973. for (var k = 0, p = components.length; k < p; k++) {
  31974. var component = components[k];
  31975. switch (component.type) {
  31976. case "Animator":
  31977. var avatarPath = component.avatarPath;
  31978. var avatarData = component.avatar;
  31979. (avatarData) && (avatarData.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, avatarData.path, Laya3D.AVATAR));
  31980. var clipPaths = component.clipPaths;
  31981. if (!clipPaths) {
  31982. var layersData = component.layers;
  31983. for (i = 0; i < layersData.length; i++) {
  31984. var states = layersData[i].states;
  31985. for (var j = 0, m = states.length; j < m; j++) {
  31986. var clipPath = states[j].clipPath;
  31987. (clipPath) && (states[j].clipPath = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, clipPath, Laya3D.ANIMATIONCLIP));
  31988. }
  31989. }
  31990. }
  31991. else {
  31992. for (i = 0, n = clipPaths.length; i < n; i++)
  31993. clipPaths[i] = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, clipPaths[i], Laya3D.ANIMATIONCLIP);
  31994. }
  31995. break;
  31996. case "PhysicsCollider":
  31997. case "Rigidbody3D":
  31998. case "CharacterController":
  31999. var shapes = component.shapes;
  32000. for (i = 0; i < shapes.length; i++) {
  32001. var shape = shapes[i];
  32002. if (shape.type === "MeshColliderShape") {
  32003. var mesh = shape.mesh;
  32004. (mesh) && (shape.mesh = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, mesh, Laya3D.MESH));
  32005. }
  32006. }
  32007. break;
  32008. }
  32009. }
  32010. }
  32011. var children = node.child;
  32012. for (i = 0, n = children.length; i < n; i++)
  32013. Laya3D._getSprite3DHierarchyInnerUrls(children[i], firstLevelUrls, secondLevelUrls, thirdLevelUrls, fourthLelUrls, subUrls, urlVersion, hierarchyBasePath);
  32014. }
  32015. static _loadHierarchy(loader) {
  32016. loader._originType = loader.type;
  32017. loader.on(Laya.Event.LOADED, null, Laya3D._onHierarchylhLoaded, [loader]);
  32018. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  32019. }
  32020. static _onHierarchylhLoaded(loader, lhData) {
  32021. var url = loader.url;
  32022. var urlVersion = Utils3D.getURLVerion(url);
  32023. var hierarchyBasePath = Laya.URL.getPath(url);
  32024. var firstLevUrls = [];
  32025. var secondLevUrls = [];
  32026. var thirdLevUrls = [];
  32027. var forthLevUrls = [];
  32028. var subUrls = [];
  32029. Laya3D._getSprite3DHierarchyInnerUrls(lhData.data, firstLevUrls, secondLevUrls, thirdLevUrls, forthLevUrls, subUrls, urlVersion, hierarchyBasePath);
  32030. var urlCount = firstLevUrls.length + secondLevUrls.length + forthLevUrls.length;
  32031. var totalProcessCount = urlCount + 1;
  32032. var weight = 1 / totalProcessCount;
  32033. Laya3D._onProcessChange(loader, 0, weight, 1.0);
  32034. if (forthLevUrls.length > 0) {
  32035. var processCeil = urlCount / totalProcessCount;
  32036. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, weight, processCeil], false);
  32037. 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);
  32038. }
  32039. else {
  32040. Laya3D._onHierarchyInnerForthLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, weight, processCeil);
  32041. }
  32042. }
  32043. static _onHierarchyInnerForthLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, processOffset, processCeil) {
  32044. (processHandler) && (processHandler.recover());
  32045. if (thirdLevUrls.length > 0) {
  32046. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  32047. 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);
  32048. }
  32049. else {
  32050. Laya3D._onHierarchyInnerThirdLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset, processCeil);
  32051. }
  32052. }
  32053. static _onHierarchyInnerThirdLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset, processCeil) {
  32054. (processHandler) && (processHandler.recover());
  32055. if (secondLevUrls.length > 0) {
  32056. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  32057. 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);
  32058. }
  32059. else {
  32060. Laya3D._onHierarchyInnerSecondLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, processOffset, processCeil);
  32061. }
  32062. }
  32063. static _onHierarchyInnerSecondLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, processOffset, processCeil) {
  32064. (processHandler) && (processHandler.recover());
  32065. if (firstLevUrls.length > 0) {
  32066. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  32067. Laya3D._innerFirstLevelLoaderManager._create(firstLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerFirstLevResouLoaded, [loader, process, lhData, subUrls]), processHandler, null, null, null, 1, true);
  32068. }
  32069. else {
  32070. Laya3D._onHierarchyInnerFirstLevResouLoaded(loader, null, lhData, subUrls);
  32071. }
  32072. }
  32073. static _onHierarchyInnerFirstLevResouLoaded(loader, processHandler, lhData, subUrls) {
  32074. (processHandler) && (processHandler.recover());
  32075. loader._cache = loader._createCache;
  32076. var item = lhData.data.type === "Scene3D" ? Scene3DUtils._parseScene(lhData, loader._propertyParams, loader._constructParams) : Scene3DUtils._parse(lhData, loader._propertyParams, loader._constructParams);
  32077. Laya3D._endLoad(loader, item, subUrls);
  32078. }
  32079. static _loadMesh(loader) {
  32080. loader.on(Laya.Event.LOADED, null, Laya3D._onMeshLmLoaded, [loader]);
  32081. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  32082. }
  32083. static _onMeshLmLoaded(loader, lmData) {
  32084. loader._cache = loader._createCache;
  32085. var mesh = MeshReader._parse(lmData, loader._propertyParams, loader._constructParams);
  32086. Laya3D._endLoad(loader, mesh);
  32087. }
  32088. static _loadMaterial(loader) {
  32089. loader.on(Laya.Event.LOADED, null, Laya3D._onMaterilLmatLoaded, [loader]);
  32090. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  32091. }
  32092. static _onMaterilLmatLoaded(loader, lmatData) {
  32093. var url = loader.url;
  32094. var urlVersion = Utils3D.getURLVerion(url);
  32095. var materialBasePath = Laya.URL.getPath(url);
  32096. var urls = [];
  32097. var subUrls = [];
  32098. var customProps = lmatData.customProps;
  32099. var formatSubUrl;
  32100. var version = lmatData.version;
  32101. switch (version) {
  32102. case "LAYAMATERIAL:01":
  32103. case "LAYAMATERIAL:02":
  32104. var i, n;
  32105. var textures = lmatData.props.textures;
  32106. if (textures) {
  32107. for (i = 0, n = textures.length; i < n; i++) {
  32108. var tex2D = textures[i];
  32109. var tex2DPath = tex2D.path;
  32110. if (tex2DPath) {
  32111. formatSubUrl = Laya3D.formatRelativePath(materialBasePath, tex2DPath);
  32112. (urlVersion) && (formatSubUrl = formatSubUrl + urlVersion);
  32113. urls.push({ url: formatSubUrl, constructParams: tex2D.constructParams, propertyParams: tex2D.propertyParams });
  32114. subUrls.push(formatSubUrl);
  32115. tex2D.path = formatSubUrl;
  32116. }
  32117. }
  32118. }
  32119. break;
  32120. default:
  32121. throw new Error("Laya3D:unkonwn version.");
  32122. }
  32123. var urlCount = urls.length;
  32124. var totalProcessCount = urlCount + 1;
  32125. var lmatWeight = 1 / totalProcessCount;
  32126. Laya3D._onProcessChange(loader, 0, lmatWeight, 1.0);
  32127. if (urlCount > 0) {
  32128. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, lmatWeight, urlCount / totalProcessCount], false);
  32129. Laya3D._innerFourthLevelLoaderManager._create(urls, false, Laya.Handler.create(null, Laya3D._onMateialTexturesLoaded, [loader, processHandler, lmatData, subUrls]), processHandler, null, null, null, 1, true);
  32130. }
  32131. else {
  32132. Laya3D._onMateialTexturesLoaded(loader, null, lmatData, null);
  32133. }
  32134. }
  32135. static _onMateialTexturesLoaded(loader, processHandler, lmatData, subUrls) {
  32136. loader._cache = loader._createCache;
  32137. var mat = Material._parse(lmatData, loader._propertyParams, loader._constructParams);
  32138. Laya3D._endLoad(loader, mat, subUrls);
  32139. (processHandler) && (processHandler.recover());
  32140. }
  32141. static _loadAvatar(loader) {
  32142. loader.on(Laya.Event.LOADED, null, function (data) {
  32143. loader._cache = loader._createCache;
  32144. var avatar = Avatar._parse(data, loader._propertyParams, loader._constructParams);
  32145. Laya3D._endLoad(loader, avatar);
  32146. });
  32147. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  32148. }
  32149. static _loadAnimationClip(loader) {
  32150. loader.on(Laya.Event.LOADED, null, function (data) {
  32151. loader._cache = loader._createCache;
  32152. var clip = AnimationClip._parse(data, loader._propertyParams, loader._constructParams);
  32153. Laya3D._endLoad(loader, clip);
  32154. });
  32155. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  32156. }
  32157. static _loadTexture2D(loader) {
  32158. var url = loader.url;
  32159. var index = url.lastIndexOf('.') + 1;
  32160. var verIndex = url.indexOf('?');
  32161. var endIndex = verIndex == -1 ? url.length : verIndex;
  32162. var ext = url.substr(index, endIndex - index);
  32163. var type;
  32164. switch (ext) {
  32165. case "jpg":
  32166. case "jpeg":
  32167. case "bmp":
  32168. case "gif":
  32169. case "png":
  32170. type = "nativeimage";
  32171. break;
  32172. case "dds":
  32173. case "ktx":
  32174. case "pvr":
  32175. type = Laya.Loader.BUFFER;
  32176. break;
  32177. }
  32178. loader.on(Laya.Event.LOADED, null, function (image) {
  32179. loader._cache = loader._createCache;
  32180. var tex = Laya.Texture2D._parse(image, loader._propertyParams, loader._constructParams);
  32181. Laya3D._endLoad(loader, tex);
  32182. });
  32183. loader.load(loader.url, type, false, null, true);
  32184. }
  32185. static _loadTextureCube(loader) {
  32186. loader.on(Laya.Event.LOADED, null, Laya3D._onTextureCubeLtcLoaded, [loader]);
  32187. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  32188. }
  32189. static _loadTextureCubeBin(loader) {
  32190. loader.on(Laya.Event.LOADED, null, (data) => {
  32191. loader._cache = loader._createCache;
  32192. var byte = new Laya.Byte(data);
  32193. var version = byte.readUTFString();
  32194. if (version !== "LAYATEXTURECUBE:0000")
  32195. throw "Laya3D:unknow version.";
  32196. var format = byte.readUint8();
  32197. var mipCount = byte.getUint8();
  32198. var size = byte.readUint16();
  32199. var filterMode = byte.getUint8();
  32200. var warpModeU = byte.getUint8();
  32201. var warpModev = byte.getUint8();
  32202. var anisoLevel = byte.getUint8();
  32203. var cubemap = new TextureCube(size, format, mipCount > 1 ? true : false);
  32204. cubemap.filterMode = filterMode;
  32205. cubemap.wrapModeU = warpModeU;
  32206. cubemap.wrapModeV = warpModev;
  32207. cubemap.anisoLevel = anisoLevel;
  32208. var pos = byte.pos;
  32209. var mipSize = size;
  32210. for (var i = 0; i < mipCount; i++) {
  32211. var uint8Arrays = new Array(6);
  32212. var mipPixelLength = mipSize * mipSize * cubemap._getFormatByteCount();
  32213. for (var j = 0; j < 6; j++) {
  32214. uint8Arrays[j] = new Uint8Array(data, pos, mipPixelLength);
  32215. pos += mipPixelLength;
  32216. }
  32217. cubemap.setSixSidePixels(uint8Arrays, i);
  32218. mipSize /= 2;
  32219. }
  32220. Laya3D._endLoad(loader, cubemap);
  32221. });
  32222. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  32223. }
  32224. static _onTextureCubeLtcLoaded(loader, ltcData) {
  32225. var ltcBasePath = Laya.URL.getPath(loader.url);
  32226. 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)];
  32227. var ltcWeight = 1.0 / 7.0;
  32228. Laya3D._onProcessChange(loader, 0, ltcWeight, 1.0);
  32229. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, ltcWeight, 6 / 7], false);
  32230. Laya3D._innerFourthLevelLoaderManager.load(urls, Laya.Handler.create(null, Laya3D._onTextureCubeImagesLoaded, [loader, urls, processHandler]), processHandler, "nativeimage");
  32231. }
  32232. static _onTextureCubeImagesLoaded(loader, urls, processHandler) {
  32233. var images = new Array(6);
  32234. for (var i = 0; i < 6; i++)
  32235. images[i] = Laya.Loader.getRes(urls[i]);
  32236. loader._cache = loader._createCache;
  32237. var tex = TextureCube._parse(images, loader._propertyParams, loader._constructParams);
  32238. processHandler.recover();
  32239. for (i = 0; i < 6; i++)
  32240. Laya.Loader.clearRes(urls[i]);
  32241. Laya3D._endLoad(loader, tex);
  32242. }
  32243. static _onProcessChange(loader, offset, weight, process) {
  32244. process = offset + process * weight;
  32245. (process < 1.0) && (loader.event(Laya.Event.PROGRESS, process * 2 / 3 + 1 / 3));
  32246. }
  32247. static init(width, height, config = null, compolete = null) {
  32248. if (Laya3D._isInit) {
  32249. compolete && compolete.run();
  32250. return;
  32251. }
  32252. Laya3D._isInit = true;
  32253. (config) && (config.cloneTo(Config3D._config));
  32254. config = Config3D._config;
  32255. FrustumCulling.debugFrustumCulling = config.debugFrustumCulling;
  32256. Laya3D._editerEnvironment = config._editerEnvironment;
  32257. Scene3D.octreeCulling = config.octreeCulling;
  32258. Scene3D.octreeInitialSize = config.octreeInitialSize;
  32259. Scene3D.octreeInitialCenter = config.octreeInitialCenter;
  32260. Scene3D.octreeMinNodeSize = config.octreeMinNodeSize;
  32261. Scene3D.octreeLooseness = config.octreeLooseness;
  32262. var physics3D = window.Physics3D;
  32263. if (physics3D == null || config.isUseCannonPhysicsEngine) {
  32264. Physics3D._enablePhysics = false;
  32265. Laya3D.__init__(width, height, config);
  32266. compolete && compolete.run();
  32267. }
  32268. else {
  32269. Physics3D._enablePhysics = true;
  32270. physics3D(config.defaultPhysicsMemory * 16, BulletInteractive._interactive).then(function () {
  32271. Laya3D.__init__(width, height, config);
  32272. compolete && compolete.run();
  32273. });
  32274. }
  32275. }
  32276. }
  32277. Laya3D.HIERARCHY = "HIERARCHY";
  32278. Laya3D.MESH = "MESH";
  32279. Laya3D.MATERIAL = "MATERIAL";
  32280. Laya3D.TEXTURE2D = "TEXTURE2D";
  32281. Laya3D.TEXTURECUBE = "TEXTURECUBE";
  32282. Laya3D.TEXTURECUBEBIN = "TEXTURECUBEBIN";
  32283. Laya3D.ANIMATIONCLIP = "ANIMATIONCLIP";
  32284. Laya3D.AVATAR = "AVATAR";
  32285. Laya3D.TERRAINHEIGHTDATA = "TERRAINHEIGHTDATA";
  32286. Laya3D.TERRAINRES = "TERRAIN";
  32287. Laya3D._innerFirstLevelLoaderManager = new Laya.LoaderManager();
  32288. Laya3D._innerSecondLevelLoaderManager = new Laya.LoaderManager();
  32289. Laya3D._innerThirdLevelLoaderManager = new Laya.LoaderManager();
  32290. Laya3D._innerFourthLevelLoaderManager = new Laya.LoaderManager();
  32291. Laya3D._isInit = false;
  32292. Laya3D._editerEnvironment = false;
  32293. Laya3D.physicsSettings = new PhysicsSettings();
  32294. window.Laya3D = Laya3D;
  32295. class CastShadowList extends SingletonList {
  32296. constructor() {
  32297. super();
  32298. }
  32299. add(element) {
  32300. var index = element._indexInCastShadowList;
  32301. if (index !== -1)
  32302. throw "CastShadowList:element has in CastShadowList.";
  32303. this._add(element);
  32304. element._indexInCastShadowList = this.length++;
  32305. }
  32306. remove(element) {
  32307. var index = element._indexInCastShadowList;
  32308. this.length--;
  32309. if (index !== this.length) {
  32310. var end = this.elements[this.length];
  32311. this.elements[index] = end;
  32312. end._indexInCastShadowList = index;
  32313. }
  32314. element._indexInCastShadowList = -1;
  32315. }
  32316. }
  32317. class AnimatorStateScript {
  32318. constructor() {
  32319. }
  32320. onStateEnter() {
  32321. }
  32322. onStateUpdate() {
  32323. }
  32324. onStateExit() {
  32325. }
  32326. }
  32327. class Script3D extends Laya.Component {
  32328. constructor() {
  32329. super(...arguments);
  32330. this._indexInPool = -1;
  32331. }
  32332. get isSingleton() {
  32333. return false;
  32334. }
  32335. _checkProcessTriggers() {
  32336. var prototype = Script3D.prototype;
  32337. if (this.onTriggerEnter !== prototype.onTriggerEnter)
  32338. return true;
  32339. if (this.onTriggerStay !== prototype.onTriggerStay)
  32340. return true;
  32341. if (this.onTriggerExit !== prototype.onTriggerExit)
  32342. return true;
  32343. return false;
  32344. }
  32345. _checkProcessCollisions() {
  32346. var prototype = Script3D.prototype;
  32347. if (this.onCollisionEnter !== prototype.onCollisionEnter)
  32348. return true;
  32349. if (this.onCollisionStay !== prototype.onCollisionStay)
  32350. return true;
  32351. if (this.onCollisionExit !== prototype.onCollisionExit)
  32352. return true;
  32353. return false;
  32354. }
  32355. _onAwake() {
  32356. this.onAwake();
  32357. if (this.onStart !== Script3D.prototype.onStart)
  32358. Laya.Laya.startTimer.callLater(this, this.onStart);
  32359. }
  32360. _onEnable() {
  32361. this.owner._scene._addScript(this);
  32362. this.onEnable();
  32363. }
  32364. _onDisable() {
  32365. this.owner._scene._removeScript(this);
  32366. this.owner.offAllCaller(this);
  32367. this.onDisable();
  32368. }
  32369. _onDestroy() {
  32370. var scripts = this.owner._scripts;
  32371. scripts.splice(scripts.indexOf(this), 1);
  32372. var sprite = this.owner;
  32373. sprite._needProcessTriggers = false;
  32374. for (var i = 0, n = scripts.length; i < n; i++) {
  32375. if (scripts[i]._checkProcessTriggers()) {
  32376. sprite._needProcessTriggers = true;
  32377. break;
  32378. }
  32379. }
  32380. sprite._needProcessCollisions = false;
  32381. for (i = 0, n = scripts.length; i < n; i++) {
  32382. if (scripts[i]._checkProcessCollisions()) {
  32383. sprite._needProcessCollisions = true;
  32384. break;
  32385. }
  32386. }
  32387. this.onDestroy();
  32388. }
  32389. _isScript() {
  32390. return true;
  32391. }
  32392. _onAdded() {
  32393. var sprite = this.owner;
  32394. var scripts = sprite._scripts;
  32395. scripts || (sprite._scripts = scripts = []);
  32396. scripts.push(this);
  32397. if (!sprite._needProcessCollisions)
  32398. sprite._needProcessCollisions = this._checkProcessCollisions();
  32399. if (!sprite._needProcessTriggers)
  32400. sprite._needProcessTriggers = this._checkProcessTriggers();
  32401. }
  32402. onAwake() {
  32403. }
  32404. onEnable() {
  32405. }
  32406. onStart() {
  32407. }
  32408. onTriggerEnter(other) {
  32409. }
  32410. onTriggerStay(other) {
  32411. }
  32412. onTriggerExit(other) {
  32413. }
  32414. onCollisionEnter(collision) {
  32415. }
  32416. onCollisionStay(collision) {
  32417. }
  32418. onCollisionExit(collision) {
  32419. }
  32420. onJointBreak() {
  32421. }
  32422. onMouseDown() {
  32423. }
  32424. onMouseDrag() {
  32425. }
  32426. onMouseClick() {
  32427. }
  32428. onMouseUp() {
  32429. }
  32430. onMouseEnter() {
  32431. }
  32432. onMouseOver() {
  32433. }
  32434. onMouseOut() {
  32435. }
  32436. onUpdate() {
  32437. }
  32438. onLateUpdate() {
  32439. }
  32440. onPreRender() {
  32441. }
  32442. onPostRender() {
  32443. }
  32444. onDisable() {
  32445. }
  32446. onDestroy() {
  32447. }
  32448. }
  32449. class HeightMap {
  32450. constructor(width, height, minHeight, maxHeight) {
  32451. this._datas = [];
  32452. this._w = width;
  32453. this._h = height;
  32454. this._minHeight = minHeight;
  32455. this._maxHeight = maxHeight;
  32456. }
  32457. static creatFromMesh(mesh, width, height, outCellSize) {
  32458. var vertices = [];
  32459. var indexs = [];
  32460. var submesheCount = mesh.subMeshCount;
  32461. for (var i = 0; i < submesheCount; i++) {
  32462. var subMesh = mesh.getSubMesh(i);
  32463. var vertexBuffer = subMesh._vertexBuffer;
  32464. var verts = vertexBuffer.getFloat32Data();
  32465. var subMeshVertices = [];
  32466. for (var j = 0; j < verts.length; j += vertexBuffer.vertexDeclaration.vertexStride / 4) {
  32467. var position = new Vector3(verts[j + 0], verts[j + 1], verts[j + 2]);
  32468. subMeshVertices.push(position);
  32469. }
  32470. vertices.push(subMeshVertices);
  32471. var ib = subMesh._indexBuffer;
  32472. indexs.push(ib.getData());
  32473. }
  32474. var bounds = mesh.bounds;
  32475. var minX = bounds.getMin().x;
  32476. var minZ = bounds.getMin().z;
  32477. var maxX = bounds.getMax().x;
  32478. var maxZ = bounds.getMax().z;
  32479. var minY = bounds.getMin().y;
  32480. var maxY = bounds.getMax().y;
  32481. var widthSize = maxX - minX;
  32482. var heightSize = maxZ - minZ;
  32483. var cellWidth = outCellSize.x = widthSize / (width - 1);
  32484. var cellHeight = outCellSize.y = heightSize / (height - 1);
  32485. var heightMap = new HeightMap(width, height, minY, maxY);
  32486. var ray = HeightMap._tempRay;
  32487. var rayDir = ray.direction;
  32488. rayDir.x = 0;
  32489. rayDir.y = -1;
  32490. rayDir.z = 0;
  32491. const heightOffset = 0.1;
  32492. var rayY = maxY + heightOffset;
  32493. ray.origin.y = rayY;
  32494. for (var h = 0; h < height; h++) {
  32495. var posZ = minZ + h * cellHeight;
  32496. heightMap._datas[h] = [];
  32497. for (var w = 0; w < width; w++) {
  32498. var posX = minX + w * cellWidth;
  32499. var rayOri = ray.origin;
  32500. rayOri.x = posX;
  32501. rayOri.z = posZ;
  32502. var closestIntersection = HeightMap._getPosition(ray, vertices, indexs);
  32503. heightMap._datas[h][w] = (closestIntersection === Number.MAX_VALUE) ? NaN : rayY - closestIntersection;
  32504. }
  32505. }
  32506. return heightMap;
  32507. }
  32508. static createFromImage(texture, minHeight, maxHeight) {
  32509. var textureWidth = texture.width;
  32510. var textureHeight = texture.height;
  32511. var heightMap = new HeightMap(textureWidth, textureHeight, minHeight, maxHeight);
  32512. var compressionRatio = (maxHeight - minHeight) / 254;
  32513. var pixelsInfo = texture.getPixels();
  32514. var index = 0;
  32515. for (var h = 0; h < textureHeight; h++) {
  32516. var colDatas = heightMap._datas[h] = [];
  32517. for (var w = 0; w < textureWidth; w++) {
  32518. var r = pixelsInfo[index++];
  32519. var g = pixelsInfo[index++];
  32520. var b = pixelsInfo[index++];
  32521. var a = pixelsInfo[index++];
  32522. if (r == 255 && g == 255 && b == 255 && a == 255)
  32523. colDatas[w] = NaN;
  32524. else {
  32525. colDatas[w] = (r + g + b) / 3 * compressionRatio + minHeight;
  32526. }
  32527. }
  32528. }
  32529. return heightMap;
  32530. }
  32531. static _getPosition(ray, vertices, indexs) {
  32532. var closestIntersection = Number.MAX_VALUE;
  32533. for (var i = 0; i < vertices.length; i++) {
  32534. var subMeshVertices = vertices[i];
  32535. var subMeshIndexes = indexs[i];
  32536. for (var j = 0; j < subMeshIndexes.length; j += 3) {
  32537. var vertex1 = subMeshVertices[subMeshIndexes[j + 0]];
  32538. var vertex2 = subMeshVertices[subMeshIndexes[j + 1]];
  32539. var vertex3 = subMeshVertices[subMeshIndexes[j + 2]];
  32540. var intersection = Picker.rayIntersectsTriangle(ray, vertex1, vertex2, vertex3);
  32541. if (!isNaN(intersection) && intersection < closestIntersection) {
  32542. closestIntersection = intersection;
  32543. }
  32544. }
  32545. }
  32546. return closestIntersection;
  32547. }
  32548. get width() {
  32549. return this._w;
  32550. }
  32551. get height() {
  32552. return this._h;
  32553. }
  32554. get maxHeight() {
  32555. return this._maxHeight;
  32556. }
  32557. get minHeight() {
  32558. return this._minHeight;
  32559. }
  32560. _inBounds(row, col) {
  32561. return row >= 0 && row < this._h && col >= 0 && col < this._w;
  32562. }
  32563. getHeight(row, col) {
  32564. if (this._inBounds(row, col))
  32565. return this._datas[row][col];
  32566. else
  32567. return NaN;
  32568. }
  32569. }
  32570. HeightMap._tempRay = new Ray(new Vector3(), new Vector3());
  32571. class MeshTerrainSprite3D extends MeshSprite3D {
  32572. constructor(mesh, heightMap, name = null) {
  32573. super(mesh, name);
  32574. this._heightMap = heightMap;
  32575. this._cellSize = new Vector2();
  32576. }
  32577. static createFromMesh(mesh, heightMapWidth, heightMapHeight, name = null) {
  32578. var meshTerrainSprite3D = new MeshTerrainSprite3D(mesh, null, name);
  32579. meshTerrainSprite3D._initCreateFromMesh(heightMapWidth, heightMapHeight);
  32580. return meshTerrainSprite3D;
  32581. }
  32582. static createFromMeshAndHeightMap(mesh, texture, minHeight, maxHeight, name = null) {
  32583. var meshTerrainSprite3D = new MeshTerrainSprite3D(mesh, null, name);
  32584. meshTerrainSprite3D._initCreateFromMeshHeightMap(texture, minHeight, maxHeight);
  32585. return meshTerrainSprite3D;
  32586. }
  32587. get minX() {
  32588. var worldMat = this.transform.worldMatrix;
  32589. var worldMatE = worldMat.elements;
  32590. return this._minX * this._getScaleX() + worldMatE[12];
  32591. }
  32592. get minZ() {
  32593. var worldMat = this.transform.worldMatrix;
  32594. var worldMatE = worldMat.elements;
  32595. return this._minZ * this._getScaleZ() + worldMatE[14];
  32596. }
  32597. get width() {
  32598. return (this._heightMap.width - 1) * this._cellSize.x * this._getScaleX();
  32599. }
  32600. get depth() {
  32601. return (this._heightMap.height - 1) * this._cellSize.y * this._getScaleZ();
  32602. }
  32603. _disableRotation() {
  32604. var rotation = this.transform.rotation;
  32605. rotation.x = 0;
  32606. rotation.y = 0;
  32607. rotation.z = 0;
  32608. rotation.w = 1;
  32609. this.transform.rotation = rotation;
  32610. }
  32611. _getScaleX() {
  32612. var worldMat = this.transform.worldMatrix;
  32613. var worldMatE = worldMat.elements;
  32614. var m11 = worldMatE[0];
  32615. var m12 = worldMatE[1];
  32616. var m13 = worldMatE[2];
  32617. return Math.sqrt((m11 * m11) + (m12 * m12) + (m13 * m13));
  32618. }
  32619. _getScaleZ() {
  32620. var worldMat = this.transform.worldMatrix;
  32621. var worldMatE = worldMat.elements;
  32622. var m31 = worldMatE[8];
  32623. var m32 = worldMatE[9];
  32624. var m33 = worldMatE[10];
  32625. return Math.sqrt((m31 * m31) + (m32 * m32) + (m33 * m33));
  32626. }
  32627. _initCreateFromMesh(heightMapWidth, heightMapHeight) {
  32628. this._heightMap = HeightMap.creatFromMesh(this.meshFilter.sharedMesh, heightMapWidth, heightMapHeight, this._cellSize);
  32629. var boundingBox = this.meshFilter.sharedMesh.bounds;
  32630. var min = boundingBox.getMin();
  32631. var max = boundingBox.getMax();
  32632. this._minX = min.x;
  32633. this._minZ = min.z;
  32634. }
  32635. _initCreateFromMeshHeightMap(texture, minHeight, maxHeight) {
  32636. var boundingBox = this.meshFilter.sharedMesh.bounds;
  32637. this._heightMap = HeightMap.createFromImage(texture, minHeight, maxHeight);
  32638. this._computeCellSize(boundingBox);
  32639. var min = boundingBox.getMin();
  32640. var max = boundingBox.getMax();
  32641. this._minX = min.x;
  32642. this._minZ = min.z;
  32643. }
  32644. _computeCellSize(boundingBox) {
  32645. var min = boundingBox.getMin();
  32646. var max = boundingBox.getMax();
  32647. var minX = min.x;
  32648. var minZ = min.z;
  32649. var maxX = max.x;
  32650. var maxZ = max.z;
  32651. var widthSize = maxX - minX;
  32652. var heightSize = maxZ - minZ;
  32653. this._cellSize.x = widthSize / (this._heightMap.width - 1);
  32654. this._cellSize.y = heightSize / (this._heightMap.height - 1);
  32655. }
  32656. _update(state) {
  32657. this._disableRotation();
  32658. }
  32659. getHeight(x, z) {
  32660. MeshTerrainSprite3D._tempVector3.x = x;
  32661. MeshTerrainSprite3D._tempVector3.y = 0;
  32662. MeshTerrainSprite3D._tempVector3.z = z;
  32663. this._disableRotation();
  32664. var worldMat = this.transform.worldMatrix;
  32665. worldMat.invert(MeshTerrainSprite3D._tempMatrix4x4);
  32666. Vector3.transformCoordinate(MeshTerrainSprite3D._tempVector3, MeshTerrainSprite3D._tempMatrix4x4, MeshTerrainSprite3D._tempVector3);
  32667. x = MeshTerrainSprite3D._tempVector3.x;
  32668. z = MeshTerrainSprite3D._tempVector3.z;
  32669. var c = (x - this._minX) / this._cellSize.x;
  32670. var d = (z - this._minZ) / this._cellSize.y;
  32671. var row = Math.floor(d);
  32672. var col = Math.floor(c);
  32673. var s = c - col;
  32674. var t = d - row;
  32675. var uy;
  32676. var vy;
  32677. var worldMatE = worldMat.elements;
  32678. var m21 = worldMatE[4];
  32679. var m22 = worldMatE[5];
  32680. var m23 = worldMatE[6];
  32681. var scaleY = Math.sqrt((m21 * m21) + (m22 * m22) + (m23 * m23));
  32682. var translateY = worldMatE[13];
  32683. var h01 = this._heightMap.getHeight(row, col + 1);
  32684. var h10 = this._heightMap.getHeight((row + 1), col);
  32685. if (isNaN(h01) || isNaN(h10))
  32686. return NaN;
  32687. if (s + t <= 1.0) {
  32688. var h00 = this._heightMap.getHeight(row, col);
  32689. if (isNaN(h00))
  32690. return NaN;
  32691. uy = h01 - h00;
  32692. vy = h10 - h00;
  32693. return (h00 + s * uy + t * vy) * scaleY + translateY;
  32694. }
  32695. else {
  32696. var h11 = this._heightMap.getHeight((row + 1), col + 1);
  32697. if (isNaN(h11))
  32698. return NaN;
  32699. uy = h10 - h11;
  32700. vy = h01 - h11;
  32701. return (h11 + (1.0 - s) * uy + (1.0 - t) * vy) * scaleY + translateY;
  32702. }
  32703. }
  32704. }
  32705. MeshTerrainSprite3D._tempVector3 = new Vector3();
  32706. MeshTerrainSprite3D._tempMatrix4x4 = new Matrix4x4();
  32707. class GradientDataVector2 {
  32708. constructor() {
  32709. this._currentLength = 0;
  32710. this._elements = new Float32Array(12);
  32711. }
  32712. get gradientCount() {
  32713. return this._currentLength / 3;
  32714. }
  32715. add(key, value) {
  32716. if (this._currentLength < 8) {
  32717. if ((this._currentLength === 6) && ((key !== 1))) {
  32718. key = 1;
  32719. console.log("GradientDataVector2 warning:the forth key is be force set to 1.");
  32720. }
  32721. this._elements[this._currentLength++] = key;
  32722. this._elements[this._currentLength++] = value.x;
  32723. this._elements[this._currentLength++] = value.y;
  32724. }
  32725. else {
  32726. console.log("GradientDataVector2 warning:data count must lessEqual than 4");
  32727. }
  32728. }
  32729. cloneTo(destObject) {
  32730. var destGradientDataVector2 = destObject;
  32731. destGradientDataVector2._currentLength = this._currentLength;
  32732. var destElements = destGradientDataVector2._elements;
  32733. for (var i = 0, n = this._elements.length; i < n; i++) {
  32734. destElements[i] = this._elements[i];
  32735. }
  32736. }
  32737. clone() {
  32738. var destGradientDataVector2 = new GradientDataVector2();
  32739. this.cloneTo(destGradientDataVector2);
  32740. return destGradientDataVector2;
  32741. }
  32742. }
  32743. class PixelLineData {
  32744. constructor() {
  32745. this.startPosition = new Vector3();
  32746. this.endPosition = new Vector3();
  32747. this.startColor = new Color();
  32748. this.endColor = new Color();
  32749. }
  32750. cloneTo(destObject) {
  32751. this.startPosition.cloneTo(destObject.startPosition);
  32752. this.endPosition.cloneTo(destObject.endPosition);
  32753. this.startColor.cloneTo(destObject.startColor);
  32754. this.endColor.cloneTo(destObject.endColor);
  32755. }
  32756. }
  32757. class PostProcessEffect {
  32758. constructor() {
  32759. }
  32760. render(context) {
  32761. }
  32762. }
  32763. class BloomEffect extends PostProcessEffect {
  32764. constructor() {
  32765. super();
  32766. this._shader = null;
  32767. this._shaderData = new ShaderData();
  32768. this._linearColor = new Color();
  32769. this._bloomTextureTexelSize = new Vector4();
  32770. this._shaderThreshold = new Vector4();
  32771. this._shaderParams = new Vector4();
  32772. this._pyramid = null;
  32773. this._intensity = 0.0;
  32774. this._threshold = 1.0;
  32775. this._softKnee = 0.5;
  32776. this._diffusion = 7.0;
  32777. this._anamorphicRatio = 0.0;
  32778. this._dirtIntensity = 0.0;
  32779. this._shaderSetting = new Vector4();
  32780. this._dirtTileOffset = new Vector4();
  32781. this.clamp = 65472.0;
  32782. this.color = new Color(1.0, 1.0, 1.0, 1.0);
  32783. this.fastMode = false;
  32784. this.dirtTexture = null;
  32785. this._shader = Shader3D.find("PostProcessBloom");
  32786. this._pyramid = new Array(BloomEffect.MAXPYRAMIDSIZE * 2);
  32787. }
  32788. get intensity() {
  32789. return this._intensity;
  32790. }
  32791. set intensity(value) {
  32792. this._intensity = Math.max(value, 0.0);
  32793. }
  32794. get threshold() {
  32795. return this._threshold;
  32796. }
  32797. set threshold(value) {
  32798. this._threshold = Math.max(value, 0.0);
  32799. }
  32800. get softKnee() {
  32801. return this._softKnee;
  32802. }
  32803. set softKnee(value) {
  32804. this._softKnee = Math.min(Math.max(value, 0.0), 1.0);
  32805. }
  32806. get diffusion() {
  32807. return this._diffusion;
  32808. }
  32809. set diffusion(value) {
  32810. this._diffusion = Math.min(Math.max(value, 1), 10);
  32811. }
  32812. get anamorphicRatio() {
  32813. return this._anamorphicRatio;
  32814. }
  32815. set anamorphicRatio(value) {
  32816. this._anamorphicRatio = Math.min(Math.max(value, -1.0), 1.0);
  32817. }
  32818. get dirtIntensity() {
  32819. return this._dirtIntensity;
  32820. }
  32821. set dirtIntensity(value) {
  32822. this._dirtIntensity = Math.max(value, 0.0);
  32823. }
  32824. render(context) {
  32825. var cmd = context.command;
  32826. var viewport = context.camera.viewport;
  32827. this._shaderData.setTexture(BloomEffect.SHADERVALUE_AUTOEXPOSURETEX, Laya.Texture2D.whiteTexture);
  32828. var ratio = this._anamorphicRatio;
  32829. var rw = ratio < 0 ? -ratio : 0;
  32830. var rh = ratio > 0 ? ratio : 0;
  32831. var tw = Math.floor(viewport.width / (2 - rw));
  32832. var th = Math.floor(viewport.height / (2 - rh));
  32833. var s = Math.max(tw, th);
  32834. var logs;
  32835. logs = Math.log2(s) + this._diffusion - 10;
  32836. var logsInt = Math.floor(logs);
  32837. var iterations = Math.min(Math.max(logsInt, 1), BloomEffect.MAXPYRAMIDSIZE);
  32838. var sampleScale = 0.5 + logs - logsInt;
  32839. this._shaderData.setNumber(BloomEffect.SHADERVALUE_SAMPLESCALE, sampleScale);
  32840. var lthresh = Color.gammaToLinearSpace(this.threshold);
  32841. var knee = lthresh * this._softKnee + 1e-5;
  32842. this._shaderThreshold.setValue(lthresh, lthresh - knee, knee * 2, 0.25 / knee);
  32843. this._shaderData.setVector(BloomEffect.SHADERVALUE_THRESHOLD, this._shaderThreshold);
  32844. var lclamp = Color.gammaToLinearSpace(this.clamp);
  32845. this._shaderParams.setValue(lclamp, 0, 0, 0);
  32846. this._shaderData.setVector(BloomEffect.SHADERVALUE_PARAMS, this._shaderParams);
  32847. var qualityOffset = this.fastMode ? 1 : 0;
  32848. var lastDownTexture = context.source;
  32849. for (var i = 0; i < iterations; i++) {
  32850. var downIndex = i * 2;
  32851. var upIndex = downIndex + 1;
  32852. var subShader = i == 0 ? BloomEffect.SUBSHADER_PREFILTER13 + qualityOffset : BloomEffect.SUBSHADER_DOWNSAMPLE13 + qualityOffset;
  32853. var mipDownTexture = RenderTexture.createFromPool(tw, th, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE);
  32854. mipDownTexture.filterMode = Laya.FilterMode.Bilinear;
  32855. this._pyramid[downIndex] = mipDownTexture;
  32856. if (i !== iterations - 1) {
  32857. var mipUpTexture = RenderTexture.createFromPool(tw, th, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE);
  32858. mipUpTexture.filterMode = Laya.FilterMode.Bilinear;
  32859. this._pyramid[upIndex] = mipUpTexture;
  32860. }
  32861. cmd.blitScreenTriangle(lastDownTexture, mipDownTexture, null, this._shader, this._shaderData, subShader);
  32862. lastDownTexture = mipDownTexture;
  32863. tw = Math.max(Math.floor(tw / 2), 1);
  32864. th = Math.max(Math.floor(th / 2), 1);
  32865. }
  32866. var lastUpTexture = this._pyramid[(iterations - 1) * 2];
  32867. for (i = iterations - 2; i >= 0; i--) {
  32868. downIndex = i * 2;
  32869. upIndex = downIndex + 1;
  32870. mipDownTexture = this._pyramid[downIndex];
  32871. mipUpTexture = this._pyramid[upIndex];
  32872. cmd.setShaderDataTexture(this._shaderData, BloomEffect.SHADERVALUE_BLOOMTEX, mipDownTexture);
  32873. cmd.blitScreenTriangle(lastUpTexture, mipUpTexture, null, this._shader, this._shaderData, BloomEffect.SUBSHADER_UPSAMPLETENT + qualityOffset);
  32874. lastUpTexture = mipUpTexture;
  32875. }
  32876. var linearColor = this._linearColor;
  32877. this.color.toLinear(linearColor);
  32878. var intensity = Math.pow(2, this._intensity / 10.0) - 1.0;
  32879. var shaderSettings = this._shaderSetting;
  32880. this._shaderSetting.setValue(sampleScale, intensity, this._dirtIntensity, iterations);
  32881. var dirtTexture = this.dirtTexture ? this.dirtTexture : Laya.Texture2D.blackTexture;
  32882. var dirtRatio = dirtTexture.width / dirtTexture.height;
  32883. var screenRatio = viewport.width / viewport.height;
  32884. var dirtTileOffset = this._dirtTileOffset;
  32885. if (dirtRatio > screenRatio)
  32886. dirtTileOffset.setValue(screenRatio / dirtRatio, 1.0, (1.0 - dirtTileOffset.x) * 0.5, 0.0);
  32887. else if (dirtRatio < screenRatio)
  32888. dirtTileOffset.setValue(1.0, dirtRatio / screenRatio, 0.0, (1.0 - dirtTileOffset.y) * 0.5);
  32889. var compositeShaderData = context.compositeShaderData;
  32890. if (this.fastMode)
  32891. compositeShaderData.addDefine(PostProcess.SHADERDEFINE_BLOOM_LOW);
  32892. else
  32893. compositeShaderData.addDefine(PostProcess.SHADERDEFINE_BLOOM);
  32894. this._bloomTextureTexelSize.setValue(1.0 / lastUpTexture.width, 1.0 / lastUpTexture.height, lastUpTexture.width, lastUpTexture.height);
  32895. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_DIRTTILEOFFSET, dirtTileOffset);
  32896. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_SETTINGS, shaderSettings);
  32897. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_COLOR, new Vector4(linearColor.r, linearColor.g, linearColor.b, linearColor.a));
  32898. compositeShaderData.setTexture(PostProcess.SHADERVALUE_BLOOM_DIRTTEX, dirtTexture);
  32899. compositeShaderData.setTexture(PostProcess.SHADERVALUE_BLOOMTEX, lastUpTexture);
  32900. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOMTEX_TEXELSIZE, this._bloomTextureTexelSize);
  32901. for (i = 0; i < iterations; i++) {
  32902. downIndex = i * 2;
  32903. upIndex = downIndex + 1;
  32904. RenderTexture.recoverToPool(this._pyramid[downIndex]);
  32905. (i !== 0 && i !== iterations - 1) && (RenderTexture.recoverToPool(this._pyramid[upIndex]));
  32906. }
  32907. context.deferredReleaseTextures.push(lastUpTexture);
  32908. }
  32909. }
  32910. BloomEffect.SHADERVALUE_MAINTEX = Shader3D.propertyNameToID("u_MainTex");
  32911. BloomEffect.SHADERVALUE_AUTOEXPOSURETEX = Shader3D.propertyNameToID("u_AutoExposureTex");
  32912. BloomEffect.SHADERVALUE_SAMPLESCALE = Shader3D.propertyNameToID("u_SampleScale");
  32913. BloomEffect.SHADERVALUE_THRESHOLD = Shader3D.propertyNameToID("u_Threshold");
  32914. BloomEffect.SHADERVALUE_PARAMS = Shader3D.propertyNameToID("u_Params");
  32915. BloomEffect.SHADERVALUE_BLOOMTEX = Shader3D.propertyNameToID("u_BloomTex");
  32916. BloomEffect.SUBSHADER_PREFILTER13 = 0;
  32917. BloomEffect.SUBSHADER_PREFILTER4 = 1;
  32918. BloomEffect.SUBSHADER_DOWNSAMPLE13 = 2;
  32919. BloomEffect.SUBSHADER_DOWNSAMPLE4 = 3;
  32920. BloomEffect.SUBSHADER_UPSAMPLETENT = 4;
  32921. BloomEffect.SUBSHADER_UPSAMPLEBOX = 5;
  32922. BloomEffect.MAXPYRAMIDSIZE = 16;
  32923. class SceneManager {
  32924. constructor() {
  32925. }
  32926. }
  32927. class RandX {
  32928. constructor(seed) {
  32929. if (!(seed instanceof Array) || seed.length !== 4)
  32930. throw new Error('Rand:Seed must be an array with 4 numbers');
  32931. this._state0U = seed[0] | 0;
  32932. this._state0L = seed[1] | 0;
  32933. this._state1U = seed[2] | 0;
  32934. this._state1L = seed[3] | 0;
  32935. }
  32936. randomint() {
  32937. var s1U = this._state0U, s1L = this._state0L;
  32938. var s0U = this._state1U, s0L = this._state1L;
  32939. var sumL = (s0L >>> 0) + (s1L >>> 0);
  32940. var resU = (s0U + s1U + (sumL / 2 >>> 31)) >>> 0;
  32941. var resL = sumL >>> 0;
  32942. this._state0U = s0U;
  32943. this._state0L = s0L;
  32944. var t1U = 0, t1L = 0;
  32945. var t2U = 0, t2L = 0;
  32946. var a1 = 23;
  32947. var m1 = 0xFFFFFFFF << (32 - a1);
  32948. t1U = (s1U << a1) | ((s1L & m1) >>> (32 - a1));
  32949. t1L = s1L << a1;
  32950. s1U = s1U ^ t1U;
  32951. s1L = s1L ^ t1L;
  32952. t1U = s1U ^ s0U;
  32953. t1L = s1L ^ s0L;
  32954. var a2 = 18;
  32955. var m2 = 0xFFFFFFFF >>> (32 - a2);
  32956. t2U = s1U >>> a2;
  32957. t2L = (s1L >>> a2) | ((s1U & m2) << (32 - a2));
  32958. t1U = t1U ^ t2U;
  32959. t1L = t1L ^ t2L;
  32960. var a3 = 5;
  32961. var m3 = 0xFFFFFFFF >>> (32 - a3);
  32962. t2U = s0U >>> a3;
  32963. t2L = (s0L >>> a3) | ((s0U & m3) << (32 - a3));
  32964. t1U = t1U ^ t2U;
  32965. t1L = t1L ^ t2L;
  32966. this._state1U = t1U;
  32967. this._state1L = t1L;
  32968. return [resU, resL];
  32969. }
  32970. random() {
  32971. var t2 = this.randomint();
  32972. var t2U = t2[0];
  32973. var t2L = t2[1];
  32974. var eU = 0x3FF << (52 - 32);
  32975. var eL = 0;
  32976. var a1 = 12;
  32977. var m1 = 0xFFFFFFFF >>> (32 - a1);
  32978. var sU = t2U >>> a1;
  32979. var sL = (t2L >>> a1) | ((t2U & m1) << (32 - a1));
  32980. var xU = eU | sU;
  32981. var xL = eL | sL;
  32982. RandX._CONVERTION_BUFFER.setUint32(0, xU, false);
  32983. RandX._CONVERTION_BUFFER.setUint32(4, xL, false);
  32984. var d = RandX._CONVERTION_BUFFER.getFloat64(0, false);
  32985. return d - 1;
  32986. }
  32987. }
  32988. RandX._CONVERTION_BUFFER = new DataView(new ArrayBuffer(8));
  32989. RandX.defaultRand = new RandX([0, Date.now() / 65536, 0, Date.now() % 65536]);
  32990. class Constraint3D {
  32991. constructor() {
  32992. }
  32993. }
  32994. class Point2PointConstraint {
  32995. constructor() {
  32996. this._pivotInA = new Vector3();
  32997. this._pivotInB = new Vector3();
  32998. }
  32999. get pivotInA() {
  33000. return this._pivotInA;
  33001. }
  33002. set pivotInA(value) {
  33003. this._pivotInA = value;
  33004. }
  33005. get pivotInB() {
  33006. return this._pivotInB;
  33007. }
  33008. set pivotInB(value) {
  33009. this._pivotInB = value;
  33010. }
  33011. get damping() {
  33012. return this._damping;
  33013. }
  33014. set damping(value) {
  33015. this._damping = value;
  33016. }
  33017. get impulseClamp() {
  33018. return this._impulseClamp;
  33019. }
  33020. set impulseClamp(value) {
  33021. this._impulseClamp = value;
  33022. }
  33023. get tau() {
  33024. return this._tau;
  33025. }
  33026. set tau(value) {
  33027. this._tau = value;
  33028. }
  33029. }
  33030. class HeightfieldColliderShape {
  33031. constructor() {
  33032. }
  33033. }
  33034. class TextMesh {
  33035. constructor() {
  33036. }
  33037. get text() {
  33038. return this._text;
  33039. }
  33040. set text(value) {
  33041. this._text = value;
  33042. }
  33043. get fontSize() {
  33044. return this._fontSize;
  33045. }
  33046. set fontSize(value) {
  33047. this._fontSize = value;
  33048. }
  33049. get color() {
  33050. return this._color;
  33051. }
  33052. set color(value) {
  33053. this._color = value;
  33054. }
  33055. _createVertexBuffer(charCount) {
  33056. }
  33057. _resizeVertexBuffer(charCount) {
  33058. }
  33059. _addChar() {
  33060. }
  33061. }
  33062. class Size {
  33063. constructor(width, height) {
  33064. this._width = 0;
  33065. this._height = 0;
  33066. this._width = width;
  33067. this._height = height;
  33068. }
  33069. static get fullScreen() {
  33070. return new Size(-1, -1);
  33071. }
  33072. get width() {
  33073. if (this._width === -1)
  33074. return RenderContext3D.clientWidth;
  33075. return this._width;
  33076. }
  33077. get height() {
  33078. if (this._height === -1)
  33079. return RenderContext3D.clientHeight;
  33080. return this._height;
  33081. }
  33082. }
  33083. exports.AlternateLightQueue = AlternateLightQueue;
  33084. exports.AnimationClip = AnimationClip;
  33085. exports.AnimationClipParser03 = AnimationClipParser03;
  33086. exports.AnimationClipParser04 = AnimationClipParser04;
  33087. exports.AnimationEvent = AnimationEvent;
  33088. exports.AnimationNode = AnimationNode;
  33089. exports.AnimationTransform3D = AnimationTransform3D;
  33090. exports.Animator = Animator;
  33091. exports.AnimatorControllerLayer = AnimatorControllerLayer;
  33092. exports.AnimatorPlayState = AnimatorPlayState;
  33093. exports.AnimatorState = AnimatorState;
  33094. exports.AnimatorStateScript = AnimatorStateScript;
  33095. exports.Avatar = Avatar;
  33096. exports.BaseCamera = BaseCamera;
  33097. exports.BaseMaterial = BaseMaterial;
  33098. exports.BaseRender = BaseRender;
  33099. exports.BaseShape = BaseShape;
  33100. exports.BatchMark = BatchMark;
  33101. exports.BlinnPhongMaterial = BlinnPhongMaterial;
  33102. exports.BlitScreenQuadCMD = BlitScreenQuadCMD;
  33103. exports.BloomEffect = BloomEffect;
  33104. exports.BoundBox = BoundBox;
  33105. exports.BoundFrustum = BoundFrustum;
  33106. exports.BoundSphere = BoundSphere;
  33107. exports.Bounds = Bounds;
  33108. exports.BoundsOctree = BoundsOctree;
  33109. exports.BoundsOctreeNode = BoundsOctreeNode;
  33110. exports.BoxColliderShape = BoxColliderShape;
  33111. exports.BoxShape = BoxShape;
  33112. exports.BufferState = BufferState;
  33113. exports.BulletInteractive = BulletInteractive;
  33114. exports.Burst = Burst;
  33115. exports.Camera = Camera;
  33116. exports.CameraCullInfo = CameraCullInfo;
  33117. exports.CapsuleColliderShape = CapsuleColliderShape;
  33118. exports.CastShadowList = CastShadowList;
  33119. exports.CharacterController = CharacterController;
  33120. exports.CircleShape = CircleShape;
  33121. exports.Cluster = Cluster;
  33122. exports.ColliderShape = ColliderShape;
  33123. exports.Collision = Collision;
  33124. exports.CollisionTool = CollisionTool;
  33125. exports.CollisionUtils = CollisionUtils;
  33126. exports.Color = Color;
  33127. exports.ColorOverLifetime = ColorOverLifetime;
  33128. exports.Command = Command;
  33129. exports.CommandBuffer = CommandBuffer;
  33130. exports.CompoundColliderShape = CompoundColliderShape;
  33131. exports.ConchQuaternion = ConchQuaternion;
  33132. exports.ConchVector3 = ConchVector3;
  33133. exports.ConchVector4 = ConchVector4;
  33134. exports.ConeColliderShape = ConeColliderShape;
  33135. exports.ConeShape = ConeShape;
  33136. exports.Config3D = Config3D;
  33137. exports.ConfigurableConstraint = ConfigurableConstraint;
  33138. exports.Constraint3D = Constraint3D;
  33139. exports.ConstraintComponent = ConstraintComponent;
  33140. exports.ContactPoint = ContactPoint;
  33141. exports.ContainmentType = ContainmentType;
  33142. exports.CylinderColliderShape = CylinderColliderShape;
  33143. exports.DefineDatas = DefineDatas;
  33144. exports.DirectionLight = DirectionLight;
  33145. exports.DynamicBatchManager = DynamicBatchManager;
  33146. exports.EffectMaterial = EffectMaterial;
  33147. exports.Emission = Emission;
  33148. exports.ExtendTerrainMaterial = ExtendTerrainMaterial;
  33149. exports.FixedConstraint = FixedConstraint;
  33150. exports.FloatKeyframe = FloatKeyframe;
  33151. exports.FrameOverTime = FrameOverTime;
  33152. exports.FrustumCulling = FrustumCulling;
  33153. exports.GeometryElement = GeometryElement;
  33154. exports.Gradient = Gradient;
  33155. exports.GradientAngularVelocity = GradientAngularVelocity;
  33156. exports.GradientColor = GradientColor;
  33157. exports.GradientDataInt = GradientDataInt;
  33158. exports.GradientDataNumber = GradientDataNumber;
  33159. exports.GradientDataVector2 = GradientDataVector2;
  33160. exports.GradientMode = GradientMode;
  33161. exports.GradientSize = GradientSize;
  33162. exports.GradientVelocity = GradientVelocity;
  33163. exports.HalfFloatUtils = HalfFloatUtils;
  33164. exports.HeightMap = HeightMap;
  33165. exports.HeightfieldColliderShape = HeightfieldColliderShape;
  33166. exports.HemisphereShape = HemisphereShape;
  33167. exports.HitResult = HitResult;
  33168. exports.ILaya3D = ILaya3D;
  33169. exports.IndexBuffer3D = IndexBuffer3D;
  33170. exports.Input3D = Input3D;
  33171. exports.Keyframe = Keyframe;
  33172. exports.KeyframeNode = KeyframeNode;
  33173. exports.KeyframeNodeList = KeyframeNodeList;
  33174. exports.KeyframeNodeOwner = KeyframeNodeOwner;
  33175. exports.Laya3D = Laya3D;
  33176. exports.LightQueue = LightQueue;
  33177. exports.LightSprite = LightSprite;
  33178. exports.Lightmap = Lightmap;
  33179. exports.LoadModelV04 = LoadModelV04;
  33180. exports.LoadModelV05 = LoadModelV05;
  33181. exports.Material = Material;
  33182. exports.MathUtils3D = MathUtils3D;
  33183. exports.Matrix3x3 = Matrix3x3;
  33184. exports.Matrix4x4 = Matrix4x4;
  33185. exports.Mesh = Mesh;
  33186. exports.MeshColliderShape = MeshColliderShape;
  33187. exports.MeshFilter = MeshFilter;
  33188. exports.MeshReader = MeshReader;
  33189. exports.MeshRenderDynamicBatchManager = MeshRenderDynamicBatchManager;
  33190. exports.MeshRenderStaticBatchManager = MeshRenderStaticBatchManager;
  33191. exports.MeshRenderer = MeshRenderer;
  33192. exports.MeshSprite3D = MeshSprite3D;
  33193. exports.MeshSprite3DShaderDeclaration = MeshSprite3DShaderDeclaration;
  33194. exports.MeshTerrainSprite3D = MeshTerrainSprite3D;
  33195. exports.MouseTouch = MouseTouch;
  33196. exports.OctreeMotionList = OctreeMotionList;
  33197. exports.PBRMaterial = PBRMaterial;
  33198. exports.PBRSpecularMaterial = PBRSpecularMaterial;
  33199. exports.PBRStandardMaterial = PBRStandardMaterial;
  33200. exports.Physics3D = Physics3D;
  33201. exports.Physics3DUtils = Physics3DUtils;
  33202. exports.PhysicsCollider = PhysicsCollider;
  33203. exports.PhysicsComponent = PhysicsComponent;
  33204. exports.PhysicsSettings = PhysicsSettings;
  33205. exports.PhysicsSimulation = PhysicsSimulation;
  33206. exports.PhysicsTriggerComponent = PhysicsTriggerComponent;
  33207. exports.PhysicsUpdateList = PhysicsUpdateList;
  33208. exports.Picker = Picker;
  33209. exports.PixelLineData = PixelLineData;
  33210. exports.PixelLineFilter = PixelLineFilter;
  33211. exports.PixelLineMaterial = PixelLineMaterial;
  33212. exports.PixelLineRenderer = PixelLineRenderer;
  33213. exports.PixelLineSprite3D = PixelLineSprite3D;
  33214. exports.PixelLineVertex = PixelLineVertex;
  33215. exports.Plane = Plane;
  33216. exports.Point2PointConstraint = Point2PointConstraint;
  33217. exports.PointLight = PointLight;
  33218. exports.PostProcess = PostProcess;
  33219. exports.PostProcessEffect = PostProcessEffect;
  33220. exports.PostProcessRenderContext = PostProcessRenderContext;
  33221. exports.PrimitiveMesh = PrimitiveMesh;
  33222. exports.Quaternion = Quaternion;
  33223. exports.QuaternionKeyframe = QuaternionKeyframe;
  33224. exports.Rand = Rand;
  33225. exports.RandX = RandX;
  33226. exports.Ray = Ray;
  33227. exports.RenderContext3D = RenderContext3D;
  33228. exports.RenderElement = RenderElement;
  33229. exports.RenderQueue = RenderQueue;
  33230. exports.RenderState = RenderState;
  33231. exports.RenderTexture = RenderTexture;
  33232. exports.RenderableSprite3D = RenderableSprite3D;
  33233. exports.Rigidbody3D = Rigidbody3D;
  33234. exports.RotationOverLifetime = RotationOverLifetime;
  33235. exports.Scene3D = Scene3D;
  33236. exports.Scene3DShaderDeclaration = Scene3DShaderDeclaration;
  33237. exports.Scene3DUtils = Scene3DUtils;
  33238. exports.SceneManager = SceneManager;
  33239. exports.ScreenQuad = ScreenQuad;
  33240. exports.ScreenTriangle = ScreenTriangle;
  33241. exports.Script3D = Script3D;
  33242. exports.SetRenderTargetCMD = SetRenderTargetCMD;
  33243. exports.SetShaderDataTextureCMD = SetShaderDataTextureCMD;
  33244. exports.Shader3D = Shader3D;
  33245. exports.ShaderData = ShaderData;
  33246. exports.ShaderDefine = ShaderDefine;
  33247. exports.ShaderInit3D = ShaderInit3D;
  33248. exports.ShaderInstance = ShaderInstance;
  33249. exports.ShaderPass = ShaderPass;
  33250. exports.ShaderVariable = ShaderVariable;
  33251. exports.ShaderVariant = ShaderVariant;
  33252. exports.ShaderVariantCollection = ShaderVariantCollection;
  33253. exports.ShadowCasterPass = ShadowCasterPass;
  33254. exports.ShadowCullInfo = ShadowCullInfo;
  33255. exports.ShadowSliceData = ShadowSliceData;
  33256. exports.ShadowSpotData = ShadowSpotData;
  33257. exports.ShadowUtils = ShadowUtils;
  33258. exports.ShapeUtils = ShapeUtils;
  33259. exports.ShuriKenParticle3D = ShuriKenParticle3D;
  33260. exports.ShuriKenParticle3DShaderDeclaration = ShuriKenParticle3DShaderDeclaration;
  33261. exports.ShurikenParticleData = ShurikenParticleData;
  33262. exports.ShurikenParticleMaterial = ShurikenParticleMaterial;
  33263. exports.ShurikenParticleRenderer = ShurikenParticleRenderer;
  33264. exports.ShurikenParticleSystem = ShurikenParticleSystem;
  33265. exports.SimpleSingletonList = SimpleSingletonList;
  33266. exports.SingletonList = SingletonList;
  33267. exports.Size = Size;
  33268. exports.SizeOverLifetime = SizeOverLifetime;
  33269. exports.SkinnedMeshRenderer = SkinnedMeshRenderer;
  33270. exports.SkinnedMeshSprite3D = SkinnedMeshSprite3D;
  33271. exports.SkinnedMeshSprite3DShaderDeclaration = SkinnedMeshSprite3DShaderDeclaration;
  33272. exports.SkyBox = SkyBox;
  33273. exports.SkyBoxMaterial = SkyBoxMaterial;
  33274. exports.SkyDome = SkyDome;
  33275. exports.SkyMesh = SkyMesh;
  33276. exports.SkyPanoramicMaterial = SkyPanoramicMaterial;
  33277. exports.SkyProceduralMaterial = SkyProceduralMaterial;
  33278. exports.SkyRenderer = SkyRenderer;
  33279. exports.SphereColliderShape = SphereColliderShape;
  33280. exports.SphereShape = SphereShape;
  33281. exports.SphericalHarmonicsL2 = SphericalHarmonicsL2;
  33282. exports.SpotLight = SpotLight;
  33283. exports.Sprite3D = Sprite3D;
  33284. exports.StartFrame = StartFrame;
  33285. exports.StaticBatchManager = StaticBatchManager;
  33286. exports.StaticPlaneColliderShape = StaticPlaneColliderShape;
  33287. exports.SubMesh = SubMesh;
  33288. exports.SubMeshDynamicBatch = SubMeshDynamicBatch;
  33289. exports.SubMeshInstanceBatch = SubMeshInstanceBatch;
  33290. exports.SubMeshRenderElement = SubMeshRenderElement;
  33291. exports.SubMeshStaticBatch = SubMeshStaticBatch;
  33292. exports.SubShader = SubShader;
  33293. exports.TextMesh = TextMesh;
  33294. exports.TextureCube = TextureCube;
  33295. exports.TextureGenerator = TextureGenerator;
  33296. exports.TextureMode = TextureMode;
  33297. exports.TextureSheetAnimation = TextureSheetAnimation;
  33298. exports.Touch = Touch;
  33299. exports.TrailFilter = TrailFilter;
  33300. exports.TrailGeometry = TrailGeometry;
  33301. exports.TrailMaterial = TrailMaterial;
  33302. exports.TrailRenderer = TrailRenderer;
  33303. exports.TrailSprite3D = TrailSprite3D;
  33304. exports.Transform3D = Transform3D;
  33305. exports.UnlitMaterial = UnlitMaterial;
  33306. exports.Utils3D = Utils3D;
  33307. exports.Vector2 = Vector2;
  33308. exports.Vector3 = Vector3;
  33309. exports.Vector3Keyframe = Vector3Keyframe;
  33310. exports.Vector4 = Vector4;
  33311. exports.VelocityOverLifetime = VelocityOverLifetime;
  33312. exports.VertexBuffer3D = VertexBuffer3D;
  33313. exports.VertexDeclaration = VertexDeclaration;
  33314. exports.VertexElement = VertexElement;
  33315. exports.VertexElementFormat = VertexElementFormat;
  33316. exports.VertexMesh = VertexMesh;
  33317. exports.VertexPositionTerrain = VertexPositionTerrain;
  33318. exports.VertexPositionTexture0 = VertexPositionTexture0;
  33319. exports.VertexShuriKenParticle = VertexShuriKenParticle;
  33320. exports.VertexShurikenParticleBillboard = VertexShurikenParticleBillboard;
  33321. exports.VertexShurikenParticleMesh = VertexShurikenParticleMesh;
  33322. exports.VertexTrail = VertexTrail;
  33323. exports.Viewport = Viewport;
  33324. exports.WaterPrimaryMaterial = WaterPrimaryMaterial;
  33325. exports.skinnedMatrixCache = skinnedMatrixCache;
  33326. }(window.Laya = window.Laya || {}, Laya));