three.webgpu.nodes.js 1012 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, WebGLCoordinateSystem, BackSide, CubeReflectionMapping, CubeRefractionMapping, WebGPUCoordinateSystem, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Matrix2, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. class NodeMaterialObserver {
  61. constructor( builder ) {
  62. this.renderObjects = new WeakMap();
  63. this.hasNode = this.containsNode( builder );
  64. this.hasAnimation = builder.object.isSkinnedMesh === true;
  65. this.refreshUniforms = refreshUniforms;
  66. this.renderId = 0;
  67. }
  68. firstInitialization( renderObject ) {
  69. const hasInitialized = this.renderObjects.has( renderObject );
  70. if ( hasInitialized === false ) {
  71. this.getRenderObjectData( renderObject );
  72. return true;
  73. }
  74. return false;
  75. }
  76. getRenderObjectData( renderObject ) {
  77. let data = this.renderObjects.get( renderObject );
  78. if ( data === undefined ) {
  79. const { geometry, material, object } = renderObject;
  80. data = {
  81. material: this.getMaterialData( material ),
  82. geometry: {
  83. attributes: this.getAttributesData( geometry.attributes ),
  84. indexVersion: geometry.index ? geometry.index.version : null,
  85. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  86. },
  87. worldMatrix: object.matrixWorld.clone()
  88. };
  89. if ( object.center ) {
  90. data.center = object.center.clone();
  91. }
  92. if ( object.morphTargetInfluences ) {
  93. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  94. }
  95. if ( renderObject.bundle !== null ) {
  96. data.version = renderObject.bundle.version;
  97. }
  98. if ( data.material.transmission > 0 ) {
  99. const { width, height } = renderObject.context;
  100. data.bufferWidth = width;
  101. data.bufferHeight = height;
  102. }
  103. this.renderObjects.set( renderObject, data );
  104. }
  105. return data;
  106. }
  107. getAttributesData( attributes ) {
  108. const attributesData = {};
  109. for ( const name in attributes ) {
  110. const attribute = attributes[ name ];
  111. attributesData[ name ] = {
  112. version: attribute.version
  113. };
  114. }
  115. return attributesData;
  116. }
  117. containsNode( builder ) {
  118. const material = builder.material;
  119. for ( const property in material ) {
  120. if ( material[ property ] && material[ property ].isNode )
  121. return true;
  122. }
  123. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  124. return true;
  125. return false;
  126. }
  127. getMaterialData( material ) {
  128. const data = {};
  129. for ( const property of this.refreshUniforms ) {
  130. const value = material[ property ];
  131. if ( value === null || value === undefined ) continue;
  132. if ( typeof value === 'object' && value.clone !== undefined ) {
  133. if ( value.isTexture === true ) {
  134. data[ property ] = { id: value.id, version: value.version };
  135. } else {
  136. data[ property ] = value.clone();
  137. }
  138. } else {
  139. data[ property ] = value;
  140. }
  141. }
  142. return data;
  143. }
  144. equals( renderObject ) {
  145. const { object, material, geometry } = renderObject;
  146. const renderObjectData = this.getRenderObjectData( renderObject );
  147. // world matrix
  148. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  149. renderObjectData.worldMatrix.copy( object.matrixWorld );
  150. return false;
  151. }
  152. // material
  153. const materialData = renderObjectData.material;
  154. for ( const property in materialData ) {
  155. const value = materialData[ property ];
  156. const mtlValue = material[ property ];
  157. if ( value.equals !== undefined ) {
  158. if ( value.equals( mtlValue ) === false ) {
  159. value.copy( mtlValue );
  160. return false;
  161. }
  162. } else if ( mtlValue.isTexture === true ) {
  163. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  164. value.id = mtlValue.id;
  165. value.version = mtlValue.version;
  166. return false;
  167. }
  168. } else if ( value !== mtlValue ) {
  169. materialData[ property ] = mtlValue;
  170. return false;
  171. }
  172. }
  173. if ( materialData.transmission > 0 ) {
  174. const { width, height } = renderObject.context;
  175. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  176. renderObjectData.bufferWidth = width;
  177. renderObjectData.bufferHeight = height;
  178. return false;
  179. }
  180. }
  181. // geometry
  182. const storedGeometryData = renderObjectData.geometry;
  183. const attributes = geometry.attributes;
  184. const storedAttributes = storedGeometryData.attributes;
  185. const storedAttributeNames = Object.keys( storedAttributes );
  186. const currentAttributeNames = Object.keys( attributes );
  187. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  188. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  189. return false;
  190. }
  191. // compare each attribute
  192. for ( const name of storedAttributeNames ) {
  193. const storedAttributeData = storedAttributes[ name ];
  194. const attribute = attributes[ name ];
  195. if ( attribute === undefined ) {
  196. // attribute was removed
  197. delete storedAttributes[ name ];
  198. return false;
  199. }
  200. if ( storedAttributeData.version !== attribute.version ) {
  201. storedAttributeData.version = attribute.version;
  202. return false;
  203. }
  204. }
  205. // check index
  206. const index = geometry.index;
  207. const storedIndexVersion = storedGeometryData.indexVersion;
  208. const currentIndexVersion = index ? index.version : null;
  209. if ( storedIndexVersion !== currentIndexVersion ) {
  210. storedGeometryData.indexVersion = currentIndexVersion;
  211. return false;
  212. }
  213. // check drawRange
  214. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  215. storedGeometryData.drawRange.start = geometry.drawRange.start;
  216. storedGeometryData.drawRange.count = geometry.drawRange.count;
  217. return false;
  218. }
  219. // morph targets
  220. if ( renderObjectData.morphTargetInfluences ) {
  221. let morphChanged = false;
  222. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  223. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  224. morphChanged = true;
  225. }
  226. }
  227. if ( morphChanged ) return true;
  228. }
  229. // center
  230. if ( renderObjectData.center ) {
  231. if ( renderObjectData.center.equals( object.center ) === false ) {
  232. renderObjectData.center.copy( object.center );
  233. return true;
  234. }
  235. }
  236. // bundle
  237. if ( renderObject.bundle !== null ) {
  238. renderObjectData.version = renderObject.bundle.version;
  239. }
  240. return true;
  241. }
  242. needsRefresh( renderObject, nodeFrame ) {
  243. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  244. return true;
  245. const { renderId } = nodeFrame;
  246. if ( this.renderId !== renderId ) {
  247. this.renderId = renderId;
  248. return true;
  249. }
  250. const isStatic = renderObject.object.static === true;
  251. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  252. if ( isStatic || isBundle )
  253. return false;
  254. const notEqual = this.equals( renderObject ) !== true;
  255. return notEqual;
  256. }
  257. }
  258. /** @module NodeUtils **/
  259. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  260. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  261. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  262. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  263. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  264. function cyrb53( value, seed = 0 ) {
  265. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  266. if ( value instanceof Array ) {
  267. for ( let i = 0, val; i < value.length; i ++ ) {
  268. val = value[ i ];
  269. h1 = Math.imul( h1 ^ val, 2654435761 );
  270. h2 = Math.imul( h2 ^ val, 1597334677 );
  271. }
  272. } else {
  273. for ( let i = 0, ch; i < value.length; i ++ ) {
  274. ch = value.charCodeAt( i );
  275. h1 = Math.imul( h1 ^ ch, 2654435761 );
  276. h2 = Math.imul( h2 ^ ch, 1597334677 );
  277. }
  278. }
  279. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  280. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  281. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  282. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  283. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  284. }
  285. /**
  286. * Computes a hash for the given string.
  287. *
  288. * @method
  289. * @param {String} str - The string to be hashed.
  290. * @return {Number} The hash.
  291. */
  292. const hashString = ( str ) => cyrb53( str );
  293. /**
  294. * Computes a hash for the given array.
  295. *
  296. * @method
  297. * @param {Array<Number>} array - The array to be hashed.
  298. * @return {Number} The hash.
  299. */
  300. const hashArray = ( array ) => cyrb53( array );
  301. /**
  302. * Computes a hash for the given list of parameters.
  303. *
  304. * @method
  305. * @param {...Number} params - A list of parameters.
  306. * @return {Number} The hash.
  307. */
  308. const hash$1 = ( ...params ) => cyrb53( params );
  309. /**
  310. * Computes a cache key for the given node.
  311. *
  312. * @method
  313. * @param {Object} object - The object to be hashed.
  314. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  315. * @return {Number} The hash.
  316. */
  317. function getCacheKey$1( object, force = false ) {
  318. const values = [];
  319. if ( object.isNode === true ) {
  320. values.push( object.id );
  321. object = object.getSelf();
  322. }
  323. for ( const { property, childNode } of getNodeChildren( object ) ) {
  324. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  325. }
  326. return cyrb53( values );
  327. }
  328. /**
  329. * This generator function can be used to iterate over the node children
  330. * of the given object.
  331. *
  332. * @generator
  333. * @param {Object} node - The object to be hashed.
  334. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  335. * @yields {Object} A result node holding the property, index (if available) and the child node.
  336. */
  337. function* getNodeChildren( node, toJSON = false ) {
  338. for ( const property in node ) {
  339. // Ignore private properties.
  340. if ( property.startsWith( '_' ) === true ) continue;
  341. const object = node[ property ];
  342. if ( Array.isArray( object ) === true ) {
  343. for ( let i = 0; i < object.length; i ++ ) {
  344. const child = object[ i ];
  345. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  346. yield { property, index: i, childNode: child };
  347. }
  348. }
  349. } else if ( object && object.isNode === true ) {
  350. yield { property, childNode: object };
  351. } else if ( typeof object === 'object' ) {
  352. for ( const subProperty in object ) {
  353. const child = object[ subProperty ];
  354. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  355. yield { property, index: subProperty, childNode: child };
  356. }
  357. }
  358. }
  359. }
  360. }
  361. const typeFromLength = /*@__PURE__*/ new Map( [
  362. [ 1, 'float' ],
  363. [ 2, 'vec2' ],
  364. [ 3, 'vec3' ],
  365. [ 4, 'vec4' ],
  366. [ 9, 'mat3' ],
  367. [ 16, 'mat4' ]
  368. ] );
  369. /**
  370. * Returns the data type for the given the length.
  371. *
  372. * @method
  373. * @param {Number} length - The length.
  374. * @return {String} The data type.
  375. */
  376. function getTypeFromLength( length ) {
  377. return typeFromLength.get( length );
  378. }
  379. /**
  380. * Returns the length for the given data type.
  381. *
  382. * @method
  383. * @param {String} type - The data type.
  384. * @return {Number} The length.
  385. */
  386. function getLengthFromType( type ) {
  387. if ( /float|int|uint/.test( type ) ) return 1;
  388. if ( /vec2/.test( type ) ) return 2;
  389. if ( /vec3/.test( type ) ) return 3;
  390. if ( /vec4/.test( type ) ) return 4;
  391. if ( /mat3/.test( type ) ) return 9;
  392. if ( /mat4/.test( type ) ) return 16;
  393. console.error( 'THREE.TSL: Unsupported type:', type );
  394. }
  395. /**
  396. * Returns the data type for the given value.
  397. *
  398. * @method
  399. * @param {Any} value - The value.
  400. * @return {String?} The data type.
  401. */
  402. function getValueType( value ) {
  403. if ( value === undefined || value === null ) return null;
  404. const typeOf = typeof value;
  405. if ( value.isNode === true ) {
  406. return 'node';
  407. } else if ( typeOf === 'number' ) {
  408. return 'float';
  409. } else if ( typeOf === 'boolean' ) {
  410. return 'bool';
  411. } else if ( typeOf === 'string' ) {
  412. return 'string';
  413. } else if ( typeOf === 'function' ) {
  414. return 'shader';
  415. } else if ( value.isVector2 === true ) {
  416. return 'vec2';
  417. } else if ( value.isVector3 === true ) {
  418. return 'vec3';
  419. } else if ( value.isVector4 === true ) {
  420. return 'vec4';
  421. } else if ( value.isMatrix3 === true ) {
  422. return 'mat3';
  423. } else if ( value.isMatrix4 === true ) {
  424. return 'mat4';
  425. } else if ( value.isColor === true ) {
  426. return 'color';
  427. } else if ( value instanceof ArrayBuffer ) {
  428. return 'ArrayBuffer';
  429. }
  430. return null;
  431. }
  432. /**
  433. * Returns the value/object for the given data type and parameters.
  434. *
  435. * @method
  436. * @param {String} type - The given type.
  437. * @param {...Any} params - A parameter list.
  438. * @return {Any} The value/object.
  439. */
  440. function getValueFromType( type, ...params ) {
  441. const last4 = type ? type.slice( - 4 ) : undefined;
  442. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  443. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  444. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  445. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  446. }
  447. if ( type === 'color' ) {
  448. return new Color( ...params );
  449. } else if ( last4 === 'vec2' ) {
  450. return new Vector2( ...params );
  451. } else if ( last4 === 'vec3' ) {
  452. return new Vector3( ...params );
  453. } else if ( last4 === 'vec4' ) {
  454. return new Vector4( ...params );
  455. } else if ( last4 === 'mat3' ) {
  456. return new Matrix3( ...params );
  457. } else if ( last4 === 'mat4' ) {
  458. return new Matrix4( ...params );
  459. } else if ( type === 'bool' ) {
  460. return params[ 0 ] || false;
  461. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  462. return params[ 0 ] || 0;
  463. } else if ( type === 'string' ) {
  464. return params[ 0 ] || '';
  465. } else if ( type === 'ArrayBuffer' ) {
  466. return base64ToArrayBuffer( params[ 0 ] );
  467. }
  468. return null;
  469. }
  470. /**
  471. * Converts the given array buffer to a Base64 string.
  472. *
  473. * @method
  474. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  475. * @return {String} The Base64 string.
  476. */
  477. function arrayBufferToBase64( arrayBuffer ) {
  478. let chars = '';
  479. const array = new Uint8Array( arrayBuffer );
  480. for ( let i = 0; i < array.length; i ++ ) {
  481. chars += String.fromCharCode( array[ i ] );
  482. }
  483. return btoa( chars );
  484. }
  485. /**
  486. * Converts the given Base64 string to an array buffer.
  487. *
  488. * @method
  489. * @param {String} base64 - The Base64 string.
  490. * @return {ArrayBuffer} The array buffer.
  491. */
  492. function base64ToArrayBuffer( base64 ) {
  493. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  494. }
  495. var NodeUtils = /*#__PURE__*/Object.freeze({
  496. __proto__: null,
  497. arrayBufferToBase64: arrayBufferToBase64,
  498. base64ToArrayBuffer: base64ToArrayBuffer,
  499. getCacheKey: getCacheKey$1,
  500. getLengthFromType: getLengthFromType,
  501. getNodeChildren: getNodeChildren,
  502. getTypeFromLength: getTypeFromLength,
  503. getValueFromType: getValueFromType,
  504. getValueType: getValueType,
  505. hash: hash$1,
  506. hashArray: hashArray,
  507. hashString: hashString
  508. });
  509. /**
  510. * Possible shader stages.
  511. *
  512. * @property {string} VERTEX The vertex shader stage.
  513. * @property {string} FRAGMENT The fragment shader stage.
  514. */
  515. const NodeShaderStage = {
  516. VERTEX: 'vertex',
  517. FRAGMENT: 'fragment'
  518. };
  519. /**
  520. * Update types of a node.
  521. *
  522. * @property {string} NONE The update method is not executed.
  523. * @property {string} FRAME The update method is executed per frame.
  524. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  525. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  526. */
  527. const NodeUpdateType = {
  528. NONE: 'none',
  529. FRAME: 'frame',
  530. RENDER: 'render',
  531. OBJECT: 'object'
  532. };
  533. /**
  534. * Data types of a node.
  535. *
  536. * @property {string} BOOLEAN Boolean type.
  537. * @property {string} INTEGER Integer type.
  538. * @property {string} FLOAT Float type.
  539. * @property {string} VECTOR2 Two-dimensional vector type.
  540. * @property {string} VECTOR3 Three-dimensional vector type.
  541. * @property {string} VECTOR4 Four-dimensional vector type.
  542. * @property {string} MATRIX2 2x2 matrix type.
  543. * @property {string} MATRIX3 3x3 matrix type.
  544. * @property {string} MATRIX4 4x4 matrix type.
  545. */
  546. const NodeType = {
  547. BOOLEAN: 'bool',
  548. INTEGER: 'int',
  549. FLOAT: 'float',
  550. VECTOR2: 'vec2',
  551. VECTOR3: 'vec3',
  552. VECTOR4: 'vec4',
  553. MATRIX2: 'mat2',
  554. MATRIX3: 'mat3',
  555. MATRIX4: 'mat4'
  556. };
  557. /**
  558. * Access types of a node. These are relevant for compute and storage usage.
  559. *
  560. * @property {string} READ_ONLY Read-only access
  561. * @property {string} WRITE_ONLY Write-only access.
  562. * @property {string} READ_WRITE Read and write access.
  563. */
  564. const NodeAccess = {
  565. READ_ONLY: 'readOnly',
  566. WRITE_ONLY: 'writeOnly',
  567. READ_WRITE: 'readWrite',
  568. };
  569. const defaultShaderStages = [ 'fragment', 'vertex' ];
  570. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  571. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  572. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  573. let _nodeId = 0;
  574. /**
  575. * Base class for all nodes.
  576. *
  577. * @augments EventDispatcher
  578. */
  579. class Node extends EventDispatcher {
  580. static get type() {
  581. return 'Node';
  582. }
  583. /**
  584. * Constructs a new node.
  585. *
  586. * @param {String?} nodeType - The node type.
  587. */
  588. constructor( nodeType = null ) {
  589. super();
  590. /**
  591. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  592. *
  593. * @type {String?}
  594. * @default null
  595. */
  596. this.nodeType = nodeType;
  597. /**
  598. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  599. *
  600. * @type {String}
  601. * @default 'none'
  602. */
  603. this.updateType = NodeUpdateType.NONE;
  604. /**
  605. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  606. *
  607. * @type {String}
  608. * @default 'none'
  609. */
  610. this.updateBeforeType = NodeUpdateType.NONE;
  611. /**
  612. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  613. *
  614. * @type {String}
  615. * @default 'none'
  616. */
  617. this.updateAfterType = NodeUpdateType.NONE;
  618. /**
  619. * The UUID of the node.
  620. *
  621. * @type {String}
  622. * @readonly
  623. */
  624. this.uuid = MathUtils.generateUUID();
  625. /**
  626. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  627. *
  628. * @type {Number}
  629. * @readonly
  630. * @default 0
  631. */
  632. this.version = 0;
  633. /**
  634. * Whether this node is global or not. This property is relevant for the internal
  635. * node caching system. All nodes which should be declared just once should
  636. * set this flag to `true` (a typical example is {@link AttributeNode}).
  637. *
  638. * @type {Boolean}
  639. * @default false
  640. */
  641. this.global = false;
  642. /**
  643. * This flag can be used for type testing.
  644. *
  645. * @type {Boolean}
  646. * @readonly
  647. * @default true
  648. */
  649. this.isNode = true;
  650. // private
  651. /**
  652. * The cache key of this node.
  653. *
  654. * @private
  655. * @type {Number?}
  656. * @default null
  657. */
  658. this._cacheKey = null;
  659. /**
  660. * The cache key 's version.
  661. *
  662. * @private
  663. * @type {Number}
  664. * @default 0
  665. */
  666. this._cacheKeyVersion = 0;
  667. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  668. }
  669. /**
  670. * Set this property to `true` when the node should be regenerated.
  671. *
  672. * @type {Boolean}
  673. * @default false
  674. */
  675. set needsUpdate( value ) {
  676. if ( value === true ) {
  677. this.version ++;
  678. }
  679. }
  680. /**
  681. * The type of the class. The value is usually the constructor name.
  682. *
  683. * @type {String}
  684. * @readonly
  685. */
  686. get type() {
  687. return this.constructor.type;
  688. }
  689. /**
  690. * Convenient method for defining {@link Node#update}.
  691. *
  692. * @param {Function} callback - The update method.
  693. * @param {String} updateType - The update type.
  694. * @return {Node} A reference to this node.
  695. */
  696. onUpdate( callback, updateType ) {
  697. this.updateType = updateType;
  698. this.update = callback.bind( this.getSelf() );
  699. return this;
  700. }
  701. /**
  702. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  703. * this method automatically sets the update type to `FRAME`.
  704. *
  705. * @param {Function} callback - The update method.
  706. * @return {Node} A reference to this node.
  707. */
  708. onFrameUpdate( callback ) {
  709. return this.onUpdate( callback, NodeUpdateType.FRAME );
  710. }
  711. /**
  712. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  713. * this method automatically sets the update type to `RENDER`.
  714. *
  715. * @param {Function} callback - The update method.
  716. * @return {Node} A reference to this node.
  717. */
  718. onRenderUpdate( callback ) {
  719. return this.onUpdate( callback, NodeUpdateType.RENDER );
  720. }
  721. /**
  722. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  723. * this method automatically sets the update type to `OBJECT`.
  724. *
  725. * @param {Function} callback - The update method.
  726. * @return {Node} A reference to this node.
  727. */
  728. onObjectUpdate( callback ) {
  729. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  730. }
  731. /**
  732. * Convenient method for defining {@link Node#updateReference}.
  733. *
  734. * @param {Function} callback - The update method.
  735. * @return {Node} A reference to this node.
  736. */
  737. onReference( callback ) {
  738. this.updateReference = callback.bind( this.getSelf() );
  739. return this;
  740. }
  741. /**
  742. * The `this` reference might point to a Proxy so this method can be used
  743. * to get the reference to the actual node instance.
  744. *
  745. * @return {Node} A reference to the node.
  746. */
  747. getSelf() {
  748. // Returns non-node object.
  749. return this.self || this;
  750. }
  751. /**
  752. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  753. * to such objects based on a given state (e.g. the current node frame or builder).
  754. *
  755. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  756. * @return {Any} The updated reference.
  757. */
  758. updateReference( /*state*/ ) {
  759. return this;
  760. }
  761. /**
  762. * By default this method returns the value of the {@link Node#global} flag. This method
  763. * can be overwritten in derived classes if an analytical way is required to determine the
  764. * global status.
  765. *
  766. * @param {NodeBuilder} builder - The current node builder.
  767. * @return {Boolean} Whether this node is global or not.
  768. */
  769. isGlobal( /*builder*/ ) {
  770. return this.global;
  771. }
  772. /**
  773. * Generator function that can be used to iterate over the child nodes.
  774. *
  775. * @generator
  776. * @yields {Node} A child node.
  777. */
  778. * getChildren() {
  779. for ( const { childNode } of getNodeChildren( this ) ) {
  780. yield childNode;
  781. }
  782. }
  783. /**
  784. * Calling this method dispatches the `dispose` event. This event can be used
  785. * to register event listeners for clean up tasks.
  786. */
  787. dispose() {
  788. this.dispatchEvent( { type: 'dispose' } );
  789. }
  790. /**
  791. * Callback for {@link Node#traverse}.
  792. *
  793. * @callback traverseCallback
  794. * @param {Node} node - The current node.
  795. */
  796. /**
  797. * Can be used to traverse through the node's hierarchy.
  798. *
  799. * @param {traverseCallback} callback - A callback that is executed per node.
  800. */
  801. traverse( callback ) {
  802. callback( this );
  803. for ( const childNode of this.getChildren() ) {
  804. childNode.traverse( callback );
  805. }
  806. }
  807. /**
  808. * Returns the cache key for this node.
  809. *
  810. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  811. * @return {Number} The cache key of the node.
  812. */
  813. getCacheKey( force = false ) {
  814. force = force || this.version !== this._cacheKeyVersion;
  815. if ( force === true || this._cacheKey === null ) {
  816. this._cacheKey = getCacheKey$1( this, force );
  817. this._cacheKeyVersion = this.version;
  818. }
  819. return this._cacheKey;
  820. }
  821. /**
  822. * Returns the references to this node which is by default `this`.
  823. *
  824. * @return {Node} A reference to this node.
  825. */
  826. getScope() {
  827. return this;
  828. }
  829. /**
  830. * Returns the hash of the node which is used to identify the node. By default it's
  831. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  832. * depending on their implementation.
  833. *
  834. * @param {NodeBuilder} builder - The current node builder.
  835. * @return {String} The hash.
  836. */
  837. getHash( /*builder*/ ) {
  838. return this.uuid;
  839. }
  840. /**
  841. * Returns the update type of {@link Node#update}.
  842. *
  843. * @return {NodeUpdateType} The update type.
  844. */
  845. getUpdateType() {
  846. return this.updateType;
  847. }
  848. /**
  849. * Returns the update type of {@link Node#updateBefore}.
  850. *
  851. * @return {NodeUpdateType} The update type.
  852. */
  853. getUpdateBeforeType() {
  854. return this.updateBeforeType;
  855. }
  856. /**
  857. * Returns the update type of {@link Node#updateAfter}.
  858. *
  859. * @return {NodeUpdateType} The update type.
  860. */
  861. getUpdateAfterType() {
  862. return this.updateAfterType;
  863. }
  864. /**
  865. * Certain types are composed of multiple elements. For example a `vec3`
  866. * is composed of three `float` values. This method returns the type of
  867. * these elements.
  868. *
  869. * @param {NodeBuilder} builder - The current node builder.
  870. * @return {String} The type of the node.
  871. */
  872. getElementType( builder ) {
  873. const type = this.getNodeType( builder );
  874. const elementType = builder.getElementType( type );
  875. return elementType;
  876. }
  877. /**
  878. * Returns the node's type.
  879. *
  880. * @param {NodeBuilder} builder - The current node builder.
  881. * @return {String} The type of the node.
  882. */
  883. getNodeType( builder ) {
  884. const nodeProperties = builder.getNodeProperties( this );
  885. if ( nodeProperties.outputNode ) {
  886. return nodeProperties.outputNode.getNodeType( builder );
  887. }
  888. return this.nodeType;
  889. }
  890. /**
  891. * This method is used during the build process of a node and ensures
  892. * equal nodes are not built multiple times but just once. For example if
  893. * `attribute( 'uv' )` is used multiple times by the user, the build
  894. * process makes sure to process just the first node.
  895. *
  896. * @param {NodeBuilder} builder - The current node builder.
  897. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  898. */
  899. getShared( builder ) {
  900. const hash = this.getHash( builder );
  901. const nodeFromHash = builder.getNodeFromHash( hash );
  902. return nodeFromHash || this;
  903. }
  904. /**
  905. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  906. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  907. * The output node must be returned in the `return` statement.
  908. *
  909. * @param {NodeBuilder} builder - The current node builder.
  910. * @return {Node?} The output node.
  911. */
  912. setup( builder ) {
  913. const nodeProperties = builder.getNodeProperties( this );
  914. let index = 0;
  915. for ( const childNode of this.getChildren() ) {
  916. nodeProperties[ 'node' + index ++ ] = childNode;
  917. }
  918. // return a outputNode if exists
  919. return null;
  920. }
  921. /**
  922. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  923. * This stage anaylzes the node hierarchy and ensures descendent nodes are built.
  924. *
  925. * @param {NodeBuilder} builder - The current node builder.
  926. */
  927. analyze( builder ) {
  928. const usageCount = builder.increaseUsage( this );
  929. if ( usageCount === 1 ) {
  930. // node flow children
  931. const nodeProperties = builder.getNodeProperties( this );
  932. for ( const childNode of Object.values( nodeProperties ) ) {
  933. if ( childNode && childNode.isNode === true ) {
  934. childNode.build( builder );
  935. }
  936. }
  937. }
  938. }
  939. /**
  940. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  941. * This state builds the output node and returns the resulting shader string.
  942. *
  943. * @param {NodeBuilder} builder - The current node builder.
  944. * @param {String?} output - Can be used to define the output type.
  945. * @return {String?} The generated shader string.
  946. */
  947. generate( builder, output ) {
  948. const { outputNode } = builder.getNodeProperties( this );
  949. if ( outputNode && outputNode.isNode === true ) {
  950. return outputNode.build( builder, output );
  951. }
  952. }
  953. /**
  954. * The method can be implemented to update the node's internal state before it is used to render an object.
  955. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  956. *
  957. * @param {NodeFrame} frame - A reference to the current node frame.
  958. */
  959. updateBefore( /*frame*/ ) {
  960. console.warn( 'Abstract function.' );
  961. }
  962. /**
  963. * The method can be implemented to update the node's internal state after it was used to render an object.
  964. * The {@link Node#updateAfterType} property defines how often the update is executed.
  965. *
  966. * @param {NodeFrame} frame - A reference to the current node frame.
  967. */
  968. updateAfter( /*frame*/ ) {
  969. console.warn( 'Abstract function.' );
  970. }
  971. /**
  972. * The method can be implemented to update the node's internal state when it is used to render an object.
  973. * The {@link Node#updateType} property defines how often the update is executed.
  974. *
  975. * @param {NodeFrame} frame - A reference to the current node frame.
  976. */
  977. update( /*frame*/ ) {
  978. console.warn( 'Abstract function.' );
  979. }
  980. /**
  981. * This method performs the build of a node. The behavior of this method as well as its return value depend
  982. * on the current build stage (setup, analyze or generate).
  983. *
  984. * @param {NodeBuilder} builder - The current node builder.
  985. * @param {String?} output - Can be used to define the output type.
  986. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  987. */
  988. build( builder, output = null ) {
  989. const refNode = this.getShared( builder );
  990. if ( this !== refNode ) {
  991. return refNode.build( builder, output );
  992. }
  993. builder.addNode( this );
  994. builder.addChain( this );
  995. /* Build stages expected results:
  996. - "setup" -> Node
  997. - "analyze" -> null
  998. - "generate" -> String
  999. */
  1000. let result = null;
  1001. const buildStage = builder.getBuildStage();
  1002. if ( buildStage === 'setup' ) {
  1003. this.updateReference( builder );
  1004. const properties = builder.getNodeProperties( this );
  1005. if ( properties.initialized !== true ) {
  1006. const stackNodesBeforeSetup = builder.stack.nodes.length;
  1007. properties.initialized = true;
  1008. properties.outputNode = this.setup( builder );
  1009. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  1010. for ( const childNode of Object.values( properties ) ) {
  1011. if ( childNode && childNode.isNode === true ) {
  1012. childNode.build( builder );
  1013. }
  1014. }
  1015. }
  1016. } else if ( buildStage === 'analyze' ) {
  1017. this.analyze( builder );
  1018. } else if ( buildStage === 'generate' ) {
  1019. const isGenerateOnce = this.generate.length === 1;
  1020. if ( isGenerateOnce ) {
  1021. const type = this.getNodeType( builder );
  1022. const nodeData = builder.getDataFromNode( this );
  1023. result = nodeData.snippet;
  1024. if ( result === undefined ) {
  1025. result = this.generate( builder ) || '';
  1026. nodeData.snippet = result;
  1027. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1028. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1029. }
  1030. result = builder.format( result, type, output );
  1031. } else {
  1032. result = this.generate( builder, output ) || '';
  1033. }
  1034. }
  1035. builder.removeChain( this );
  1036. builder.addSequentialNode( this );
  1037. return result;
  1038. }
  1039. /**
  1040. * Returns the child nodes as a JSON object.
  1041. *
  1042. * @return {Object} The serialized child objects as JSON.
  1043. */
  1044. getSerializeChildren() {
  1045. return getNodeChildren( this );
  1046. }
  1047. /**
  1048. * Serializes the node to JSON.
  1049. *
  1050. * @param {Object} json - The output JSON object.
  1051. */
  1052. serialize( json ) {
  1053. const nodeChildren = this.getSerializeChildren();
  1054. const inputNodes = {};
  1055. for ( const { property, index, childNode } of nodeChildren ) {
  1056. if ( index !== undefined ) {
  1057. if ( inputNodes[ property ] === undefined ) {
  1058. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1059. }
  1060. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1061. } else {
  1062. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1063. }
  1064. }
  1065. if ( Object.keys( inputNodes ).length > 0 ) {
  1066. json.inputNodes = inputNodes;
  1067. }
  1068. }
  1069. /**
  1070. * Deserializes the node from the given JSON.
  1071. *
  1072. * @param {Object} json - The JSON object.
  1073. */
  1074. deserialize( json ) {
  1075. if ( json.inputNodes !== undefined ) {
  1076. const nodes = json.meta.nodes;
  1077. for ( const property in json.inputNodes ) {
  1078. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1079. const inputArray = [];
  1080. for ( const uuid of json.inputNodes[ property ] ) {
  1081. inputArray.push( nodes[ uuid ] );
  1082. }
  1083. this[ property ] = inputArray;
  1084. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1085. const inputObject = {};
  1086. for ( const subProperty in json.inputNodes[ property ] ) {
  1087. const uuid = json.inputNodes[ property ][ subProperty ];
  1088. inputObject[ subProperty ] = nodes[ uuid ];
  1089. }
  1090. this[ property ] = inputObject;
  1091. } else {
  1092. const uuid = json.inputNodes[ property ];
  1093. this[ property ] = nodes[ uuid ];
  1094. }
  1095. }
  1096. }
  1097. }
  1098. /**
  1099. * Serializes the node into the three.js JSON Object/Scene format.
  1100. *
  1101. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1102. * @return {Object} The serialized node.
  1103. */
  1104. toJSON( meta ) {
  1105. const { uuid, type } = this;
  1106. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1107. if ( isRoot ) {
  1108. meta = {
  1109. textures: {},
  1110. images: {},
  1111. nodes: {}
  1112. };
  1113. }
  1114. // serialize
  1115. let data = meta.nodes[ uuid ];
  1116. if ( data === undefined ) {
  1117. data = {
  1118. uuid,
  1119. type,
  1120. meta,
  1121. metadata: {
  1122. version: 4.6,
  1123. type: 'Node',
  1124. generator: 'Node.toJSON'
  1125. }
  1126. };
  1127. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1128. this.serialize( data );
  1129. delete data.meta;
  1130. }
  1131. // TODO: Copied from Object3D.toJSON
  1132. function extractFromCache( cache ) {
  1133. const values = [];
  1134. for ( const key in cache ) {
  1135. const data = cache[ key ];
  1136. delete data.metadata;
  1137. values.push( data );
  1138. }
  1139. return values;
  1140. }
  1141. if ( isRoot ) {
  1142. const textures = extractFromCache( meta.textures );
  1143. const images = extractFromCache( meta.images );
  1144. const nodes = extractFromCache( meta.nodes );
  1145. if ( textures.length > 0 ) data.textures = textures;
  1146. if ( images.length > 0 ) data.images = images;
  1147. if ( nodes.length > 0 ) data.nodes = nodes;
  1148. }
  1149. return data;
  1150. }
  1151. }
  1152. class ArrayElementNode extends Node {
  1153. static get type() {
  1154. return 'ArrayElementNode';
  1155. } // @TODO: If extending from TempNode it breaks webgpu_compute
  1156. constructor( node, indexNode ) {
  1157. super();
  1158. this.node = node;
  1159. this.indexNode = indexNode;
  1160. this.isArrayElementNode = true;
  1161. }
  1162. getNodeType( builder ) {
  1163. return this.node.getElementType( builder );
  1164. }
  1165. generate( builder ) {
  1166. const nodeSnippet = this.node.build( builder );
  1167. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1168. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1169. }
  1170. }
  1171. class ConvertNode extends Node {
  1172. static get type() {
  1173. return 'ConvertNode';
  1174. }
  1175. constructor( node, convertTo ) {
  1176. super();
  1177. this.node = node;
  1178. this.convertTo = convertTo;
  1179. }
  1180. getNodeType( builder ) {
  1181. const requestType = this.node.getNodeType( builder );
  1182. let convertTo = null;
  1183. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1184. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1185. convertTo = overloadingType;
  1186. }
  1187. }
  1188. return convertTo;
  1189. }
  1190. serialize( data ) {
  1191. super.serialize( data );
  1192. data.convertTo = this.convertTo;
  1193. }
  1194. deserialize( data ) {
  1195. super.deserialize( data );
  1196. this.convertTo = data.convertTo;
  1197. }
  1198. generate( builder, output ) {
  1199. const node = this.node;
  1200. const type = this.getNodeType( builder );
  1201. const snippet = node.build( builder, type );
  1202. return builder.format( snippet, type, output );
  1203. }
  1204. }
  1205. /**
  1206. * This module uses cache management to create temporary variables
  1207. * if the node is used more than once to prevent duplicate calculations.
  1208. *
  1209. * The class acts as a base class for many other nodes types.
  1210. *
  1211. * @augments Node
  1212. */
  1213. class TempNode extends Node {
  1214. static get type() {
  1215. return 'TempNode';
  1216. }
  1217. /**
  1218. * Constructs a temp node.
  1219. *
  1220. * @param {String} nodeType - The node type.
  1221. */
  1222. constructor( type ) {
  1223. super( type );
  1224. /**
  1225. * This flag can be used for type testing.
  1226. *
  1227. * @type {Boolean}
  1228. * @readonly
  1229. * @default true
  1230. */
  1231. this.isTempNode = true;
  1232. }
  1233. /**
  1234. * Whether this node is used more than once in context of other nodes.
  1235. *
  1236. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1237. */
  1238. hasDependencies( builder ) {
  1239. return builder.getDataFromNode( this ).usageCount > 1;
  1240. }
  1241. build( builder, output ) {
  1242. const buildStage = builder.getBuildStage();
  1243. if ( buildStage === 'generate' ) {
  1244. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1245. const nodeData = builder.getDataFromNode( this );
  1246. if ( nodeData.propertyName !== undefined ) {
  1247. return builder.format( nodeData.propertyName, type, output );
  1248. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1249. const snippet = super.build( builder, type );
  1250. const nodeVar = builder.getVarFromNode( this, null, type );
  1251. const propertyName = builder.getPropertyName( nodeVar );
  1252. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1253. nodeData.snippet = snippet;
  1254. nodeData.propertyName = propertyName;
  1255. return builder.format( nodeData.propertyName, type, output );
  1256. }
  1257. }
  1258. return super.build( builder, output );
  1259. }
  1260. }
  1261. class JoinNode extends TempNode {
  1262. static get type() {
  1263. return 'JoinNode';
  1264. }
  1265. constructor( nodes = [], nodeType = null ) {
  1266. super( nodeType );
  1267. this.nodes = nodes;
  1268. }
  1269. getNodeType( builder ) {
  1270. if ( this.nodeType !== null ) {
  1271. return builder.getVectorType( this.nodeType );
  1272. }
  1273. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1274. }
  1275. generate( builder, output ) {
  1276. const type = this.getNodeType( builder );
  1277. const nodes = this.nodes;
  1278. const primitiveType = builder.getComponentType( type );
  1279. const snippetValues = [];
  1280. for ( const input of nodes ) {
  1281. let inputSnippet = input.build( builder );
  1282. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1283. if ( inputPrimitiveType !== primitiveType ) {
  1284. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1285. }
  1286. snippetValues.push( inputSnippet );
  1287. }
  1288. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1289. return builder.format( snippet, type, output );
  1290. }
  1291. }
  1292. const stringVectorComponents = vectorComponents.join( '' );
  1293. class SplitNode extends Node {
  1294. static get type() {
  1295. return 'SplitNode';
  1296. }
  1297. constructor( node, components = 'x' ) {
  1298. super();
  1299. this.node = node;
  1300. this.components = components;
  1301. this.isSplitNode = true;
  1302. }
  1303. getVectorLength() {
  1304. let vectorLength = this.components.length;
  1305. for ( const c of this.components ) {
  1306. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1307. }
  1308. return vectorLength;
  1309. }
  1310. getComponentType( builder ) {
  1311. return builder.getComponentType( this.node.getNodeType( builder ) );
  1312. }
  1313. getNodeType( builder ) {
  1314. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1315. }
  1316. generate( builder, output ) {
  1317. const node = this.node;
  1318. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1319. let snippet = null;
  1320. if ( nodeTypeLength > 1 ) {
  1321. let type = null;
  1322. const componentsLength = this.getVectorLength();
  1323. if ( componentsLength >= nodeTypeLength ) {
  1324. // needed expand the input node
  1325. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1326. }
  1327. const nodeSnippet = node.build( builder, type );
  1328. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  1329. // unnecessary swizzle
  1330. snippet = builder.format( nodeSnippet, type, output );
  1331. } else {
  1332. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1333. }
  1334. } else {
  1335. // ignore .components if .node returns float/integer
  1336. snippet = node.build( builder, output );
  1337. }
  1338. return snippet;
  1339. }
  1340. serialize( data ) {
  1341. super.serialize( data );
  1342. data.components = this.components;
  1343. }
  1344. deserialize( data ) {
  1345. super.deserialize( data );
  1346. this.components = data.components;
  1347. }
  1348. }
  1349. class SetNode extends TempNode {
  1350. static get type() {
  1351. return 'SetNode';
  1352. }
  1353. constructor( sourceNode, components, targetNode ) {
  1354. super();
  1355. this.sourceNode = sourceNode;
  1356. this.components = components;
  1357. this.targetNode = targetNode;
  1358. }
  1359. getNodeType( builder ) {
  1360. return this.sourceNode.getNodeType( builder );
  1361. }
  1362. generate( builder ) {
  1363. const { sourceNode, components, targetNode } = this;
  1364. const sourceType = this.getNodeType( builder );
  1365. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  1366. const targetSnippet = targetNode.build( builder, targetType );
  1367. const sourceSnippet = sourceNode.build( builder, sourceType );
  1368. const length = builder.getTypeLength( sourceType );
  1369. const snippetValues = [];
  1370. for ( let i = 0; i < length; i ++ ) {
  1371. const component = vectorComponents[ i ];
  1372. if ( component === components[ 0 ] ) {
  1373. snippetValues.push( targetSnippet );
  1374. i += components.length - 1;
  1375. } else {
  1376. snippetValues.push( sourceSnippet + '.' + component );
  1377. }
  1378. }
  1379. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1380. }
  1381. }
  1382. class FlipNode extends TempNode {
  1383. static get type() {
  1384. return 'FlipNode';
  1385. }
  1386. constructor( sourceNode, components ) {
  1387. super();
  1388. this.sourceNode = sourceNode;
  1389. this.components = components;
  1390. }
  1391. getNodeType( builder ) {
  1392. return this.sourceNode.getNodeType( builder );
  1393. }
  1394. generate( builder ) {
  1395. const { components, sourceNode } = this;
  1396. const sourceType = this.getNodeType( builder );
  1397. const sourceSnippet = sourceNode.build( builder );
  1398. const sourceCache = builder.getVarFromNode( this );
  1399. const sourceProperty = builder.getPropertyName( sourceCache );
  1400. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1401. const length = builder.getTypeLength( sourceType );
  1402. const snippetValues = [];
  1403. let componentIndex = 0;
  1404. for ( let i = 0; i < length; i ++ ) {
  1405. const component = vectorComponents[ i ];
  1406. if ( component === components[ componentIndex ] ) {
  1407. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1408. componentIndex ++;
  1409. } else {
  1410. snippetValues.push( sourceProperty + '.' + component );
  1411. }
  1412. }
  1413. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1414. }
  1415. }
  1416. /**
  1417. * Base class for representing data input nodes.
  1418. *
  1419. * @augments Node
  1420. */
  1421. class InputNode extends Node {
  1422. static get type() {
  1423. return 'InputNode';
  1424. }
  1425. /**
  1426. * Constructs a new input node.
  1427. *
  1428. * @param {Any} value - The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1429. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1430. */
  1431. constructor( value, nodeType = null ) {
  1432. super( nodeType );
  1433. /**
  1434. * This flag can be used for type testing.
  1435. *
  1436. * @type {Boolean}
  1437. * @readonly
  1438. * @default true
  1439. */
  1440. this.isInputNode = true;
  1441. /**
  1442. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1443. *
  1444. * @type {Any}
  1445. */
  1446. this.value = value;
  1447. /**
  1448. * The precision of the value in the shader.
  1449. *
  1450. * @type {('low'|'medium'|'high')?}
  1451. * @default null
  1452. */
  1453. this.precision = null;
  1454. }
  1455. getNodeType( /*builder*/ ) {
  1456. if ( this.nodeType === null ) {
  1457. return getValueType( this.value );
  1458. }
  1459. return this.nodeType;
  1460. }
  1461. /**
  1462. * Returns the input type of the node which is by default the node type. Derived modules
  1463. * might overwrite this method and use a fixed type or compute one analytically.
  1464. *
  1465. * A typical example for different input and node types are textures. The input type of a
  1466. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1467. *
  1468. * @param {NodeBuilder} builder - The current node builder.
  1469. * @return {String} The input type.
  1470. */
  1471. getInputType( builder ) {
  1472. return this.getNodeType( builder );
  1473. }
  1474. /**
  1475. * Sets the precision to the given value. The method can be
  1476. * overwritten in derived classes if the final precision must be computed
  1477. * analytically.
  1478. *
  1479. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1480. * @return {InputNode} A reference to this node.
  1481. */
  1482. setPrecision( precision ) {
  1483. this.precision = precision;
  1484. return this;
  1485. }
  1486. serialize( data ) {
  1487. super.serialize( data );
  1488. data.value = this.value;
  1489. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1490. data.valueType = getValueType( this.value );
  1491. data.nodeType = this.nodeType;
  1492. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1493. data.precision = this.precision;
  1494. }
  1495. deserialize( data ) {
  1496. super.deserialize( data );
  1497. this.nodeType = data.nodeType;
  1498. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1499. this.precision = data.precision || null;
  1500. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1501. }
  1502. generate( /*builder, output*/ ) {
  1503. console.warn( 'Abstract function.' );
  1504. }
  1505. }
  1506. /**
  1507. * Class for representing a constant value in the shader.
  1508. *
  1509. * @augments InputNode
  1510. */
  1511. class ConstNode extends InputNode {
  1512. static get type() {
  1513. return 'ConstNode';
  1514. }
  1515. /**
  1516. * Constructs a new input node.
  1517. *
  1518. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1519. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1520. */
  1521. constructor( value, nodeType = null ) {
  1522. super( value, nodeType );
  1523. /**
  1524. * This flag can be used for type testing.
  1525. *
  1526. * @type {Boolean}
  1527. * @readonly
  1528. * @default true
  1529. */
  1530. this.isConstNode = true;
  1531. }
  1532. /**
  1533. * Generates the shader string of the value with the current node builder.
  1534. *
  1535. * @param {NodeBuilder} builder - The current node builder.
  1536. * @return {String} The generated value as a shader string.
  1537. */
  1538. generateConst( builder ) {
  1539. return builder.generateConst( this.getNodeType( builder ), this.value );
  1540. }
  1541. generate( builder, output ) {
  1542. const type = this.getNodeType( builder );
  1543. return builder.format( this.generateConst( builder ), type, output );
  1544. }
  1545. }
  1546. //
  1547. let currentStack = null;
  1548. const NodeElements = new Map();
  1549. function addMethodChaining( name, nodeElement ) {
  1550. if ( NodeElements.has( name ) ) {
  1551. console.warn( `Redefinition of method chaining ${ name }` );
  1552. return;
  1553. }
  1554. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1555. NodeElements.set( name, nodeElement );
  1556. }
  1557. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1558. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1559. const shaderNodeHandler = {
  1560. setup( NodeClosure, params ) {
  1561. const inputs = params.shift();
  1562. return NodeClosure( nodeObjects( inputs ), ...params );
  1563. },
  1564. get( node, prop, nodeObj ) {
  1565. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1566. if ( node.isStackNode !== true && prop === 'assign' ) {
  1567. return ( ...params ) => {
  1568. currentStack.assign( nodeObj, ...params );
  1569. return nodeObj;
  1570. };
  1571. } else if ( NodeElements.has( prop ) ) {
  1572. const nodeElement = NodeElements.get( prop );
  1573. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1574. } else if ( prop === 'self' ) {
  1575. return node;
  1576. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1577. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1578. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1579. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1580. // accessing properties ( swizzle )
  1581. prop = parseSwizzle( prop );
  1582. return nodeObject( new SplitNode( nodeObj, prop ) );
  1583. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1584. // set properties ( swizzle ) and sort to xyzw sequence
  1585. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1586. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1587. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1588. // set properties ( swizzle ) and sort to xyzw sequence
  1589. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1590. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1591. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1592. // accessing property
  1593. if ( prop === 'width' ) prop = 'x';
  1594. else if ( prop === 'height' ) prop = 'y';
  1595. else if ( prop === 'depth' ) prop = 'z';
  1596. return nodeObject( new SplitNode( node, prop ) );
  1597. } else if ( /^\d+$/.test( prop ) === true ) {
  1598. // accessing array
  1599. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1600. }
  1601. }
  1602. return Reflect.get( node, prop, nodeObj );
  1603. },
  1604. set( node, prop, value, nodeObj ) {
  1605. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1606. // setting properties
  1607. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1608. nodeObj[ prop ].assign( value );
  1609. return true;
  1610. }
  1611. }
  1612. return Reflect.set( node, prop, value, nodeObj );
  1613. }
  1614. };
  1615. const nodeObjectsCacheMap = new WeakMap();
  1616. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1617. const ShaderNodeObject = function ( obj, altType = null ) {
  1618. const type = getValueType( obj );
  1619. if ( type === 'node' ) {
  1620. let nodeObject = nodeObjectsCacheMap.get( obj );
  1621. if ( nodeObject === undefined ) {
  1622. nodeObject = new Proxy( obj, shaderNodeHandler );
  1623. nodeObjectsCacheMap.set( obj, nodeObject );
  1624. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1625. }
  1626. return nodeObject;
  1627. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1628. return nodeObject( getConstNode( obj, altType ) );
  1629. } else if ( type === 'shader' ) {
  1630. return Fn( obj );
  1631. }
  1632. return obj;
  1633. };
  1634. const ShaderNodeObjects = function ( objects, altType = null ) {
  1635. for ( const name in objects ) {
  1636. objects[ name ] = nodeObject( objects[ name ], altType );
  1637. }
  1638. return objects;
  1639. };
  1640. const ShaderNodeArray = function ( array, altType = null ) {
  1641. const len = array.length;
  1642. for ( let i = 0; i < len; i ++ ) {
  1643. array[ i ] = nodeObject( array[ i ], altType );
  1644. }
  1645. return array;
  1646. };
  1647. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1648. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1649. if ( scope === null ) {
  1650. return ( ...params ) => {
  1651. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1652. };
  1653. } else if ( factor !== null ) {
  1654. factor = nodeObject( factor );
  1655. return ( ...params ) => {
  1656. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1657. };
  1658. } else {
  1659. return ( ...params ) => {
  1660. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1661. };
  1662. }
  1663. };
  1664. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1665. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1666. };
  1667. class ShaderCallNodeInternal extends Node {
  1668. constructor( shaderNode, inputNodes ) {
  1669. super();
  1670. this.shaderNode = shaderNode;
  1671. this.inputNodes = inputNodes;
  1672. }
  1673. getNodeType( builder ) {
  1674. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1675. }
  1676. call( builder ) {
  1677. const { shaderNode, inputNodes } = this;
  1678. const properties = builder.getNodeProperties( shaderNode );
  1679. if ( properties.onceOutput ) return properties.onceOutput;
  1680. //
  1681. let result = null;
  1682. if ( shaderNode.layout ) {
  1683. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1684. if ( functionNodesCacheMap === undefined ) {
  1685. functionNodesCacheMap = new WeakMap();
  1686. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1687. }
  1688. let functionNode = functionNodesCacheMap.get( shaderNode );
  1689. if ( functionNode === undefined ) {
  1690. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1691. functionNodesCacheMap.set( shaderNode, functionNode );
  1692. }
  1693. if ( builder.currentFunctionNode !== null ) {
  1694. builder.currentFunctionNode.includes.push( functionNode );
  1695. }
  1696. result = nodeObject( functionNode.call( inputNodes ) );
  1697. } else {
  1698. const jsFunc = shaderNode.jsFunc;
  1699. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1700. result = nodeObject( outputNode );
  1701. }
  1702. if ( shaderNode.once ) {
  1703. properties.onceOutput = result;
  1704. }
  1705. return result;
  1706. }
  1707. getOutputNode( builder ) {
  1708. const properties = builder.getNodeProperties( this );
  1709. if ( properties.outputNode === null ) {
  1710. properties.outputNode = this.setupOutput( builder );
  1711. }
  1712. return properties.outputNode;
  1713. }
  1714. setup( builder ) {
  1715. return this.getOutputNode( builder );
  1716. }
  1717. setupOutput( builder ) {
  1718. builder.addStack();
  1719. builder.stack.outputNode = this.call( builder );
  1720. return builder.removeStack();
  1721. }
  1722. generate( builder, output ) {
  1723. const outputNode = this.getOutputNode( builder );
  1724. return outputNode.build( builder, output );
  1725. }
  1726. }
  1727. class ShaderNodeInternal extends Node {
  1728. constructor( jsFunc, nodeType ) {
  1729. super( nodeType );
  1730. this.jsFunc = jsFunc;
  1731. this.layout = null;
  1732. this.global = true;
  1733. this.once = false;
  1734. }
  1735. setLayout( layout ) {
  1736. this.layout = layout;
  1737. return this;
  1738. }
  1739. call( inputs = null ) {
  1740. nodeObjects( inputs );
  1741. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1742. }
  1743. setup() {
  1744. return this.call();
  1745. }
  1746. }
  1747. const bools = [ false, true ];
  1748. const uints = [ 0, 1, 2, 3 ];
  1749. const ints = [ - 1, - 2 ];
  1750. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  1751. const boolsCacheMap = new Map();
  1752. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1753. const uintsCacheMap = new Map();
  1754. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1755. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1756. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1757. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1758. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1759. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1760. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1761. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1762. const getConstNode = ( value, type ) => {
  1763. if ( constNodesCacheMap.has( value ) ) {
  1764. return constNodesCacheMap.get( value );
  1765. } else if ( value.isNode === true ) {
  1766. return value;
  1767. } else {
  1768. return new ConstNode( value, type );
  1769. }
  1770. };
  1771. const safeGetNodeType = ( node ) => {
  1772. try {
  1773. return node.getNodeType();
  1774. } catch ( _ ) {
  1775. return undefined;
  1776. }
  1777. };
  1778. const ConvertType = function ( type, cacheMap = null ) {
  1779. return ( ...params ) => {
  1780. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  1781. params = [ getValueFromType( type, ...params ) ];
  1782. }
  1783. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  1784. return nodeObject( cacheMap.get( params[ 0 ] ) );
  1785. }
  1786. if ( params.length === 1 ) {
  1787. const node = getConstNode( params[ 0 ], type );
  1788. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  1789. return nodeObject( new ConvertNode( node, type ) );
  1790. }
  1791. const nodes = params.map( param => getConstNode( param ) );
  1792. return nodeObject( new JoinNode( nodes, type ) );
  1793. };
  1794. };
  1795. // exports
  1796. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  1797. // utils
  1798. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  1799. // shader node base
  1800. function ShaderNode( jsFunc, nodeType ) {
  1801. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  1802. }
  1803. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  1804. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  1805. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  1806. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  1807. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  1808. const Fn = ( jsFunc, nodeType ) => {
  1809. const shaderNode = new ShaderNode( jsFunc, nodeType );
  1810. const fn = ( ...params ) => {
  1811. let inputs;
  1812. nodeObjects( params );
  1813. if ( params[ 0 ] && params[ 0 ].isNode ) {
  1814. inputs = [ ...params ];
  1815. } else {
  1816. inputs = params[ 0 ];
  1817. }
  1818. return shaderNode.call( inputs );
  1819. };
  1820. fn.shaderNode = shaderNode;
  1821. fn.setLayout = ( layout ) => {
  1822. shaderNode.setLayout( layout );
  1823. return fn;
  1824. };
  1825. fn.once = () => {
  1826. shaderNode.once = true;
  1827. return fn;
  1828. };
  1829. return fn;
  1830. };
  1831. const tslFn = ( ...params ) => { // @deprecated, r168
  1832. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  1833. return Fn( ...params );
  1834. };
  1835. //
  1836. addMethodChaining( 'toGlobal', ( node ) => {
  1837. node.global = true;
  1838. return node;
  1839. } );
  1840. //
  1841. const setCurrentStack = ( stack ) => {
  1842. currentStack = stack;
  1843. };
  1844. const getCurrentStack = () => currentStack;
  1845. const If = ( ...params ) => currentStack.If( ...params );
  1846. function append( node ) {
  1847. if ( currentStack ) currentStack.add( node );
  1848. return node;
  1849. }
  1850. addMethodChaining( 'append', append );
  1851. // types
  1852. const color = new ConvertType( 'color' );
  1853. const float = new ConvertType( 'float', cacheMaps.float );
  1854. const int = new ConvertType( 'int', cacheMaps.ints );
  1855. const uint = new ConvertType( 'uint', cacheMaps.uint );
  1856. const bool = new ConvertType( 'bool', cacheMaps.bool );
  1857. const vec2 = new ConvertType( 'vec2' );
  1858. const ivec2 = new ConvertType( 'ivec2' );
  1859. const uvec2 = new ConvertType( 'uvec2' );
  1860. const bvec2 = new ConvertType( 'bvec2' );
  1861. const vec3 = new ConvertType( 'vec3' );
  1862. const ivec3 = new ConvertType( 'ivec3' );
  1863. const uvec3 = new ConvertType( 'uvec3' );
  1864. const bvec3 = new ConvertType( 'bvec3' );
  1865. const vec4 = new ConvertType( 'vec4' );
  1866. const ivec4 = new ConvertType( 'ivec4' );
  1867. const uvec4 = new ConvertType( 'uvec4' );
  1868. const bvec4 = new ConvertType( 'bvec4' );
  1869. const mat2 = new ConvertType( 'mat2' );
  1870. const mat3 = new ConvertType( 'mat3' );
  1871. const mat4 = new ConvertType( 'mat4' );
  1872. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  1873. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  1874. addMethodChaining( 'toColor', color );
  1875. addMethodChaining( 'toFloat', float );
  1876. addMethodChaining( 'toInt', int );
  1877. addMethodChaining( 'toUint', uint );
  1878. addMethodChaining( 'toBool', bool );
  1879. addMethodChaining( 'toVec2', vec2 );
  1880. addMethodChaining( 'toIVec2', ivec2 );
  1881. addMethodChaining( 'toUVec2', uvec2 );
  1882. addMethodChaining( 'toBVec2', bvec2 );
  1883. addMethodChaining( 'toVec3', vec3 );
  1884. addMethodChaining( 'toIVec3', ivec3 );
  1885. addMethodChaining( 'toUVec3', uvec3 );
  1886. addMethodChaining( 'toBVec3', bvec3 );
  1887. addMethodChaining( 'toVec4', vec4 );
  1888. addMethodChaining( 'toIVec4', ivec4 );
  1889. addMethodChaining( 'toUVec4', uvec4 );
  1890. addMethodChaining( 'toBVec4', bvec4 );
  1891. addMethodChaining( 'toMat2', mat2 );
  1892. addMethodChaining( 'toMat3', mat3 );
  1893. addMethodChaining( 'toMat4', mat4 );
  1894. // basic nodes
  1895. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  1896. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  1897. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  1898. addMethodChaining( 'element', element );
  1899. addMethodChaining( 'convert', convert );
  1900. /**
  1901. * This node can be used to group single instances of {@link UniformNode}
  1902. * and manage them as a uniform buffer.
  1903. *
  1904. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  1905. * will be used when defining the {@link UniformNode#groupNode} property.
  1906. *
  1907. * - `objectGroup`: Uniform buffer per object.
  1908. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  1909. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  1910. *
  1911. * @augments Node
  1912. */
  1913. class UniformGroupNode extends Node {
  1914. static get type() {
  1915. return 'UniformGroupNode';
  1916. }
  1917. /**
  1918. * Constructs a new uniform group node.
  1919. *
  1920. * @param {String} name - The name of the uniform group node.
  1921. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  1922. * @param {Number} [order=1] - Influences the internal sorting.
  1923. */
  1924. constructor( name, shared = false, order = 1 ) {
  1925. super( 'string' );
  1926. /**
  1927. * The name of the uniform group node.
  1928. *
  1929. * @type {String}
  1930. */
  1931. this.name = name;
  1932. /**
  1933. * Whether this uniform group node is shared or not.
  1934. *
  1935. * @type {Boolean}
  1936. * @default false
  1937. */
  1938. this.shared = shared;
  1939. /**
  1940. * Influences the internal sorting.
  1941. * TODO: Add details when this property should be changed.
  1942. *
  1943. * @type {Number}
  1944. * @default 1
  1945. */
  1946. this.order = order;
  1947. /**
  1948. * This flag can be used for type testing.
  1949. *
  1950. * @type {Boolean}
  1951. * @readonly
  1952. * @default true
  1953. */
  1954. this.isUniformGroup = true;
  1955. }
  1956. serialize( data ) {
  1957. super.serialize( data );
  1958. data.name = this.name;
  1959. data.version = this.version;
  1960. data.shared = this.shared;
  1961. }
  1962. deserialize( data ) {
  1963. super.deserialize( data );
  1964. this.name = data.name;
  1965. this.version = data.version;
  1966. this.shared = data.shared;
  1967. }
  1968. }
  1969. const uniformGroup = ( name ) => new UniformGroupNode( name );
  1970. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  1971. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  1972. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  1973. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  1974. /**
  1975. * Class for representing a uniform.
  1976. *
  1977. * @augments InputNode
  1978. */
  1979. class UniformNode extends InputNode {
  1980. static get type() {
  1981. return 'UniformNode';
  1982. }
  1983. /**
  1984. * Constructs a new uniform node.
  1985. *
  1986. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  1987. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1988. */
  1989. constructor( value, nodeType = null ) {
  1990. super( value, nodeType );
  1991. /**
  1992. * This flag can be used for type testing.
  1993. *
  1994. * @type {Boolean}
  1995. * @readonly
  1996. * @default true
  1997. */
  1998. this.isUniformNode = true;
  1999. /**
  2000. * The name or label of the uniform.
  2001. *
  2002. * @type {String}
  2003. * @default ''
  2004. */
  2005. this.name = '';
  2006. /**
  2007. * The uniform group of this uniform. By default, uniforms are
  2008. * managed per object but they might belong to a shared group
  2009. * which is updated per frame or render call.
  2010. *
  2011. * @type {UniformGroupNode}
  2012. */
  2013. this.groupNode = objectGroup;
  2014. }
  2015. /**
  2016. * Sets the {@link UniformNode#name} property.
  2017. *
  2018. * @param {String} name - The name of the uniform.
  2019. * @return {UniformNode} A reference to this node.
  2020. */
  2021. label( name ) {
  2022. this.name = name;
  2023. return this;
  2024. }
  2025. /**
  2026. * Sets the {@link UniformNode#groupNode} property.
  2027. *
  2028. * @param {UniformGroupNode} group - The uniform group.
  2029. * @return {UniformNode} A reference to this node.
  2030. */
  2031. setGroup( group ) {
  2032. this.groupNode = group;
  2033. return this;
  2034. }
  2035. /**
  2036. * Returns the {@link UniformNode#groupNode}.
  2037. *
  2038. * @return {UniformGroupNode} The uniform group.
  2039. */
  2040. getGroup() {
  2041. return this.groupNode;
  2042. }
  2043. /**
  2044. * By default, this method returns the result of {@link Node#getHash} but derived
  2045. * classes might overwrite this method with a different implementation.
  2046. *
  2047. * @param {NodeBuilder} builder - The current node builder.
  2048. * @return {String} The uniform hash.
  2049. */
  2050. getUniformHash( builder ) {
  2051. return this.getHash( builder );
  2052. }
  2053. onUpdate( callback, updateType ) {
  2054. const self = this.getSelf();
  2055. callback = callback.bind( self );
  2056. return super.onUpdate( ( frame ) => {
  2057. const value = callback( frame, self );
  2058. if ( value !== undefined ) {
  2059. this.value = value;
  2060. }
  2061. }, updateType );
  2062. }
  2063. generate( builder, output ) {
  2064. const type = this.getNodeType( builder );
  2065. const hash = this.getUniformHash( builder );
  2066. let sharedNode = builder.getNodeFromHash( hash );
  2067. if ( sharedNode === undefined ) {
  2068. builder.setHashNode( this, hash );
  2069. sharedNode = this;
  2070. }
  2071. const sharedNodeType = sharedNode.getInputType( builder );
  2072. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2073. const propertyName = builder.getPropertyName( nodeUniform );
  2074. if ( builder.context.label !== undefined ) delete builder.context.label;
  2075. return builder.format( propertyName, type, output );
  2076. }
  2077. }
  2078. const uniform = ( arg1, arg2 ) => {
  2079. const nodeType = getConstNodeType( arg2 || arg1 );
  2080. // @TODO: get ConstNode from .traverse() in the future
  2081. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2082. return nodeObject( new UniformNode( value, nodeType ) );
  2083. };
  2084. class PropertyNode extends Node {
  2085. static get type() {
  2086. return 'PropertyNode';
  2087. }
  2088. constructor( nodeType, name = null, varying = false ) {
  2089. super( nodeType );
  2090. this.name = name;
  2091. this.varying = varying;
  2092. this.isPropertyNode = true;
  2093. }
  2094. getHash( builder ) {
  2095. return this.name || super.getHash( builder );
  2096. }
  2097. isGlobal( /*builder*/ ) {
  2098. return true;
  2099. }
  2100. generate( builder ) {
  2101. let nodeVar;
  2102. if ( this.varying === true ) {
  2103. nodeVar = builder.getVaryingFromNode( this, this.name );
  2104. nodeVar.needsInterpolation = true;
  2105. } else {
  2106. nodeVar = builder.getVarFromNode( this, this.name );
  2107. }
  2108. return builder.getPropertyName( nodeVar );
  2109. }
  2110. }
  2111. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2112. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2113. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2114. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2115. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2116. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2117. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2118. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2119. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2120. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2121. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2122. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2123. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2124. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2125. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2126. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2127. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2128. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2129. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2130. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2131. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2132. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2133. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2134. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2135. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2136. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2137. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2138. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2139. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2140. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2141. /**
  2142. * These node represents an assign operation. Meaning a node is assigned
  2143. * to another node.
  2144. *
  2145. * @augments TempNode
  2146. */
  2147. class AssignNode extends TempNode {
  2148. static get type() {
  2149. return 'AssignNode';
  2150. }
  2151. /**
  2152. * Constructs a new assign node.
  2153. *
  2154. * @param {Node} targetNode - The target node.
  2155. * @param {Node} sourceNode - The source type.
  2156. */
  2157. constructor( targetNode, sourceNode ) {
  2158. super();
  2159. /**
  2160. * The target node.
  2161. *
  2162. * @type {Node}
  2163. */
  2164. this.targetNode = targetNode;
  2165. /**
  2166. * The source node.
  2167. *
  2168. * @type {Node}
  2169. */
  2170. this.sourceNode = sourceNode;
  2171. }
  2172. /**
  2173. * Whether this node is used more than once in context of other nodes. This method
  2174. * is overwritten since it always returns `false` (assigns are unique).
  2175. *
  2176. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2177. */
  2178. hasDependencies() {
  2179. return false;
  2180. }
  2181. getNodeType( builder, output ) {
  2182. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2183. }
  2184. /**
  2185. * Whether a split is required when assigning source to target. This can happen when the component length of
  2186. * target and source data type does not match.
  2187. *
  2188. * @param {NodeBuilder} builder - The current node builder.
  2189. * @return {Boolean} Whether a split is required when assigning source to target.
  2190. */
  2191. needsSplitAssign( builder ) {
  2192. const { targetNode } = this;
  2193. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2194. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2195. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2196. return assignDifferentVector;
  2197. }
  2198. return false;
  2199. }
  2200. generate( builder, output ) {
  2201. const { targetNode, sourceNode } = this;
  2202. const needsSplitAssign = this.needsSplitAssign( builder );
  2203. const targetType = targetNode.getNodeType( builder );
  2204. const target = targetNode.context( { assign: true } ).build( builder );
  2205. const source = sourceNode.build( builder, targetType );
  2206. const sourceType = sourceNode.getNodeType( builder );
  2207. const nodeData = builder.getDataFromNode( this );
  2208. //
  2209. let snippet;
  2210. if ( nodeData.initialized === true ) {
  2211. if ( output !== 'void' ) {
  2212. snippet = target;
  2213. }
  2214. } else if ( needsSplitAssign ) {
  2215. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2216. const sourceProperty = builder.getPropertyName( sourceVar );
  2217. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2218. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2219. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2220. const component = targetNode.components[ i ];
  2221. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2222. }
  2223. if ( output !== 'void' ) {
  2224. snippet = target;
  2225. }
  2226. } else {
  2227. snippet = `${ target } = ${ source }`;
  2228. if ( output === 'void' || sourceType === 'void' ) {
  2229. builder.addLineFlowCode( snippet, this );
  2230. if ( output !== 'void' ) {
  2231. snippet = target;
  2232. }
  2233. }
  2234. }
  2235. nodeData.initialized = true;
  2236. return builder.format( snippet, targetType, output );
  2237. }
  2238. }
  2239. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2240. addMethodChaining( 'assign', assign );
  2241. /**
  2242. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2243. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2244. * this logic.
  2245. *
  2246. * @augments TempNode
  2247. */
  2248. class FunctionCallNode extends TempNode {
  2249. static get type() {
  2250. return 'FunctionCallNode';
  2251. }
  2252. /**
  2253. * Constructs a new function call node.
  2254. *
  2255. * @param {FunctionNode?} functionNode - The function node.
  2256. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2257. */
  2258. constructor( functionNode = null, parameters = {} ) {
  2259. super();
  2260. /**
  2261. * The function node.
  2262. *
  2263. * @type {FunctionNode}
  2264. * @default null
  2265. */
  2266. this.functionNode = functionNode;
  2267. /**
  2268. * The parameters of the function call.
  2269. *
  2270. * @type {Object<String, Node>}
  2271. * @default {}
  2272. */
  2273. this.parameters = parameters;
  2274. }
  2275. /**
  2276. * Sets the parameters of the function call node.
  2277. *
  2278. * @param {Object<String, Node>} parameters - The parameters to set.
  2279. * @return {FunctionCallNode} A reference to this node.
  2280. */
  2281. setParameters( parameters ) {
  2282. this.parameters = parameters;
  2283. return this;
  2284. }
  2285. /**
  2286. * Returns the parameters of the function call node.
  2287. *
  2288. * @return {Object<String, Node>} The parameters of this node.
  2289. */
  2290. getParameters() {
  2291. return this.parameters;
  2292. }
  2293. getNodeType( builder ) {
  2294. return this.functionNode.getNodeType( builder );
  2295. }
  2296. generate( builder ) {
  2297. const params = [];
  2298. const functionNode = this.functionNode;
  2299. const inputs = functionNode.getInputs( builder );
  2300. const parameters = this.parameters;
  2301. const generateInput = ( node, inputNode ) => {
  2302. const type = inputNode.type;
  2303. const pointer = type === 'pointer';
  2304. let output;
  2305. if ( pointer ) output = '&' + node.build( builder );
  2306. else output = node.build( builder, type );
  2307. return output;
  2308. };
  2309. if ( Array.isArray( parameters ) ) {
  2310. for ( let i = 0; i < parameters.length; i ++ ) {
  2311. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2312. }
  2313. } else {
  2314. for ( const inputNode of inputs ) {
  2315. const node = parameters[ inputNode.name ];
  2316. if ( node !== undefined ) {
  2317. params.push( generateInput( node, inputNode ) );
  2318. } else {
  2319. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2320. }
  2321. }
  2322. }
  2323. const functionName = functionNode.build( builder, 'property' );
  2324. return `${functionName}( ${params.join( ', ' )} )`;
  2325. }
  2326. }
  2327. const call = ( func, ...params ) => {
  2328. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2329. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2330. };
  2331. addMethodChaining( 'call', call );
  2332. class OperatorNode extends TempNode {
  2333. static get type() {
  2334. return 'OperatorNode';
  2335. }
  2336. constructor( op, aNode, bNode, ...params ) {
  2337. super();
  2338. if ( params.length > 0 ) {
  2339. let finalOp = new OperatorNode( op, aNode, bNode );
  2340. for ( let i = 0; i < params.length - 1; i ++ ) {
  2341. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2342. }
  2343. aNode = finalOp;
  2344. bNode = params[ params.length - 1 ];
  2345. }
  2346. this.op = op;
  2347. this.aNode = aNode;
  2348. this.bNode = bNode;
  2349. }
  2350. getNodeType( builder, output ) {
  2351. const op = this.op;
  2352. const aNode = this.aNode;
  2353. const bNode = this.bNode;
  2354. const typeA = aNode.getNodeType( builder );
  2355. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2356. if ( typeA === 'void' || typeB === 'void' ) {
  2357. return 'void';
  2358. } else if ( op === '%' ) {
  2359. return typeA;
  2360. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  2361. return builder.getIntegerType( typeA );
  2362. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  2363. return 'bool';
  2364. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  2365. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  2366. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  2367. } else {
  2368. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  2369. return typeB;
  2370. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2371. // matrix x vector
  2372. return builder.getVectorFromMatrix( typeA );
  2373. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2374. // vector x matrix
  2375. return builder.getVectorFromMatrix( typeB );
  2376. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  2377. // anytype x anytype: use the greater length vector
  2378. return typeB;
  2379. }
  2380. return typeA;
  2381. }
  2382. }
  2383. generate( builder, output ) {
  2384. const op = this.op;
  2385. const aNode = this.aNode;
  2386. const bNode = this.bNode;
  2387. const type = this.getNodeType( builder, output );
  2388. let typeA = null;
  2389. let typeB = null;
  2390. if ( type !== 'void' ) {
  2391. typeA = aNode.getNodeType( builder );
  2392. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2393. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  2394. if ( builder.isVector( typeA ) ) {
  2395. typeB = typeA;
  2396. } else if ( typeA !== typeB ) {
  2397. typeA = typeB = 'float';
  2398. }
  2399. } else if ( op === '>>' || op === '<<' ) {
  2400. typeA = type;
  2401. typeB = builder.changeComponentType( typeB, 'uint' );
  2402. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2403. // matrix x vector
  2404. typeB = builder.getVectorFromMatrix( typeA );
  2405. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2406. // vector x matrix
  2407. typeA = builder.getVectorFromMatrix( typeB );
  2408. } else {
  2409. // anytype x anytype
  2410. typeA = typeB = type;
  2411. }
  2412. } else {
  2413. typeA = typeB = type;
  2414. }
  2415. const a = aNode.build( builder, typeA );
  2416. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  2417. const outputLength = builder.getTypeLength( output );
  2418. const fnOpSnippet = builder.getFunctionOperator( op );
  2419. if ( output !== 'void' ) {
  2420. if ( op === '<' && outputLength > 1 ) {
  2421. if ( builder.useComparisonMethod ) {
  2422. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  2423. } else {
  2424. return builder.format( `( ${ a } < ${ b } )`, type, output );
  2425. }
  2426. } else if ( op === '<=' && outputLength > 1 ) {
  2427. if ( builder.useComparisonMethod ) {
  2428. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2429. } else {
  2430. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  2431. }
  2432. } else if ( op === '>' && outputLength > 1 ) {
  2433. if ( builder.useComparisonMethod ) {
  2434. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  2435. } else {
  2436. return builder.format( `( ${ a } > ${ b } )`, type, output );
  2437. }
  2438. } else if ( op === '>=' && outputLength > 1 ) {
  2439. if ( builder.useComparisonMethod ) {
  2440. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2441. } else {
  2442. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  2443. }
  2444. } else if ( op === '!' || op === '~' ) {
  2445. return builder.format( `(${op}${a})`, typeA, output );
  2446. } else if ( fnOpSnippet ) {
  2447. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2448. } else {
  2449. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  2450. }
  2451. } else if ( typeA !== 'void' ) {
  2452. if ( fnOpSnippet ) {
  2453. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2454. } else {
  2455. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  2456. }
  2457. }
  2458. }
  2459. serialize( data ) {
  2460. super.serialize( data );
  2461. data.op = this.op;
  2462. }
  2463. deserialize( data ) {
  2464. super.deserialize( data );
  2465. this.op = data.op;
  2466. }
  2467. }
  2468. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  2469. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  2470. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  2471. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  2472. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  2473. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  2474. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  2475. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  2476. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  2477. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  2478. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  2479. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  2480. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  2481. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  2482. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  2483. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  2484. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  2485. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  2486. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  2487. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  2488. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  2489. addMethodChaining( 'add', add );
  2490. addMethodChaining( 'sub', sub );
  2491. addMethodChaining( 'mul', mul );
  2492. addMethodChaining( 'div', div );
  2493. addMethodChaining( 'modInt', modInt );
  2494. addMethodChaining( 'equal', equal );
  2495. addMethodChaining( 'notEqual', notEqual );
  2496. addMethodChaining( 'lessThan', lessThan );
  2497. addMethodChaining( 'greaterThan', greaterThan );
  2498. addMethodChaining( 'lessThanEqual', lessThanEqual );
  2499. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  2500. addMethodChaining( 'and', and );
  2501. addMethodChaining( 'or', or );
  2502. addMethodChaining( 'not', not );
  2503. addMethodChaining( 'xor', xor );
  2504. addMethodChaining( 'bitAnd', bitAnd );
  2505. addMethodChaining( 'bitNot', bitNot );
  2506. addMethodChaining( 'bitOr', bitOr );
  2507. addMethodChaining( 'bitXor', bitXor );
  2508. addMethodChaining( 'shiftLeft', shiftLeft );
  2509. addMethodChaining( 'shiftRight', shiftRight );
  2510. const remainder = ( ...params ) => { // @deprecated, r168
  2511. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  2512. return modInt( ...params );
  2513. };
  2514. addMethodChaining( 'remainder', remainder );
  2515. class MathNode extends TempNode {
  2516. static get type() {
  2517. return 'MathNode';
  2518. }
  2519. constructor( method, aNode, bNode = null, cNode = null ) {
  2520. super();
  2521. this.method = method;
  2522. this.aNode = aNode;
  2523. this.bNode = bNode;
  2524. this.cNode = cNode;
  2525. }
  2526. getInputType( builder ) {
  2527. const aType = this.aNode.getNodeType( builder );
  2528. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  2529. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  2530. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  2531. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  2532. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  2533. if ( aLen > bLen && aLen > cLen ) {
  2534. return aType;
  2535. } else if ( bLen > cLen ) {
  2536. return bType;
  2537. } else if ( cLen > aLen ) {
  2538. return cType;
  2539. }
  2540. return aType;
  2541. }
  2542. getNodeType( builder ) {
  2543. const method = this.method;
  2544. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  2545. return 'float';
  2546. } else if ( method === MathNode.CROSS ) {
  2547. return 'vec3';
  2548. } else if ( method === MathNode.ALL ) {
  2549. return 'bool';
  2550. } else if ( method === MathNode.EQUALS ) {
  2551. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  2552. } else if ( method === MathNode.MOD ) {
  2553. return this.aNode.getNodeType( builder );
  2554. } else {
  2555. return this.getInputType( builder );
  2556. }
  2557. }
  2558. generate( builder, output ) {
  2559. const method = this.method;
  2560. const type = this.getNodeType( builder );
  2561. const inputType = this.getInputType( builder );
  2562. const a = this.aNode;
  2563. const b = this.bNode;
  2564. const c = this.cNode;
  2565. const isWebGL = builder.renderer.isWebGLRenderer === true;
  2566. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  2567. // dir can be either a direction vector or a normal vector
  2568. // upper-left 3x3 of matrix is assumed to be orthogonal
  2569. let tA = a;
  2570. let tB = b;
  2571. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  2572. tB = vec4( vec3( tB ), 0.0 );
  2573. } else {
  2574. tA = vec4( vec3( tA ), 0.0 );
  2575. }
  2576. const mulNode = mul( tA, tB ).xyz;
  2577. return normalize( mulNode ).build( builder, output );
  2578. } else if ( method === MathNode.NEGATE ) {
  2579. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  2580. } else if ( method === MathNode.ONE_MINUS ) {
  2581. return sub( 1.0, a ).build( builder, output );
  2582. } else if ( method === MathNode.RECIPROCAL ) {
  2583. return div( 1.0, a ).build( builder, output );
  2584. } else if ( method === MathNode.DIFFERENCE ) {
  2585. return abs( sub( a, b ) ).build( builder, output );
  2586. } else {
  2587. const params = [];
  2588. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  2589. params.push(
  2590. a.build( builder, type ),
  2591. b.build( builder, type )
  2592. );
  2593. } else if ( isWebGL && method === MathNode.STEP ) {
  2594. params.push(
  2595. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  2596. b.build( builder, inputType )
  2597. );
  2598. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  2599. params.push(
  2600. a.build( builder, inputType ),
  2601. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2602. );
  2603. } else if ( method === MathNode.REFRACT ) {
  2604. params.push(
  2605. a.build( builder, inputType ),
  2606. b.build( builder, inputType ),
  2607. c.build( builder, 'float' )
  2608. );
  2609. } else if ( method === MathNode.MIX ) {
  2610. params.push(
  2611. a.build( builder, inputType ),
  2612. b.build( builder, inputType ),
  2613. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2614. );
  2615. } else {
  2616. params.push( a.build( builder, inputType ) );
  2617. if ( b !== null ) params.push( b.build( builder, inputType ) );
  2618. if ( c !== null ) params.push( c.build( builder, inputType ) );
  2619. }
  2620. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  2621. }
  2622. }
  2623. serialize( data ) {
  2624. super.serialize( data );
  2625. data.method = this.method;
  2626. }
  2627. deserialize( data ) {
  2628. super.deserialize( data );
  2629. this.method = data.method;
  2630. }
  2631. }
  2632. // 1 input
  2633. MathNode.ALL = 'all';
  2634. MathNode.ANY = 'any';
  2635. MathNode.EQUALS = 'equals';
  2636. MathNode.RADIANS = 'radians';
  2637. MathNode.DEGREES = 'degrees';
  2638. MathNode.EXP = 'exp';
  2639. MathNode.EXP2 = 'exp2';
  2640. MathNode.LOG = 'log';
  2641. MathNode.LOG2 = 'log2';
  2642. MathNode.SQRT = 'sqrt';
  2643. MathNode.INVERSE_SQRT = 'inversesqrt';
  2644. MathNode.FLOOR = 'floor';
  2645. MathNode.CEIL = 'ceil';
  2646. MathNode.NORMALIZE = 'normalize';
  2647. MathNode.FRACT = 'fract';
  2648. MathNode.SIN = 'sin';
  2649. MathNode.COS = 'cos';
  2650. MathNode.TAN = 'tan';
  2651. MathNode.ASIN = 'asin';
  2652. MathNode.ACOS = 'acos';
  2653. MathNode.ATAN = 'atan';
  2654. MathNode.ABS = 'abs';
  2655. MathNode.SIGN = 'sign';
  2656. MathNode.LENGTH = 'length';
  2657. MathNode.NEGATE = 'negate';
  2658. MathNode.ONE_MINUS = 'oneMinus';
  2659. MathNode.DFDX = 'dFdx';
  2660. MathNode.DFDY = 'dFdy';
  2661. MathNode.ROUND = 'round';
  2662. MathNode.RECIPROCAL = 'reciprocal';
  2663. MathNode.TRUNC = 'trunc';
  2664. MathNode.FWIDTH = 'fwidth';
  2665. MathNode.BITCAST = 'bitcast';
  2666. MathNode.TRANSPOSE = 'transpose';
  2667. // 2 inputs
  2668. MathNode.ATAN2 = 'atan2';
  2669. MathNode.MIN = 'min';
  2670. MathNode.MAX = 'max';
  2671. MathNode.MOD = 'mod';
  2672. MathNode.STEP = 'step';
  2673. MathNode.REFLECT = 'reflect';
  2674. MathNode.DISTANCE = 'distance';
  2675. MathNode.DIFFERENCE = 'difference';
  2676. MathNode.DOT = 'dot';
  2677. MathNode.CROSS = 'cross';
  2678. MathNode.POW = 'pow';
  2679. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  2680. // 3 inputs
  2681. MathNode.MIX = 'mix';
  2682. MathNode.CLAMP = 'clamp';
  2683. MathNode.REFRACT = 'refract';
  2684. MathNode.SMOOTHSTEP = 'smoothstep';
  2685. MathNode.FACEFORWARD = 'faceforward';
  2686. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  2687. const INFINITY = /*@__PURE__*/ float( 1e6 );
  2688. const PI = /*@__PURE__*/ float( Math.PI );
  2689. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  2690. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  2691. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  2692. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  2693. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  2694. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  2695. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  2696. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2697. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2698. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2699. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2700. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2701. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2702. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2703. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2704. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2705. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2706. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2707. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2708. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2709. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2710. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2711. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2712. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2713. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2714. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2715. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2716. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2717. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2718. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2719. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2720. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2721. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2722. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2723. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2724. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  2725. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  2726. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  2727. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  2728. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  2729. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  2730. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  2731. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  2732. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  2733. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  2734. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  2735. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  2736. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  2737. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  2738. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  2739. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  2740. const lengthSq = ( a ) => dot( a, a );
  2741. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  2742. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  2743. const saturate = ( value ) => clamp( value );
  2744. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  2745. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  2746. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  2747. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  2748. const a = 12.9898, b = 78.233, c = 43758.5453;
  2749. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  2750. return fract( sin( sn ).mul( c ) );
  2751. } );
  2752. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  2753. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  2754. addMethodChaining( 'all', all );
  2755. addMethodChaining( 'any', any );
  2756. addMethodChaining( 'equals', equals );
  2757. addMethodChaining( 'radians', radians );
  2758. addMethodChaining( 'degrees', degrees );
  2759. addMethodChaining( 'exp', exp );
  2760. addMethodChaining( 'exp2', exp2 );
  2761. addMethodChaining( 'log', log );
  2762. addMethodChaining( 'log2', log2 );
  2763. addMethodChaining( 'sqrt', sqrt );
  2764. addMethodChaining( 'inverseSqrt', inverseSqrt );
  2765. addMethodChaining( 'floor', floor );
  2766. addMethodChaining( 'ceil', ceil );
  2767. addMethodChaining( 'normalize', normalize );
  2768. addMethodChaining( 'fract', fract );
  2769. addMethodChaining( 'sin', sin );
  2770. addMethodChaining( 'cos', cos );
  2771. addMethodChaining( 'tan', tan );
  2772. addMethodChaining( 'asin', asin );
  2773. addMethodChaining( 'acos', acos );
  2774. addMethodChaining( 'atan', atan );
  2775. addMethodChaining( 'abs', abs );
  2776. addMethodChaining( 'sign', sign );
  2777. addMethodChaining( 'length', length );
  2778. addMethodChaining( 'lengthSq', lengthSq );
  2779. addMethodChaining( 'negate', negate );
  2780. addMethodChaining( 'oneMinus', oneMinus );
  2781. addMethodChaining( 'dFdx', dFdx );
  2782. addMethodChaining( 'dFdy', dFdy );
  2783. addMethodChaining( 'round', round );
  2784. addMethodChaining( 'reciprocal', reciprocal );
  2785. addMethodChaining( 'trunc', trunc );
  2786. addMethodChaining( 'fwidth', fwidth );
  2787. addMethodChaining( 'atan2', atan2 );
  2788. addMethodChaining( 'min', min$1 );
  2789. addMethodChaining( 'max', max$1 );
  2790. addMethodChaining( 'mod', mod );
  2791. addMethodChaining( 'step', step );
  2792. addMethodChaining( 'reflect', reflect );
  2793. addMethodChaining( 'distance', distance );
  2794. addMethodChaining( 'dot', dot );
  2795. addMethodChaining( 'cross', cross );
  2796. addMethodChaining( 'pow', pow );
  2797. addMethodChaining( 'pow2', pow2 );
  2798. addMethodChaining( 'pow3', pow3 );
  2799. addMethodChaining( 'pow4', pow4 );
  2800. addMethodChaining( 'transformDirection', transformDirection );
  2801. addMethodChaining( 'mix', mixElement );
  2802. addMethodChaining( 'clamp', clamp );
  2803. addMethodChaining( 'refract', refract );
  2804. addMethodChaining( 'smoothstep', smoothstepElement );
  2805. addMethodChaining( 'faceForward', faceForward );
  2806. addMethodChaining( 'difference', difference );
  2807. addMethodChaining( 'saturate', saturate );
  2808. addMethodChaining( 'cbrt', cbrt );
  2809. addMethodChaining( 'transpose', transpose );
  2810. addMethodChaining( 'rand', rand );
  2811. class ConditionalNode extends Node {
  2812. static get type() {
  2813. return 'ConditionalNode';
  2814. }
  2815. constructor( condNode, ifNode, elseNode = null ) {
  2816. super();
  2817. this.condNode = condNode;
  2818. this.ifNode = ifNode;
  2819. this.elseNode = elseNode;
  2820. }
  2821. getNodeType( builder ) {
  2822. const ifType = this.ifNode.getNodeType( builder );
  2823. if ( this.elseNode !== null ) {
  2824. const elseType = this.elseNode.getNodeType( builder );
  2825. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  2826. return elseType;
  2827. }
  2828. }
  2829. return ifType;
  2830. }
  2831. setup( builder ) {
  2832. const condNode = this.condNode.cache();
  2833. const ifNode = this.ifNode.cache();
  2834. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  2835. //
  2836. const currentNodeBlock = builder.context.nodeBlock;
  2837. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  2838. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  2839. //
  2840. const properties = builder.getNodeProperties( this );
  2841. properties.condNode = condNode;
  2842. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  2843. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  2844. }
  2845. generate( builder, output ) {
  2846. const type = this.getNodeType( builder );
  2847. const nodeData = builder.getDataFromNode( this );
  2848. if ( nodeData.nodeProperty !== undefined ) {
  2849. return nodeData.nodeProperty;
  2850. }
  2851. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  2852. const needsOutput = output !== 'void';
  2853. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  2854. nodeData.nodeProperty = nodeProperty;
  2855. const nodeSnippet = condNode.build( builder, 'bool' );
  2856. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  2857. let ifSnippet = ifNode.build( builder, type );
  2858. if ( ifSnippet ) {
  2859. if ( needsOutput ) {
  2860. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  2861. } else {
  2862. ifSnippet = 'return ' + ifSnippet + ';';
  2863. }
  2864. }
  2865. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  2866. if ( elseNode !== null ) {
  2867. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  2868. let elseSnippet = elseNode.build( builder, type );
  2869. if ( elseSnippet ) {
  2870. if ( needsOutput ) {
  2871. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  2872. } else {
  2873. elseSnippet = 'return ' + elseSnippet + ';';
  2874. }
  2875. }
  2876. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  2877. } else {
  2878. builder.addFlowCode( '\n\n' );
  2879. }
  2880. return builder.format( nodeProperty, type, output );
  2881. }
  2882. }
  2883. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  2884. addMethodChaining( 'select', select );
  2885. //
  2886. const cond = ( ...params ) => { // @deprecated, r168
  2887. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  2888. return select( ...params );
  2889. };
  2890. addMethodChaining( 'cond', cond );
  2891. /**
  2892. * This node can be used as a context management component for another node.
  2893. * {@link NodeBuilder} performs its node building process in a specific context and
  2894. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  2895. *
  2896. * ```js
  2897. *node.context( { getUV: () => customCoord } );
  2898. *```
  2899. * @augments Node
  2900. */
  2901. class ContextNode extends Node {
  2902. static get type() {
  2903. return 'ContextNode';
  2904. }
  2905. /**
  2906. * Constructs a new context node.
  2907. *
  2908. * @param {Node} node - The node whose context should be modified.
  2909. * @param {Object} [value={}] - The modified context data.
  2910. */
  2911. constructor( node, value = {} ) {
  2912. super();
  2913. /**
  2914. * This flag can be used for type testing.
  2915. *
  2916. * @type {Boolean}
  2917. * @readonly
  2918. * @default true
  2919. */
  2920. this.isContextNode = true;
  2921. /**
  2922. * The node whose context should be modified.
  2923. *
  2924. * @type {Node}
  2925. */
  2926. this.node = node;
  2927. /**
  2928. * The modified context data.
  2929. *
  2930. * @type {Object}
  2931. * @default {}
  2932. */
  2933. this.value = value;
  2934. }
  2935. /**
  2936. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  2937. *
  2938. * @return {Node} A reference to {@link ContextNode#node}.
  2939. */
  2940. getScope() {
  2941. return this.node.getScope();
  2942. }
  2943. /**
  2944. * This method is overwritten to ensure it returns the type to {@link ContextNode#node}.
  2945. *
  2946. * @param {NodeBuilder} builder - The current node builder.
  2947. * @return {String} The type of {@link ContextNode#node}.
  2948. */
  2949. getNodeType( builder ) {
  2950. return this.node.getNodeType( builder );
  2951. }
  2952. analyze( builder ) {
  2953. this.node.build( builder );
  2954. }
  2955. setup( builder ) {
  2956. const previousContext = builder.getContext();
  2957. builder.setContext( { ...builder.context, ...this.value } );
  2958. const node = this.node.build( builder );
  2959. builder.setContext( previousContext );
  2960. return node;
  2961. }
  2962. generate( builder, output ) {
  2963. const previousContext = builder.getContext();
  2964. builder.setContext( { ...builder.context, ...this.value } );
  2965. const snippet = this.node.build( builder, output );
  2966. builder.setContext( previousContext );
  2967. return snippet;
  2968. }
  2969. }
  2970. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  2971. const label = ( node, name ) => context( node, { label: name } );
  2972. addMethodChaining( 'context', context );
  2973. addMethodChaining( 'label', label );
  2974. /**
  2975. * Class for representing shader variables as nodes. Variables are create from
  2976. * existing nodes like the following:
  2977. *
  2978. * ```js
  2979. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  2980. * ```
  2981. *
  2982. * @augments Node
  2983. */
  2984. class VarNode extends Node {
  2985. static get type() {
  2986. return 'VarNode';
  2987. }
  2988. /**
  2989. * Constructs a new variable node.
  2990. *
  2991. * @param {Node} node - The node for which a variable should be created.
  2992. * @param {String?} name - The name of the variable in the shader.
  2993. */
  2994. constructor( node, name = null ) {
  2995. super();
  2996. /**
  2997. * The node for which a variable should be created.
  2998. *
  2999. * @type {Node}
  3000. */
  3001. this.node = node;
  3002. /**
  3003. * The name of the variable in the shader. If no name is defined,
  3004. * the node system auto-generates one.
  3005. *
  3006. * @type {String?}
  3007. * @default null
  3008. */
  3009. this.name = name;
  3010. /**
  3011. * `VarNonde` sets this property to `true` by default.
  3012. *
  3013. * @type {Boolean}
  3014. * @default true
  3015. */
  3016. this.global = true;
  3017. /**
  3018. * This flag can be used for type testing.
  3019. *
  3020. * @type {Boolean}
  3021. * @readonly
  3022. * @default true
  3023. */
  3024. this.isVarNode = true;
  3025. }
  3026. getHash( builder ) {
  3027. return this.name || super.getHash( builder );
  3028. }
  3029. getNodeType( builder ) {
  3030. return this.node.getNodeType( builder );
  3031. }
  3032. generate( builder ) {
  3033. const { node, name } = this;
  3034. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  3035. const propertyName = builder.getPropertyName( nodeVar );
  3036. const snippet = node.build( builder, nodeVar.type );
  3037. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3038. return propertyName;
  3039. }
  3040. }
  3041. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  3042. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  3043. // Deprecated
  3044. const temp = ( node ) => { // @deprecated, r170
  3045. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  3046. return createVar( node );
  3047. };
  3048. addMethodChaining( 'temp', temp );
  3049. /**
  3050. * Class for representing shader varyings as nodes. Varyings are create from
  3051. * existing nodes like the following:
  3052. *
  3053. * ```js
  3054. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  3055. * ```
  3056. *
  3057. * @augments Node
  3058. */
  3059. class VaryingNode extends Node {
  3060. static get type() {
  3061. return 'VaryingNode';
  3062. }
  3063. /**
  3064. * Constructs a new varying node.
  3065. *
  3066. * @param {Node} node - The node for which a varying should be created.
  3067. * @param {String?} name - The name of the varying in the shader.
  3068. */
  3069. constructor( node, name = null ) {
  3070. super();
  3071. /**
  3072. * The node for which a varying should be created.
  3073. *
  3074. * @type {Node}
  3075. */
  3076. this.node = node;
  3077. /**
  3078. * The name of the varying in the shader. If no name is defined,
  3079. * the node system auto-generates one.
  3080. *
  3081. * @type {String?}
  3082. * @default null
  3083. */
  3084. this.name = name;
  3085. /**
  3086. * This flag can be used for type testing.
  3087. *
  3088. * @type {Boolean}
  3089. * @readonly
  3090. * @default true
  3091. */
  3092. this.isVaryingNode = true;
  3093. }
  3094. /**
  3095. * The method is overwritten so it always returns `true`.
  3096. *
  3097. * @return {Boolean} Whether this node is global or not.
  3098. */
  3099. isGlobal() {
  3100. return true;
  3101. }
  3102. getHash( builder ) {
  3103. return this.name || super.getHash( builder );
  3104. }
  3105. getNodeType( builder ) {
  3106. // VaryingNode is auto type
  3107. return this.node.getNodeType( builder );
  3108. }
  3109. /**
  3110. * This method performs the setup of a varying node with the current node builder.
  3111. *
  3112. * @param {NodeBuilder} builder - The current node builder.
  3113. * @return {NodeVarying} The node varying from the node builder.
  3114. */
  3115. setupVarying( builder ) {
  3116. const properties = builder.getNodeProperties( this );
  3117. let varying = properties.varying;
  3118. if ( varying === undefined ) {
  3119. const name = this.name;
  3120. const type = this.getNodeType( builder );
  3121. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  3122. properties.node = this.node;
  3123. }
  3124. // this property can be used to check if the varying can be optimized for a variable
  3125. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  3126. return varying;
  3127. }
  3128. setup( builder ) {
  3129. this.setupVarying( builder );
  3130. }
  3131. analyze( builder ) {
  3132. this.setupVarying( builder );
  3133. return this.node.analyze( builder );
  3134. }
  3135. generate( builder ) {
  3136. const properties = builder.getNodeProperties( this );
  3137. const varying = this.setupVarying( builder );
  3138. if ( properties.propertyName === undefined ) {
  3139. const type = this.getNodeType( builder );
  3140. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  3141. // force node run in vertex stage
  3142. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  3143. properties.propertyName = propertyName;
  3144. }
  3145. return builder.getPropertyName( varying );
  3146. }
  3147. }
  3148. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  3149. addMethodChaining( 'varying', varying );
  3150. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3151. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  3152. const b = color.mul( 0.0773993808 );
  3153. const factor = color.lessThanEqual( 0.04045 );
  3154. const rgbResult = mix( a, b, factor );
  3155. return rgbResult;
  3156. } ).setLayout( {
  3157. name: 'sRGBTransferEOTF',
  3158. type: 'vec3',
  3159. inputs: [
  3160. { name: 'color', type: 'vec3' }
  3161. ]
  3162. } );
  3163. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3164. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  3165. const b = color.mul( 12.92 );
  3166. const factor = color.lessThanEqual( 0.0031308 );
  3167. const rgbResult = mix( a, b, factor );
  3168. return rgbResult;
  3169. } ).setLayout( {
  3170. name: 'sRGBTransferOETF',
  3171. type: 'vec3',
  3172. inputs: [
  3173. { name: 'color', type: 'vec3' }
  3174. ]
  3175. } );
  3176. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  3177. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  3178. class ColorSpaceNode extends TempNode {
  3179. static get type() {
  3180. return 'ColorSpaceNode';
  3181. }
  3182. constructor( colorNode, source, target ) {
  3183. super( 'vec4' );
  3184. this.colorNode = colorNode;
  3185. this.source = source;
  3186. this.target = target;
  3187. }
  3188. resolveColorSpace( builder, colorSpace ) {
  3189. if ( colorSpace === WORKING_COLOR_SPACE ) {
  3190. return ColorManagement.workingColorSpace;
  3191. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  3192. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  3193. }
  3194. return colorSpace;
  3195. }
  3196. setup( builder ) {
  3197. const { colorNode } = this;
  3198. const source = this.resolveColorSpace( builder, this.source );
  3199. const target = this.resolveColorSpace( builder, this.target );
  3200. let outputNode = colorNode;
  3201. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  3202. return outputNode;
  3203. }
  3204. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  3205. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  3206. }
  3207. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  3208. outputNode = vec4(
  3209. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  3210. outputNode.a
  3211. );
  3212. }
  3213. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  3214. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  3215. }
  3216. return outputNode;
  3217. }
  3218. }
  3219. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  3220. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  3221. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  3222. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  3223. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  3224. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  3225. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  3226. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  3227. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  3228. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  3229. static get type() {
  3230. return 'ReferenceElementNode';
  3231. }
  3232. constructor( referenceNode, indexNode ) {
  3233. super( referenceNode, indexNode );
  3234. this.referenceNode = referenceNode;
  3235. this.isReferenceElementNode = true;
  3236. }
  3237. getNodeType() {
  3238. return this.referenceNode.uniformType;
  3239. }
  3240. generate( builder ) {
  3241. const snippet = super.generate( builder );
  3242. const arrayType = this.referenceNode.getNodeType();
  3243. const elementType = this.getNodeType();
  3244. return builder.format( snippet, arrayType, elementType );
  3245. }
  3246. };
  3247. class ReferenceBaseNode extends Node {
  3248. static get type() {
  3249. return 'ReferenceBaseNode';
  3250. }
  3251. constructor( property, uniformType, object = null, count = null ) {
  3252. super();
  3253. this.property = property;
  3254. this.uniformType = uniformType;
  3255. this.object = object;
  3256. this.count = count;
  3257. this.properties = property.split( '.' );
  3258. this.reference = object;
  3259. this.node = null;
  3260. this.group = null;
  3261. this.updateType = NodeUpdateType.OBJECT;
  3262. }
  3263. setGroup( group ) {
  3264. this.group = group;
  3265. return this;
  3266. }
  3267. element( indexNode ) {
  3268. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  3269. }
  3270. setNodeType( uniformType ) {
  3271. const node = uniform( null, uniformType ).getSelf();
  3272. if ( this.group !== null ) {
  3273. node.setGroup( this.group );
  3274. }
  3275. this.node = node;
  3276. }
  3277. getNodeType( builder ) {
  3278. if ( this.node === null ) {
  3279. this.updateReference( builder );
  3280. this.updateValue();
  3281. }
  3282. return this.node.getNodeType( builder );
  3283. }
  3284. getValueFromReference( object = this.reference ) {
  3285. const { properties } = this;
  3286. let value = object[ properties[ 0 ] ];
  3287. for ( let i = 1; i < properties.length; i ++ ) {
  3288. value = value[ properties[ i ] ];
  3289. }
  3290. return value;
  3291. }
  3292. updateReference( state ) {
  3293. this.reference = this.object !== null ? this.object : state.object;
  3294. return this.reference;
  3295. }
  3296. setup() {
  3297. this.updateValue();
  3298. return this.node;
  3299. }
  3300. update( /*frame*/ ) {
  3301. this.updateValue();
  3302. }
  3303. updateValue() {
  3304. if ( this.node === null ) this.setNodeType( this.uniformType );
  3305. const value = this.getValueFromReference();
  3306. if ( Array.isArray( value ) ) {
  3307. this.node.array = value;
  3308. } else {
  3309. this.node.value = value;
  3310. }
  3311. }
  3312. }
  3313. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  3314. class RendererReferenceNode extends ReferenceBaseNode {
  3315. static get type() {
  3316. return 'RendererReferenceNode';
  3317. }
  3318. constructor( property, inputType, renderer = null ) {
  3319. super( property, inputType, renderer );
  3320. this.renderer = renderer;
  3321. this.setGroup( renderGroup );
  3322. }
  3323. updateReference( state ) {
  3324. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  3325. return this.reference;
  3326. }
  3327. }
  3328. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  3329. class ToneMappingNode extends TempNode {
  3330. static get type() {
  3331. return 'ToneMappingNode';
  3332. }
  3333. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  3334. super( 'vec3' );
  3335. this.toneMapping = toneMapping;
  3336. this.exposureNode = exposureNode;
  3337. this.colorNode = colorNode;
  3338. }
  3339. getCacheKey() {
  3340. return hash$1( super.getCacheKey(), this.toneMapping );
  3341. }
  3342. setup( builder ) {
  3343. const colorNode = this.colorNode || builder.context.color;
  3344. const toneMapping = this.toneMapping;
  3345. if ( toneMapping === NoToneMapping ) return colorNode;
  3346. let outputNode = null;
  3347. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  3348. if ( toneMappingFn !== null ) {
  3349. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  3350. } else {
  3351. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  3352. outputNode = colorNode;
  3353. }
  3354. return outputNode;
  3355. }
  3356. }
  3357. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  3358. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  3359. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  3360. class BufferAttributeNode extends InputNode {
  3361. static get type() {
  3362. return 'BufferAttributeNode';
  3363. }
  3364. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  3365. super( value, bufferType );
  3366. this.isBufferNode = true;
  3367. this.bufferType = bufferType;
  3368. this.bufferStride = bufferStride;
  3369. this.bufferOffset = bufferOffset;
  3370. this.usage = StaticDrawUsage;
  3371. this.instanced = false;
  3372. this.attribute = null;
  3373. this.global = true;
  3374. if ( value && value.isBufferAttribute === true ) {
  3375. this.attribute = value;
  3376. this.usage = value.usage;
  3377. this.instanced = value.isInstancedBufferAttribute;
  3378. }
  3379. }
  3380. getHash( builder ) {
  3381. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  3382. let bufferData = builder.globalCache.getData( this.value );
  3383. if ( bufferData === undefined ) {
  3384. bufferData = {
  3385. node: this
  3386. };
  3387. builder.globalCache.setData( this.value, bufferData );
  3388. }
  3389. return bufferData.node.uuid;
  3390. }
  3391. return this.uuid;
  3392. }
  3393. getNodeType( builder ) {
  3394. if ( this.bufferType === null ) {
  3395. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  3396. }
  3397. return this.bufferType;
  3398. }
  3399. setup( builder ) {
  3400. if ( this.attribute !== null ) return;
  3401. const type = this.getNodeType( builder );
  3402. const array = this.value;
  3403. const itemSize = builder.getTypeLength( type );
  3404. const stride = this.bufferStride || itemSize;
  3405. const offset = this.bufferOffset;
  3406. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  3407. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  3408. buffer.setUsage( this.usage );
  3409. this.attribute = bufferAttribute;
  3410. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  3411. }
  3412. generate( builder ) {
  3413. const nodeType = this.getNodeType( builder );
  3414. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  3415. const propertyName = builder.getPropertyName( nodeAttribute );
  3416. let output = null;
  3417. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  3418. this.name = propertyName;
  3419. output = propertyName;
  3420. } else {
  3421. const nodeVarying = varying( this );
  3422. output = nodeVarying.build( builder, nodeType );
  3423. }
  3424. return output;
  3425. }
  3426. getInputType( /*builder*/ ) {
  3427. return 'bufferAttribute';
  3428. }
  3429. setUsage( value ) {
  3430. this.usage = value;
  3431. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  3432. this.attribute.usage = value;
  3433. }
  3434. return this;
  3435. }
  3436. setInstanced( value ) {
  3437. this.instanced = value;
  3438. return this;
  3439. }
  3440. }
  3441. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  3442. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  3443. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  3444. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  3445. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  3446. class ComputeNode extends Node {
  3447. static get type() {
  3448. return 'ComputeNode';
  3449. }
  3450. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  3451. super( 'void' );
  3452. this.isComputeNode = true;
  3453. this.computeNode = computeNode;
  3454. this.count = count;
  3455. this.workgroupSize = workgroupSize;
  3456. this.dispatchCount = 0;
  3457. this.version = 1;
  3458. this.updateBeforeType = NodeUpdateType.OBJECT;
  3459. this.onInitFunction = null;
  3460. this.updateDispatchCount();
  3461. }
  3462. dispose() {
  3463. this.dispatchEvent( { type: 'dispose' } );
  3464. }
  3465. set needsUpdate( value ) {
  3466. if ( value === true ) this.version ++;
  3467. }
  3468. updateDispatchCount() {
  3469. const { count, workgroupSize } = this;
  3470. let size = workgroupSize[ 0 ];
  3471. for ( let i = 1; i < workgroupSize.length; i ++ )
  3472. size *= workgroupSize[ i ];
  3473. this.dispatchCount = Math.ceil( count / size );
  3474. }
  3475. onInit( callback ) {
  3476. this.onInitFunction = callback;
  3477. return this;
  3478. }
  3479. updateBefore( { renderer } ) {
  3480. renderer.compute( this );
  3481. }
  3482. generate( builder ) {
  3483. const { shaderStage } = builder;
  3484. if ( shaderStage === 'compute' ) {
  3485. const snippet = this.computeNode.build( builder, 'void' );
  3486. if ( snippet !== '' ) {
  3487. builder.addLineFlowCode( snippet, this );
  3488. }
  3489. }
  3490. }
  3491. }
  3492. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  3493. addMethodChaining( 'compute', compute );
  3494. /**
  3495. * This node can be used as a cache management component for another node.
  3496. * Caching is in general used by default in {@link NodeBuilder} but this node
  3497. * allows the usage of a shared parent cache during the build process.
  3498. *
  3499. * @augments Node
  3500. */
  3501. class CacheNode extends Node {
  3502. static get type() {
  3503. return 'CacheNode';
  3504. }
  3505. /**
  3506. * Constructs a new cache node.
  3507. *
  3508. * @param {Node} node - The node that should be cached.
  3509. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  3510. */
  3511. constructor( node, parent = true ) {
  3512. super();
  3513. /**
  3514. * The node that should be cached.
  3515. *
  3516. * @type {Node}
  3517. */
  3518. this.node = node;
  3519. /**
  3520. * Whether this node refers to a shared parent cache or not.
  3521. *
  3522. * @type {Boolean}
  3523. * @default true
  3524. */
  3525. this.parent = parent;
  3526. /**
  3527. * This flag can be used for type testing.
  3528. *
  3529. * @type {Boolean}
  3530. * @readonly
  3531. * @default true
  3532. */
  3533. this.isCacheNode = true;
  3534. }
  3535. getNodeType( builder ) {
  3536. return this.node.getNodeType( builder );
  3537. }
  3538. build( builder, ...params ) {
  3539. const previousCache = builder.getCache();
  3540. const cache = builder.getCacheFromNode( this, this.parent );
  3541. builder.setCache( cache );
  3542. const data = this.node.build( builder, ...params );
  3543. builder.setCache( previousCache );
  3544. return data;
  3545. }
  3546. }
  3547. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  3548. addMethodChaining( 'cache', cache );
  3549. /**
  3550. * The class generates the code of a given node but returns another node in the output.
  3551. * This can be used to call a method or node that does not return a value, i.e.
  3552. * type `void` on an input where returning a value is required. Example:
  3553. *
  3554. * ```js
  3555. * material.colorNode = myColor.bypass( runVoidFn() )
  3556. *```
  3557. *
  3558. * @augments Node
  3559. */
  3560. class BypassNode extends Node {
  3561. static get type() {
  3562. return 'BypassNode';
  3563. }
  3564. /**
  3565. * Constructs a new bypass node.
  3566. *
  3567. * @param {Node} outputNode - The output node.
  3568. * @param {Node} callNode - The call node.
  3569. */
  3570. constructor( outputNode, callNode ) {
  3571. super();
  3572. /**
  3573. * This flag can be used for type testing.
  3574. *
  3575. * @type {Boolean}
  3576. * @readonly
  3577. * @default true
  3578. */
  3579. this.isBypassNode = true;
  3580. /**
  3581. * The output node.
  3582. *
  3583. * @type {Node}
  3584. */
  3585. this.outputNode = outputNode;
  3586. /**
  3587. * The call node.
  3588. *
  3589. * @type {Node}
  3590. */
  3591. this.callNode = callNode;
  3592. }
  3593. getNodeType( builder ) {
  3594. return this.outputNode.getNodeType( builder );
  3595. }
  3596. generate( builder ) {
  3597. const snippet = this.callNode.build( builder, 'void' );
  3598. if ( snippet !== '' ) {
  3599. builder.addLineFlowCode( snippet, this );
  3600. }
  3601. return this.outputNode.build( builder );
  3602. }
  3603. }
  3604. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  3605. addMethodChaining( 'bypass', bypass );
  3606. class RemapNode extends Node {
  3607. static get type() {
  3608. return 'RemapNode';
  3609. }
  3610. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  3611. super();
  3612. this.node = node;
  3613. this.inLowNode = inLowNode;
  3614. this.inHighNode = inHighNode;
  3615. this.outLowNode = outLowNode;
  3616. this.outHighNode = outHighNode;
  3617. this.doClamp = true;
  3618. }
  3619. setup() {
  3620. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  3621. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  3622. if ( doClamp === true ) t = t.clamp();
  3623. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  3624. }
  3625. }
  3626. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  3627. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  3628. addMethodChaining( 'remap', remap );
  3629. addMethodChaining( 'remapClamp', remapClamp );
  3630. /**
  3631. * This class can be used to implement basic expressions in shader code.
  3632. * Basic examples for that are `return`, `continue` or `discard` statements.
  3633. *
  3634. * @augments Node
  3635. */
  3636. class ExpressionNode extends Node {
  3637. static get type() {
  3638. return 'ExpressionNode';
  3639. }
  3640. /**
  3641. * Constructs a new expression node.
  3642. *
  3643. * @param {String} [snippet=''] - The native code snippet.
  3644. * @param {String} [includes='void'] - The node type.
  3645. */
  3646. constructor( snippet = '', nodeType = 'void' ) {
  3647. super( nodeType );
  3648. /**
  3649. * The native code snippet.
  3650. *
  3651. * @type {String}
  3652. * @default ''
  3653. */
  3654. this.snippet = snippet;
  3655. }
  3656. generate( builder, output ) {
  3657. const type = this.getNodeType( builder );
  3658. const snippet = this.snippet;
  3659. if ( type === 'void' ) {
  3660. builder.addLineFlowCode( snippet, this );
  3661. } else {
  3662. return builder.format( `( ${ snippet } )`, type, output );
  3663. }
  3664. }
  3665. }
  3666. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  3667. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  3668. const Return = () => expression( 'return' ).append();
  3669. addMethodChaining( 'discard', Discard );
  3670. class RenderOutputNode extends TempNode {
  3671. static get type() {
  3672. return 'RenderOutputNode';
  3673. }
  3674. constructor( colorNode, toneMapping, outputColorSpace ) {
  3675. super( 'vec4' );
  3676. this.colorNode = colorNode;
  3677. this.toneMapping = toneMapping;
  3678. this.outputColorSpace = outputColorSpace;
  3679. this.isRenderOutput = true;
  3680. }
  3681. setup( { context } ) {
  3682. let outputNode = this.colorNode || context.color;
  3683. // tone mapping
  3684. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  3685. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  3686. if ( toneMapping !== NoToneMapping ) {
  3687. outputNode = outputNode.toneMapping( toneMapping );
  3688. }
  3689. // working to output color space
  3690. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  3691. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  3692. }
  3693. return outputNode;
  3694. }
  3695. }
  3696. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  3697. addMethodChaining( 'renderOutput', renderOutput );
  3698. // Non-PURE exports list, side-effects are required here.
  3699. // TSL Base Syntax
  3700. function addNodeElement( name/*, nodeElement*/ ) {
  3701. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  3702. }
  3703. /**
  3704. * Base class for representing shader attributes as nodes.
  3705. *
  3706. * @augments Node
  3707. */
  3708. class AttributeNode extends Node {
  3709. static get type() {
  3710. return 'AttributeNode';
  3711. }
  3712. /**
  3713. * Constructs a new attribute node.
  3714. *
  3715. * @param {String} attributeName - The name of the attribute.
  3716. * @param {String?} nodeType - The node type.
  3717. */
  3718. constructor( attributeName, nodeType = null ) {
  3719. super( nodeType );
  3720. /**
  3721. * `AttributeNode` sets this property to `true` by default.
  3722. *
  3723. * @type {Boolean}
  3724. * @default true
  3725. */
  3726. this.global = true;
  3727. this._attributeName = attributeName;
  3728. }
  3729. getHash( builder ) {
  3730. return this.getAttributeName( builder );
  3731. }
  3732. getNodeType( builder ) {
  3733. let nodeType = this.nodeType;
  3734. if ( nodeType === null ) {
  3735. const attributeName = this.getAttributeName( builder );
  3736. if ( builder.hasGeometryAttribute( attributeName ) ) {
  3737. const attribute = builder.geometry.getAttribute( attributeName );
  3738. nodeType = builder.getTypeFromAttribute( attribute );
  3739. } else {
  3740. nodeType = 'float';
  3741. }
  3742. }
  3743. return nodeType;
  3744. }
  3745. /**
  3746. * Sets the attribute name to the given value. The method can be
  3747. * overwritten in derived classes if the final name must be computed
  3748. * analytically.
  3749. *
  3750. * @param {String} attributeName - The name of the attribute.
  3751. * @return {AttributeNode} A reference to this node.
  3752. */
  3753. setAttributeName( attributeName ) {
  3754. this._attributeName = attributeName;
  3755. return this;
  3756. }
  3757. /**
  3758. * Returns the attribute name of this node. The method can be
  3759. * overwritten in derived classes if the final name must be computed
  3760. * analytically.
  3761. *
  3762. * @param {NodeBuilder} builder - The current node builder.
  3763. * @return {String} The attribute name.
  3764. */
  3765. getAttributeName( /*builder*/ ) {
  3766. return this._attributeName;
  3767. }
  3768. generate( builder ) {
  3769. const attributeName = this.getAttributeName( builder );
  3770. const nodeType = this.getNodeType( builder );
  3771. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  3772. if ( geometryAttribute === true ) {
  3773. const attribute = builder.geometry.getAttribute( attributeName );
  3774. const attributeType = builder.getTypeFromAttribute( attribute );
  3775. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  3776. if ( builder.shaderStage === 'vertex' ) {
  3777. return builder.format( nodeAttribute.name, attributeType, nodeType );
  3778. } else {
  3779. const nodeVarying = varying( this );
  3780. return nodeVarying.build( builder, nodeType );
  3781. }
  3782. } else {
  3783. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  3784. return builder.generateConst( nodeType );
  3785. }
  3786. }
  3787. serialize( data ) {
  3788. super.serialize( data );
  3789. data.global = this.global;
  3790. data._attributeName = this._attributeName;
  3791. }
  3792. deserialize( data ) {
  3793. super.deserialize( data );
  3794. this.global = data.global;
  3795. this._attributeName = data._attributeName;
  3796. }
  3797. }
  3798. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  3799. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  3800. class TextureSizeNode extends Node {
  3801. static get type() {
  3802. return 'TextureSizeNode';
  3803. }
  3804. constructor( textureNode, levelNode = null ) {
  3805. super( 'uvec2' );
  3806. this.isTextureSizeNode = true;
  3807. this.textureNode = textureNode;
  3808. this.levelNode = levelNode;
  3809. }
  3810. generate( builder, output ) {
  3811. const textureProperty = this.textureNode.build( builder, 'property' );
  3812. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  3813. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  3814. }
  3815. }
  3816. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  3817. class MaxMipLevelNode extends UniformNode {
  3818. static get type() {
  3819. return 'MaxMipLevelNode';
  3820. }
  3821. constructor( textureNode ) {
  3822. super( 0 );
  3823. this._textureNode = textureNode;
  3824. this.updateType = NodeUpdateType.FRAME;
  3825. }
  3826. get textureNode() {
  3827. return this._textureNode;
  3828. }
  3829. get texture() {
  3830. return this._textureNode.value;
  3831. }
  3832. update() {
  3833. const texture = this.texture;
  3834. const images = texture.images;
  3835. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  3836. if ( image && image.width !== undefined ) {
  3837. const { width, height } = image;
  3838. this.value = Math.log2( Math.max( width, height ) );
  3839. }
  3840. }
  3841. }
  3842. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  3843. class TextureNode extends UniformNode {
  3844. static get type() {
  3845. return 'TextureNode';
  3846. }
  3847. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  3848. super( value );
  3849. this.isTextureNode = true;
  3850. this.uvNode = uvNode;
  3851. this.levelNode = levelNode;
  3852. this.biasNode = biasNode;
  3853. this.compareNode = null;
  3854. this.depthNode = null;
  3855. this.gradNode = null;
  3856. this.sampler = true;
  3857. this.updateMatrix = false;
  3858. this.updateType = NodeUpdateType.NONE;
  3859. this.referenceNode = null;
  3860. this._value = value;
  3861. this._matrixUniform = null;
  3862. this.setUpdateMatrix( uvNode === null );
  3863. }
  3864. set value( value ) {
  3865. if ( this.referenceNode ) {
  3866. this.referenceNode.value = value;
  3867. } else {
  3868. this._value = value;
  3869. }
  3870. }
  3871. get value() {
  3872. return this.referenceNode ? this.referenceNode.value : this._value;
  3873. }
  3874. getUniformHash( /*builder*/ ) {
  3875. return this.value.uuid;
  3876. }
  3877. getNodeType( /*builder*/ ) {
  3878. if ( this.value.isDepthTexture === true ) return 'float';
  3879. if ( this.value.type === UnsignedIntType ) {
  3880. return 'uvec4';
  3881. } else if ( this.value.type === IntType ) {
  3882. return 'ivec4';
  3883. }
  3884. return 'vec4';
  3885. }
  3886. getInputType( /*builder*/ ) {
  3887. return 'texture';
  3888. }
  3889. getDefaultUV() {
  3890. return uv( this.value.channel );
  3891. }
  3892. updateReference( /*state*/ ) {
  3893. return this.value;
  3894. }
  3895. getTransformedUV( uvNode ) {
  3896. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  3897. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  3898. }
  3899. setUpdateMatrix( value ) {
  3900. this.updateMatrix = value;
  3901. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  3902. return this;
  3903. }
  3904. setupUV( builder, uvNode ) {
  3905. const texture = this.value;
  3906. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  3907. if ( this.sampler ) {
  3908. uvNode = uvNode.flipY();
  3909. } else {
  3910. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  3911. }
  3912. }
  3913. return uvNode;
  3914. }
  3915. setup( builder ) {
  3916. const properties = builder.getNodeProperties( this );
  3917. properties.referenceNode = this.referenceNode;
  3918. //
  3919. let uvNode = this.uvNode;
  3920. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  3921. uvNode = builder.context.getUV( this );
  3922. }
  3923. if ( ! uvNode ) uvNode = this.getDefaultUV();
  3924. if ( this.updateMatrix === true ) {
  3925. uvNode = this.getTransformedUV( uvNode );
  3926. }
  3927. uvNode = this.setupUV( builder, uvNode );
  3928. //
  3929. let levelNode = this.levelNode;
  3930. if ( levelNode === null && builder.context.getTextureLevel ) {
  3931. levelNode = builder.context.getTextureLevel( this );
  3932. }
  3933. //
  3934. properties.uvNode = uvNode;
  3935. properties.levelNode = levelNode;
  3936. properties.biasNode = this.biasNode;
  3937. properties.compareNode = this.compareNode;
  3938. properties.gradNode = this.gradNode;
  3939. properties.depthNode = this.depthNode;
  3940. }
  3941. generateUV( builder, uvNode ) {
  3942. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  3943. }
  3944. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  3945. const texture = this.value;
  3946. let snippet;
  3947. if ( levelSnippet ) {
  3948. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  3949. } else if ( biasSnippet ) {
  3950. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  3951. } else if ( gradSnippet ) {
  3952. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  3953. } else if ( compareSnippet ) {
  3954. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  3955. } else if ( this.sampler === false ) {
  3956. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  3957. } else {
  3958. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  3959. }
  3960. return snippet;
  3961. }
  3962. generate( builder, output ) {
  3963. const properties = builder.getNodeProperties( this );
  3964. const texture = this.value;
  3965. if ( ! texture || texture.isTexture !== true ) {
  3966. throw new Error( 'TextureNode: Need a three.js texture.' );
  3967. }
  3968. const textureProperty = super.generate( builder, 'property' );
  3969. if ( output === 'sampler' ) {
  3970. return textureProperty + '_sampler';
  3971. } else if ( builder.isReference( output ) ) {
  3972. return textureProperty;
  3973. } else {
  3974. const nodeData = builder.getDataFromNode( this );
  3975. let propertyName = nodeData.propertyName;
  3976. if ( propertyName === undefined ) {
  3977. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  3978. const uvSnippet = this.generateUV( builder, uvNode );
  3979. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  3980. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  3981. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  3982. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  3983. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  3984. const nodeVar = builder.getVarFromNode( this );
  3985. propertyName = builder.getPropertyName( nodeVar );
  3986. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  3987. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3988. nodeData.snippet = snippet;
  3989. nodeData.propertyName = propertyName;
  3990. }
  3991. let snippet = propertyName;
  3992. const nodeType = this.getNodeType( builder );
  3993. if ( builder.needsToWorkingColorSpace( texture ) ) {
  3994. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  3995. }
  3996. return builder.format( snippet, nodeType, output );
  3997. }
  3998. }
  3999. setSampler( value ) {
  4000. this.sampler = value;
  4001. return this;
  4002. }
  4003. getSampler() {
  4004. return this.sampler;
  4005. }
  4006. // @TODO: Move to TSL
  4007. uv( uvNode ) {
  4008. const textureNode = this.clone();
  4009. textureNode.uvNode = nodeObject( uvNode );
  4010. textureNode.referenceNode = this.getSelf();
  4011. return nodeObject( textureNode );
  4012. }
  4013. blur( amountNode ) {
  4014. const textureNode = this.clone();
  4015. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  4016. textureNode.referenceNode = this.getSelf();
  4017. return nodeObject( textureNode );
  4018. }
  4019. level( levelNode ) {
  4020. const textureNode = this.clone();
  4021. textureNode.levelNode = nodeObject( levelNode );
  4022. textureNode.referenceNode = this.getSelf();
  4023. return nodeObject( textureNode );
  4024. }
  4025. size( levelNode ) {
  4026. return textureSize( this, levelNode );
  4027. }
  4028. bias( biasNode ) {
  4029. const textureNode = this.clone();
  4030. textureNode.biasNode = nodeObject( biasNode );
  4031. textureNode.referenceNode = this.getSelf();
  4032. return nodeObject( textureNode );
  4033. }
  4034. compare( compareNode ) {
  4035. const textureNode = this.clone();
  4036. textureNode.compareNode = nodeObject( compareNode );
  4037. textureNode.referenceNode = this.getSelf();
  4038. return nodeObject( textureNode );
  4039. }
  4040. grad( gradNodeX, gradNodeY ) {
  4041. const textureNode = this.clone();
  4042. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  4043. textureNode.referenceNode = this.getSelf();
  4044. return nodeObject( textureNode );
  4045. }
  4046. depth( depthNode ) {
  4047. const textureNode = this.clone();
  4048. textureNode.depthNode = nodeObject( depthNode );
  4049. textureNode.referenceNode = this.getSelf();
  4050. return nodeObject( textureNode );
  4051. }
  4052. // --
  4053. serialize( data ) {
  4054. super.serialize( data );
  4055. data.value = this.value.toJSON( data.meta ).uuid;
  4056. data.sampler = this.sampler;
  4057. data.updateMatrix = this.updateMatrix;
  4058. data.updateType = this.updateType;
  4059. }
  4060. deserialize( data ) {
  4061. super.deserialize( data );
  4062. this.value = data.meta.textures[ data.value ];
  4063. this.sampler = data.sampler;
  4064. this.updateMatrix = data.updateMatrix;
  4065. this.updateType = data.updateType;
  4066. }
  4067. update() {
  4068. const texture = this.value;
  4069. const matrixUniform = this._matrixUniform;
  4070. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  4071. if ( texture.matrixAutoUpdate === true ) {
  4072. texture.updateMatrix();
  4073. }
  4074. }
  4075. clone() {
  4076. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  4077. newNode.sampler = this.sampler;
  4078. return newNode;
  4079. }
  4080. }
  4081. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  4082. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  4083. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  4084. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  4085. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  4086. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  4087. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  4088. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  4089. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  4090. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  4091. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  4092. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  4093. class Object3DNode extends Node {
  4094. static get type() {
  4095. return 'Object3DNode';
  4096. }
  4097. constructor( scope, object3d = null ) {
  4098. super();
  4099. this.scope = scope;
  4100. this.object3d = object3d;
  4101. this.updateType = NodeUpdateType.OBJECT;
  4102. this._uniformNode = new UniformNode( null );
  4103. }
  4104. getNodeType() {
  4105. const scope = this.scope;
  4106. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4107. return 'mat4';
  4108. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4109. return 'vec3';
  4110. }
  4111. }
  4112. update( frame ) {
  4113. const object = this.object3d;
  4114. const uniformNode = this._uniformNode;
  4115. const scope = this.scope;
  4116. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4117. uniformNode.value = object.matrixWorld;
  4118. } else if ( scope === Object3DNode.POSITION ) {
  4119. uniformNode.value = uniformNode.value || new Vector3();
  4120. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4121. } else if ( scope === Object3DNode.SCALE ) {
  4122. uniformNode.value = uniformNode.value || new Vector3();
  4123. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  4124. } else if ( scope === Object3DNode.DIRECTION ) {
  4125. uniformNode.value = uniformNode.value || new Vector3();
  4126. object.getWorldDirection( uniformNode.value );
  4127. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  4128. const camera = frame.camera;
  4129. uniformNode.value = uniformNode.value || new Vector3();
  4130. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4131. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  4132. }
  4133. }
  4134. generate( builder ) {
  4135. const scope = this.scope;
  4136. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4137. this._uniformNode.nodeType = 'mat4';
  4138. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4139. this._uniformNode.nodeType = 'vec3';
  4140. }
  4141. return this._uniformNode.build( builder );
  4142. }
  4143. serialize( data ) {
  4144. super.serialize( data );
  4145. data.scope = this.scope;
  4146. }
  4147. deserialize( data ) {
  4148. super.deserialize( data );
  4149. this.scope = data.scope;
  4150. }
  4151. }
  4152. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  4153. Object3DNode.POSITION = 'position';
  4154. Object3DNode.SCALE = 'scale';
  4155. Object3DNode.VIEW_POSITION = 'viewPosition';
  4156. Object3DNode.DIRECTION = 'direction';
  4157. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  4158. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  4159. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  4160. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  4161. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  4162. class ModelNode extends Object3DNode {
  4163. static get type() {
  4164. return 'ModelNode';
  4165. }
  4166. constructor( scope ) {
  4167. super( scope );
  4168. }
  4169. update( frame ) {
  4170. this.object3d = frame.object;
  4171. super.update( frame );
  4172. }
  4173. }
  4174. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  4175. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  4176. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  4177. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  4178. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  4179. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  4180. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  4181. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  4182. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4183. builder.context.isHighPrecisionModelViewMatrix = true;
  4184. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  4185. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4186. } );
  4187. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  4188. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4189. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  4190. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  4191. if ( isHighPrecisionModelViewMatrix !== true ) {
  4192. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4193. }
  4194. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  4195. } );
  4196. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  4197. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  4198. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  4199. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  4200. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  4201. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  4202. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  4203. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  4204. class FrontFacingNode extends Node {
  4205. static get type() {
  4206. return 'FrontFacingNode';
  4207. }
  4208. constructor() {
  4209. super( 'bool' );
  4210. this.isFrontFacingNode = true;
  4211. }
  4212. generate( builder ) {
  4213. const { renderer, material } = builder;
  4214. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  4215. if ( material.side === BackSide ) {
  4216. return 'false';
  4217. }
  4218. }
  4219. return builder.getFrontFacing();
  4220. }
  4221. }
  4222. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  4223. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  4224. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  4225. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  4226. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  4227. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  4228. return vec3( 0, 1, 0 );
  4229. }
  4230. return normalGeometry;
  4231. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  4232. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  4233. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4234. let node;
  4235. if ( builder.material.flatShading === true ) {
  4236. node = normalFlat;
  4237. } else {
  4238. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  4239. }
  4240. return node;
  4241. }, 'vec3' ).once() )().toVar( 'normalView' );
  4242. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  4243. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4244. return builder.context.setupNormal();
  4245. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  4246. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  4247. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4248. return builder.context.setupClearcoatNormal();
  4249. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  4250. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  4251. const m = mat3( matrix );
  4252. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  4253. return m.mul( transformedNormal ).xyz;
  4254. } );
  4255. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  4256. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  4257. if ( modelNormalViewMatrix !== null ) {
  4258. return modelNormalViewMatrix.transformDirection( normal );
  4259. }
  4260. //
  4261. const transformedNormal = modelNormalMatrix.mul( normal );
  4262. return cameraViewMatrix.transformDirection( transformedNormal );
  4263. } );
  4264. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  4265. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  4266. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  4267. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4268. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4269. class CubeTextureNode extends TextureNode {
  4270. static get type() {
  4271. return 'CubeTextureNode';
  4272. }
  4273. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  4274. super( value, uvNode, levelNode, biasNode );
  4275. this.isCubeTextureNode = true;
  4276. }
  4277. getInputType( /*builder*/ ) {
  4278. return 'cubeTexture';
  4279. }
  4280. getDefaultUV() {
  4281. const texture = this.value;
  4282. if ( texture.mapping === CubeReflectionMapping ) {
  4283. return reflectVector;
  4284. } else if ( texture.mapping === CubeRefractionMapping ) {
  4285. return refractVector;
  4286. } else {
  4287. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  4288. return vec3( 0, 0, 0 );
  4289. }
  4290. }
  4291. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  4292. setupUV( builder, uvNode ) {
  4293. const texture = this.value;
  4294. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  4295. return vec3( uvNode.x.negate(), uvNode.yz );
  4296. } else {
  4297. return uvNode;
  4298. }
  4299. }
  4300. generateUV( builder, cubeUV ) {
  4301. return cubeUV.build( builder, 'vec3' );
  4302. }
  4303. }
  4304. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  4305. class BufferNode extends UniformNode {
  4306. static get type() {
  4307. return 'BufferNode';
  4308. }
  4309. constructor( value, bufferType, bufferCount = 0 ) {
  4310. super( value, bufferType );
  4311. this.isBufferNode = true;
  4312. this.bufferType = bufferType;
  4313. this.bufferCount = bufferCount;
  4314. }
  4315. getElementType( builder ) {
  4316. return this.getNodeType( builder );
  4317. }
  4318. getInputType( /*builder*/ ) {
  4319. return 'buffer';
  4320. }
  4321. }
  4322. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  4323. class UniformArrayElementNode extends ArrayElementNode {
  4324. static get type() {
  4325. return 'UniformArrayElementNode';
  4326. }
  4327. constructor( arrayBuffer, indexNode ) {
  4328. super( arrayBuffer, indexNode );
  4329. this.isArrayBufferElementNode = true;
  4330. }
  4331. generate( builder ) {
  4332. const snippet = super.generate( builder );
  4333. const type = this.getNodeType();
  4334. return builder.format( snippet, 'vec4', type );
  4335. }
  4336. }
  4337. class UniformArrayNode extends BufferNode {
  4338. static get type() {
  4339. return 'UniformArrayNode';
  4340. }
  4341. constructor( value, elementType = null ) {
  4342. super( null, 'vec4' );
  4343. this.array = value;
  4344. this.elementType = elementType;
  4345. this._elementType = null;
  4346. this._elementLength = 0;
  4347. this.updateType = NodeUpdateType.RENDER;
  4348. this.isArrayBufferNode = true;
  4349. }
  4350. getElementType() {
  4351. return this.elementType || this._elementType;
  4352. }
  4353. getElementLength() {
  4354. return this._elementLength;
  4355. }
  4356. update( /*frame*/ ) {
  4357. const { array, value } = this;
  4358. const elementLength = this.getElementLength();
  4359. const elementType = this.getElementType();
  4360. if ( elementLength === 1 ) {
  4361. for ( let i = 0; i < array.length; i ++ ) {
  4362. const index = i * 4;
  4363. value[ index ] = array[ i ];
  4364. }
  4365. } else if ( elementType === 'color' ) {
  4366. for ( let i = 0; i < array.length; i ++ ) {
  4367. const index = i * 4;
  4368. const vector = array[ i ];
  4369. value[ index ] = vector.r;
  4370. value[ index + 1 ] = vector.g;
  4371. value[ index + 2 ] = vector.b || 0;
  4372. //value[ index + 3 ] = vector.a || 0;
  4373. }
  4374. } else {
  4375. for ( let i = 0; i < array.length; i ++ ) {
  4376. const index = i * 4;
  4377. const vector = array[ i ];
  4378. value[ index ] = vector.x;
  4379. value[ index + 1 ] = vector.y;
  4380. value[ index + 2 ] = vector.z || 0;
  4381. value[ index + 3 ] = vector.w || 0;
  4382. }
  4383. }
  4384. }
  4385. setup( builder ) {
  4386. const length = this.array.length;
  4387. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  4388. this._elementLength = builder.getTypeLength( this._elementType );
  4389. let arrayType = Float32Array;
  4390. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  4391. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  4392. this.value = new arrayType( length * 4 );
  4393. this.bufferCount = length;
  4394. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  4395. return super.setup( builder );
  4396. }
  4397. element( indexNode ) {
  4398. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  4399. }
  4400. }
  4401. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  4402. //
  4403. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  4404. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  4405. return nodeObject( new UniformArrayNode( values, nodeType ) );
  4406. };
  4407. class ReferenceElementNode extends ArrayElementNode {
  4408. static get type() {
  4409. return 'ReferenceElementNode';
  4410. }
  4411. constructor( referenceNode, indexNode ) {
  4412. super( referenceNode, indexNode );
  4413. this.referenceNode = referenceNode;
  4414. this.isReferenceElementNode = true;
  4415. }
  4416. getNodeType() {
  4417. return this.referenceNode.uniformType;
  4418. }
  4419. generate( builder ) {
  4420. const snippet = super.generate( builder );
  4421. const arrayType = this.referenceNode.getNodeType();
  4422. const elementType = this.getNodeType();
  4423. return builder.format( snippet, arrayType, elementType );
  4424. }
  4425. }
  4426. // TODO: Extends this from ReferenceBaseNode
  4427. class ReferenceNode extends Node {
  4428. static get type() {
  4429. return 'ReferenceNode';
  4430. }
  4431. constructor( property, uniformType, object = null, count = null ) {
  4432. super();
  4433. this.property = property;
  4434. this.uniformType = uniformType;
  4435. this.object = object;
  4436. this.count = count;
  4437. this.properties = property.split( '.' );
  4438. this.reference = object;
  4439. this.node = null;
  4440. this.group = null;
  4441. this.name = null;
  4442. this.updateType = NodeUpdateType.OBJECT;
  4443. }
  4444. element( indexNode ) {
  4445. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  4446. }
  4447. setGroup( group ) {
  4448. this.group = group;
  4449. return this;
  4450. }
  4451. label( name ) {
  4452. this.name = name;
  4453. return this;
  4454. }
  4455. setNodeType( uniformType ) {
  4456. let node = null;
  4457. if ( this.count !== null ) {
  4458. node = buffer( null, uniformType, this.count );
  4459. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  4460. node = uniformArray( null, uniformType );
  4461. } else if ( uniformType === 'texture' ) {
  4462. node = texture( null );
  4463. } else if ( uniformType === 'cubeTexture' ) {
  4464. node = cubeTexture( null );
  4465. } else {
  4466. node = uniform( null, uniformType );
  4467. }
  4468. if ( this.group !== null ) {
  4469. node.setGroup( this.group );
  4470. }
  4471. if ( this.name !== null ) node.label( this.name );
  4472. this.node = node.getSelf();
  4473. }
  4474. getNodeType( builder ) {
  4475. if ( this.node === null ) {
  4476. this.updateReference( builder );
  4477. this.updateValue();
  4478. }
  4479. return this.node.getNodeType( builder );
  4480. }
  4481. getValueFromReference( object = this.reference ) {
  4482. const { properties } = this;
  4483. let value = object[ properties[ 0 ] ];
  4484. for ( let i = 1; i < properties.length; i ++ ) {
  4485. value = value[ properties[ i ] ];
  4486. }
  4487. return value;
  4488. }
  4489. updateReference( state ) {
  4490. this.reference = this.object !== null ? this.object : state.object;
  4491. return this.reference;
  4492. }
  4493. setup() {
  4494. this.updateValue();
  4495. return this.node;
  4496. }
  4497. update( /*frame*/ ) {
  4498. this.updateValue();
  4499. }
  4500. updateValue() {
  4501. if ( this.node === null ) this.setNodeType( this.uniformType );
  4502. const value = this.getValueFromReference();
  4503. if ( Array.isArray( value ) ) {
  4504. this.node.array = value;
  4505. } else {
  4506. this.node.value = value;
  4507. }
  4508. }
  4509. }
  4510. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  4511. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  4512. class MaterialReferenceNode extends ReferenceNode {
  4513. static get type() {
  4514. return 'MaterialReferenceNode';
  4515. }
  4516. constructor( property, inputType, material = null ) {
  4517. super( property, inputType, material );
  4518. this.material = material;
  4519. //this.updateType = NodeUpdateType.RENDER;
  4520. this.isMaterialReferenceNode = true;
  4521. }
  4522. /*setNodeType( node ) {
  4523. super.setNodeType( node );
  4524. this.node.groupNode = renderGroup;
  4525. }*/
  4526. updateReference( state ) {
  4527. this.reference = this.material !== null ? this.material : state.material;
  4528. return this.reference;
  4529. }
  4530. }
  4531. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  4532. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  4533. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  4534. builder.geometry.computeTangents();
  4535. }
  4536. return attribute( 'tangent', 'vec4' );
  4537. } )();
  4538. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  4539. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  4540. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  4541. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  4542. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  4543. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  4544. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  4545. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  4546. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  4547. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  4548. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  4549. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  4550. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  4551. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  4552. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  4553. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  4554. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  4555. let bentNormal = anisotropyB.cross( positionViewDirection );
  4556. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  4557. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  4558. return bentNormal;
  4559. } )();
  4560. // Normal Mapping Without Precomputed Tangents
  4561. // http://www.thetenthplanet.de/archives/1180
  4562. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  4563. const { eye_pos, surf_norm, mapN, uv } = inputs;
  4564. const q0 = eye_pos.dFdx();
  4565. const q1 = eye_pos.dFdy();
  4566. const st0 = uv.dFdx();
  4567. const st1 = uv.dFdy();
  4568. const N = surf_norm; // normalized
  4569. const q1perp = q1.cross( N );
  4570. const q0perp = N.cross( q0 );
  4571. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  4572. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  4573. const det = T.dot( T ).max( B.dot( B ) );
  4574. const scale = faceDirection.mul( det.inverseSqrt() );
  4575. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  4576. } );
  4577. class NormalMapNode extends TempNode {
  4578. static get type() {
  4579. return 'NormalMapNode';
  4580. }
  4581. constructor( node, scaleNode = null ) {
  4582. super( 'vec3' );
  4583. this.node = node;
  4584. this.scaleNode = scaleNode;
  4585. this.normalMapType = TangentSpaceNormalMap;
  4586. }
  4587. setup( builder ) {
  4588. const { normalMapType, scaleNode } = this;
  4589. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  4590. if ( scaleNode !== null ) {
  4591. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  4592. }
  4593. let outputNode = null;
  4594. if ( normalMapType === ObjectSpaceNormalMap ) {
  4595. outputNode = transformNormalToView( normalMap );
  4596. } else if ( normalMapType === TangentSpaceNormalMap ) {
  4597. const tangent = builder.hasGeometryAttribute( 'tangent' );
  4598. if ( tangent === true ) {
  4599. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  4600. } else {
  4601. outputNode = perturbNormal2Arb( {
  4602. eye_pos: positionView,
  4603. surf_norm: normalView,
  4604. mapN: normalMap,
  4605. uv: uv()
  4606. } );
  4607. }
  4608. }
  4609. return outputNode;
  4610. }
  4611. }
  4612. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  4613. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  4614. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  4615. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  4616. // It's used to preserve the same TextureNode instance
  4617. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  4618. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  4619. return vec2(
  4620. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  4621. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  4622. ).mul( bumpScale );
  4623. } );
  4624. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  4625. const perturbNormalArb = Fn( ( inputs ) => {
  4626. const { surf_pos, surf_norm, dHdxy } = inputs;
  4627. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  4628. const vSigmaX = surf_pos.dFdx().normalize();
  4629. const vSigmaY = surf_pos.dFdy().normalize();
  4630. const vN = surf_norm; // normalized
  4631. const R1 = vSigmaY.cross( vN );
  4632. const R2 = vN.cross( vSigmaX );
  4633. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  4634. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  4635. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  4636. } );
  4637. class BumpMapNode extends TempNode {
  4638. static get type() {
  4639. return 'BumpMapNode';
  4640. }
  4641. constructor( textureNode, scaleNode = null ) {
  4642. super( 'vec3' );
  4643. this.textureNode = textureNode;
  4644. this.scaleNode = scaleNode;
  4645. }
  4646. setup() {
  4647. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  4648. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  4649. return perturbNormalArb( {
  4650. surf_pos: positionView,
  4651. surf_norm: normalView,
  4652. dHdxy
  4653. } );
  4654. }
  4655. }
  4656. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  4657. const _propertyCache = new Map();
  4658. class MaterialNode extends Node {
  4659. static get type() {
  4660. return 'MaterialNode';
  4661. }
  4662. constructor( scope ) {
  4663. super();
  4664. this.scope = scope;
  4665. }
  4666. getCache( property, type ) {
  4667. let node = _propertyCache.get( property );
  4668. if ( node === undefined ) {
  4669. node = materialReference( property, type );
  4670. _propertyCache.set( property, node );
  4671. }
  4672. return node;
  4673. }
  4674. getFloat( property ) {
  4675. return this.getCache( property, 'float' );
  4676. }
  4677. getColor( property ) {
  4678. return this.getCache( property, 'color' );
  4679. }
  4680. getTexture( property ) {
  4681. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  4682. }
  4683. setup( builder ) {
  4684. const material = builder.context.material;
  4685. const scope = this.scope;
  4686. let node = null;
  4687. if ( scope === MaterialNode.COLOR ) {
  4688. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  4689. if ( material.map && material.map.isTexture === true ) {
  4690. node = colorNode.mul( this.getTexture( 'map' ) );
  4691. } else {
  4692. node = colorNode;
  4693. }
  4694. } else if ( scope === MaterialNode.OPACITY ) {
  4695. const opacityNode = this.getFloat( scope );
  4696. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  4697. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  4698. } else {
  4699. node = opacityNode;
  4700. }
  4701. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  4702. if ( material.specularMap && material.specularMap.isTexture === true ) {
  4703. node = this.getTexture( 'specular' ).r;
  4704. } else {
  4705. node = float( 1 );
  4706. }
  4707. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  4708. const specularIntensity = this.getFloat( scope );
  4709. if ( material.specularMap ) {
  4710. node = specularIntensity.mul( this.getTexture( scope ).a );
  4711. } else {
  4712. node = specularIntensity;
  4713. }
  4714. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  4715. const specularColorNode = this.getColor( scope );
  4716. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  4717. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  4718. } else {
  4719. node = specularColorNode;
  4720. }
  4721. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  4722. const roughnessNode = this.getFloat( scope );
  4723. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  4724. node = roughnessNode.mul( this.getTexture( scope ).g );
  4725. } else {
  4726. node = roughnessNode;
  4727. }
  4728. } else if ( scope === MaterialNode.METALNESS ) {
  4729. const metalnessNode = this.getFloat( scope );
  4730. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  4731. node = metalnessNode.mul( this.getTexture( scope ).b );
  4732. } else {
  4733. node = metalnessNode;
  4734. }
  4735. } else if ( scope === MaterialNode.EMISSIVE ) {
  4736. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  4737. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  4738. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  4739. node = emissiveNode.mul( this.getTexture( scope ) );
  4740. } else {
  4741. node = emissiveNode;
  4742. }
  4743. } else if ( scope === MaterialNode.NORMAL ) {
  4744. if ( material.normalMap ) {
  4745. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  4746. node.normalMapType = material.normalMapType;
  4747. } else if ( material.bumpMap ) {
  4748. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  4749. } else {
  4750. node = normalView;
  4751. }
  4752. } else if ( scope === MaterialNode.CLEARCOAT ) {
  4753. const clearcoatNode = this.getFloat( scope );
  4754. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  4755. node = clearcoatNode.mul( this.getTexture( scope ).r );
  4756. } else {
  4757. node = clearcoatNode;
  4758. }
  4759. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  4760. const clearcoatRoughnessNode = this.getFloat( scope );
  4761. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  4762. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  4763. } else {
  4764. node = clearcoatRoughnessNode;
  4765. }
  4766. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  4767. if ( material.clearcoatNormalMap ) {
  4768. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  4769. } else {
  4770. node = normalView;
  4771. }
  4772. } else if ( scope === MaterialNode.SHEEN ) {
  4773. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  4774. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  4775. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  4776. } else {
  4777. node = sheenNode;
  4778. }
  4779. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  4780. const sheenRoughnessNode = this.getFloat( scope );
  4781. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  4782. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  4783. } else {
  4784. node = sheenRoughnessNode;
  4785. }
  4786. node = node.clamp( 0.07, 1.0 );
  4787. } else if ( scope === MaterialNode.ANISOTROPY ) {
  4788. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  4789. const anisotropyPolar = this.getTexture( scope );
  4790. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  4791. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  4792. } else {
  4793. node = materialAnisotropyVector;
  4794. }
  4795. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  4796. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  4797. if ( material.iridescenceThicknessMap ) {
  4798. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  4799. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  4800. } else {
  4801. node = iridescenceThicknessMaximum;
  4802. }
  4803. } else if ( scope === MaterialNode.TRANSMISSION ) {
  4804. const transmissionNode = this.getFloat( scope );
  4805. if ( material.transmissionMap ) {
  4806. node = transmissionNode.mul( this.getTexture( scope ).r );
  4807. } else {
  4808. node = transmissionNode;
  4809. }
  4810. } else if ( scope === MaterialNode.THICKNESS ) {
  4811. const thicknessNode = this.getFloat( scope );
  4812. if ( material.thicknessMap ) {
  4813. node = thicknessNode.mul( this.getTexture( scope ).g );
  4814. } else {
  4815. node = thicknessNode;
  4816. }
  4817. } else if ( scope === MaterialNode.IOR ) {
  4818. node = this.getFloat( scope );
  4819. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  4820. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  4821. } else if ( scope === MaterialNode.AO_MAP ) {
  4822. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  4823. } else {
  4824. const outputType = this.getNodeType( builder );
  4825. node = this.getCache( scope, outputType );
  4826. }
  4827. return node;
  4828. }
  4829. }
  4830. MaterialNode.ALPHA_TEST = 'alphaTest';
  4831. MaterialNode.COLOR = 'color';
  4832. MaterialNode.OPACITY = 'opacity';
  4833. MaterialNode.SHININESS = 'shininess';
  4834. MaterialNode.SPECULAR = 'specular';
  4835. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  4836. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  4837. MaterialNode.SPECULAR_COLOR = 'specularColor';
  4838. MaterialNode.REFLECTIVITY = 'reflectivity';
  4839. MaterialNode.ROUGHNESS = 'roughness';
  4840. MaterialNode.METALNESS = 'metalness';
  4841. MaterialNode.NORMAL = 'normal';
  4842. MaterialNode.CLEARCOAT = 'clearcoat';
  4843. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  4844. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  4845. MaterialNode.EMISSIVE = 'emissive';
  4846. MaterialNode.ROTATION = 'rotation';
  4847. MaterialNode.SHEEN = 'sheen';
  4848. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  4849. MaterialNode.ANISOTROPY = 'anisotropy';
  4850. MaterialNode.IRIDESCENCE = 'iridescence';
  4851. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  4852. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  4853. MaterialNode.IOR = 'ior';
  4854. MaterialNode.TRANSMISSION = 'transmission';
  4855. MaterialNode.THICKNESS = 'thickness';
  4856. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  4857. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  4858. MaterialNode.LINE_SCALE = 'scale';
  4859. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  4860. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  4861. MaterialNode.LINE_WIDTH = 'linewidth';
  4862. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  4863. MaterialNode.POINT_WIDTH = 'pointWidth';
  4864. MaterialNode.DISPERSION = 'dispersion';
  4865. MaterialNode.LIGHT_MAP = 'light';
  4866. MaterialNode.AO_MAP = 'ao';
  4867. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  4868. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  4869. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  4870. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  4871. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  4872. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  4873. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  4874. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  4875. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  4876. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  4877. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  4878. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  4879. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  4880. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  4881. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  4882. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  4883. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  4884. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  4885. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  4886. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  4887. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  4888. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  4889. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  4890. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  4891. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  4892. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  4893. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  4894. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  4895. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  4896. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  4897. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  4898. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  4899. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  4900. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  4901. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  4902. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  4903. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  4904. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  4905. return frame.material;
  4906. } ).onRenderUpdate( function ( { material } ) {
  4907. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  4908. } );
  4909. class ModelViewProjectionNode extends TempNode {
  4910. static get type() {
  4911. return 'ModelViewProjectionNode';
  4912. }
  4913. constructor( positionNode = null ) {
  4914. super( 'vec4' );
  4915. this.positionNode = positionNode;
  4916. }
  4917. setup( builder ) {
  4918. if ( builder.shaderStage === 'fragment' ) {
  4919. return varying( builder.context.mvp );
  4920. }
  4921. const position = this.positionNode || positionLocal;
  4922. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  4923. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  4924. }
  4925. }
  4926. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  4927. /**
  4928. * This class represents shader indices of different types. The following predefined node
  4929. * objects cover frequent use cases:
  4930. *
  4931. * - `vertexIndex`: The index of a vertex within a mesh.
  4932. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  4933. * - `drawIndex`: The index of a draw call.
  4934. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  4935. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  4936. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  4937. *
  4938. * @augments Node
  4939. */
  4940. class IndexNode extends Node {
  4941. static get type() {
  4942. return 'IndexNode';
  4943. }
  4944. /**
  4945. * Constructs a new index node.
  4946. *
  4947. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} value - The scope of the index node.
  4948. */
  4949. constructor( scope ) {
  4950. super( 'uint' );
  4951. /**
  4952. * The scope of the index node.
  4953. *
  4954. * @type {String}
  4955. */
  4956. this.scope = scope;
  4957. /**
  4958. * This flag can be used for type testing.
  4959. *
  4960. * @type {Boolean}
  4961. * @readonly
  4962. * @default true
  4963. */
  4964. this.isIndexNode = true;
  4965. }
  4966. generate( builder ) {
  4967. const nodeType = this.getNodeType( builder );
  4968. const scope = this.scope;
  4969. let propertyName;
  4970. if ( scope === IndexNode.VERTEX ) {
  4971. propertyName = builder.getVertexIndex();
  4972. } else if ( scope === IndexNode.INSTANCE ) {
  4973. propertyName = builder.getInstanceIndex();
  4974. } else if ( scope === IndexNode.DRAW ) {
  4975. propertyName = builder.getDrawIndex();
  4976. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  4977. propertyName = builder.getInvocationLocalIndex();
  4978. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  4979. propertyName = builder.getInvocationSubgroupIndex();
  4980. } else if ( scope === IndexNode.SUBGROUP ) {
  4981. propertyName = builder.getSubgroupIndex();
  4982. } else {
  4983. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  4984. }
  4985. let output;
  4986. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  4987. output = propertyName;
  4988. } else {
  4989. const nodeVarying = varying( this );
  4990. output = nodeVarying.build( builder, nodeType );
  4991. }
  4992. return output;
  4993. }
  4994. }
  4995. IndexNode.VERTEX = 'vertex';
  4996. IndexNode.INSTANCE = 'instance';
  4997. IndexNode.SUBGROUP = 'subgroup';
  4998. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  4999. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  5000. IndexNode.DRAW = 'draw';
  5001. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  5002. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  5003. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  5004. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  5005. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  5006. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  5007. class InstanceNode extends Node {
  5008. static get type() {
  5009. return 'InstanceNode';
  5010. }
  5011. constructor( count, instanceMatrix, instanceColor ) {
  5012. super( 'void' );
  5013. this.count = count;
  5014. this.instanceMatrix = instanceMatrix;
  5015. this.instanceColor = instanceColor;
  5016. this.instanceMatrixNode = null;
  5017. this.instanceColorNode = null;
  5018. this.updateType = NodeUpdateType.FRAME;
  5019. this.buffer = null;
  5020. this.bufferColor = null;
  5021. }
  5022. setup( builder ) {
  5023. const { count, instanceMatrix, instanceColor } = this;
  5024. let { instanceMatrixNode, instanceColorNode } = this;
  5025. if ( instanceMatrixNode === null ) {
  5026. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  5027. if ( count <= 1000 ) {
  5028. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  5029. } else {
  5030. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  5031. this.buffer = buffer;
  5032. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5033. const instanceBuffers = [
  5034. // F.Signature -> bufferAttribute( array, type, stride, offset )
  5035. bufferFn( buffer, 'vec4', 16, 0 ),
  5036. bufferFn( buffer, 'vec4', 16, 4 ),
  5037. bufferFn( buffer, 'vec4', 16, 8 ),
  5038. bufferFn( buffer, 'vec4', 16, 12 )
  5039. ];
  5040. instanceMatrixNode = mat4( ...instanceBuffers );
  5041. }
  5042. this.instanceMatrixNode = instanceMatrixNode;
  5043. }
  5044. if ( instanceColor && instanceColorNode === null ) {
  5045. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  5046. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5047. this.bufferColor = buffer;
  5048. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  5049. this.instanceColorNode = instanceColorNode;
  5050. }
  5051. // POSITION
  5052. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  5053. positionLocal.assign( instancePosition );
  5054. // NORMAL
  5055. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5056. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  5057. // ASSIGNS
  5058. normalLocal.assign( instanceNormal );
  5059. }
  5060. // COLOR
  5061. if ( this.instanceColorNode !== null ) {
  5062. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  5063. }
  5064. }
  5065. update( /*frame*/ ) {
  5066. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  5067. this.buffer.version = this.instanceMatrix.version;
  5068. }
  5069. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  5070. this.bufferColor.version = this.instanceColor.version;
  5071. }
  5072. }
  5073. }
  5074. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  5075. class InstancedMeshNode extends InstanceNode {
  5076. static get type() {
  5077. return 'InstancedMeshNode';
  5078. }
  5079. constructor( instanceMesh ) {
  5080. const { count, instanceMatrix, instanceColor } = instanceMesh;
  5081. super( count, instanceMatrix, instanceColor );
  5082. this.instanceMesh = instanceMesh;
  5083. }
  5084. }
  5085. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  5086. class BatchNode extends Node {
  5087. static get type() {
  5088. return 'BatchNode';
  5089. }
  5090. constructor( batchMesh ) {
  5091. super( 'void' );
  5092. this.batchMesh = batchMesh;
  5093. this.batchingIdNode = null;
  5094. }
  5095. setup( builder ) {
  5096. // POSITION
  5097. if ( this.batchingIdNode === null ) {
  5098. if ( builder.getDrawIndex() === null ) {
  5099. this.batchingIdNode = instanceIndex;
  5100. } else {
  5101. this.batchingIdNode = drawIndex;
  5102. }
  5103. }
  5104. const getIndirectIndex = Fn( ( [ id ] ) => {
  5105. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  5106. const x = int( id ).modInt( int( size ) );
  5107. const y = int( id ).div( int( size ) );
  5108. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  5109. } ).setLayout( {
  5110. name: 'getIndirectIndex',
  5111. type: 'uint',
  5112. inputs: [
  5113. { name: 'id', type: 'int' }
  5114. ]
  5115. } );
  5116. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  5117. const matricesTexture = this.batchMesh._matricesTexture;
  5118. const size = textureSize( textureLoad( matricesTexture ), 0 );
  5119. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  5120. const x = j.modInt( size );
  5121. const y = j.div( int( size ) );
  5122. const batchingMatrix = mat4(
  5123. textureLoad( matricesTexture, ivec2( x, y ) ),
  5124. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  5125. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  5126. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  5127. );
  5128. const colorsTexture = this.batchMesh._colorsTexture;
  5129. if ( colorsTexture !== null ) {
  5130. const getBatchingColor = Fn( ( [ id ] ) => {
  5131. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  5132. const j = id;
  5133. const x = j.modInt( size );
  5134. const y = j.div( size );
  5135. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  5136. } ).setLayout( {
  5137. name: 'getBatchingColor',
  5138. type: 'vec3',
  5139. inputs: [
  5140. { name: 'id', type: 'int' }
  5141. ]
  5142. } );
  5143. const color = getBatchingColor( indirectId );
  5144. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  5145. }
  5146. const bm = mat3( batchingMatrix );
  5147. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  5148. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  5149. const batchingNormal = bm.mul( transformedNormal ).xyz;
  5150. normalLocal.assign( batchingNormal );
  5151. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5152. tangentLocal.mulAssign( bm );
  5153. }
  5154. }
  5155. }
  5156. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  5157. const _frameId = new WeakMap();
  5158. class SkinningNode extends Node {
  5159. static get type() {
  5160. return 'SkinningNode';
  5161. }
  5162. constructor( skinnedMesh, useReference = false ) {
  5163. super( 'void' );
  5164. this.skinnedMesh = skinnedMesh;
  5165. this.useReference = useReference;
  5166. this.updateType = NodeUpdateType.OBJECT;
  5167. //
  5168. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  5169. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  5170. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  5171. if ( useReference ) {
  5172. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  5173. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  5174. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5175. } else {
  5176. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  5177. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  5178. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  5179. }
  5180. this.bindMatrixNode = bindMatrixNode;
  5181. this.bindMatrixInverseNode = bindMatrixInverseNode;
  5182. this.boneMatricesNode = boneMatricesNode;
  5183. this.previousBoneMatricesNode = null;
  5184. }
  5185. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  5186. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5187. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5188. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5189. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5190. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5191. // POSITION
  5192. const skinVertex = bindMatrixNode.mul( position );
  5193. const skinned = add(
  5194. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  5195. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  5196. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  5197. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  5198. );
  5199. return bindMatrixInverseNode.mul( skinned ).xyz;
  5200. }
  5201. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  5202. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5203. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5204. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5205. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5206. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5207. // NORMAL
  5208. let skinMatrix = add(
  5209. skinWeightNode.x.mul( boneMatX ),
  5210. skinWeightNode.y.mul( boneMatY ),
  5211. skinWeightNode.z.mul( boneMatZ ),
  5212. skinWeightNode.w.mul( boneMatW )
  5213. );
  5214. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  5215. return skinMatrix.transformDirection( normal ).xyz;
  5216. }
  5217. getPreviousSkinnedPosition( builder ) {
  5218. const skinnedMesh = builder.object;
  5219. if ( this.previousBoneMatricesNode === null ) {
  5220. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  5221. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5222. }
  5223. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  5224. }
  5225. needsPreviousBoneMatrices( builder ) {
  5226. const mrt = builder.renderer.getMRT();
  5227. return mrt && mrt.has( 'velocity' );
  5228. }
  5229. setup( builder ) {
  5230. if ( this.needsPreviousBoneMatrices( builder ) ) {
  5231. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  5232. }
  5233. const skinPosition = this.getSkinnedPosition();
  5234. positionLocal.assign( skinPosition );
  5235. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5236. const skinNormal = this.getSkinnedNormal();
  5237. normalLocal.assign( skinNormal );
  5238. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5239. tangentLocal.assign( skinNormal );
  5240. }
  5241. }
  5242. }
  5243. generate( builder, output ) {
  5244. if ( output !== 'void' ) {
  5245. return positionLocal.build( builder, output );
  5246. }
  5247. }
  5248. update( frame ) {
  5249. const object = this.useReference ? frame.object : this.skinnedMesh;
  5250. const skeleton = object.skeleton;
  5251. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  5252. _frameId.set( skeleton, frame.frameId );
  5253. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  5254. skeleton.update();
  5255. }
  5256. }
  5257. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  5258. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  5259. class LoopNode extends Node {
  5260. static get type() {
  5261. return 'LoopNode';
  5262. }
  5263. constructor( params = [] ) {
  5264. super();
  5265. this.params = params;
  5266. }
  5267. getVarName( index ) {
  5268. return String.fromCharCode( 'i'.charCodeAt() + index );
  5269. }
  5270. getProperties( builder ) {
  5271. const properties = builder.getNodeProperties( this );
  5272. if ( properties.stackNode !== undefined ) return properties;
  5273. //
  5274. const inputs = {};
  5275. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  5276. const param = this.params[ i ];
  5277. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  5278. const type = ( param.isNode !== true && param.type ) || 'int';
  5279. inputs[ name ] = expression( name, type );
  5280. }
  5281. const stack = builder.addStack(); // TODO: cache() it
  5282. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  5283. properties.stackNode = stack;
  5284. builder.removeStack();
  5285. return properties;
  5286. }
  5287. getNodeType( builder ) {
  5288. const { returnsNode } = this.getProperties( builder );
  5289. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  5290. }
  5291. setup( builder ) {
  5292. // setup properties
  5293. this.getProperties( builder );
  5294. }
  5295. generate( builder ) {
  5296. const properties = this.getProperties( builder );
  5297. const params = this.params;
  5298. const stackNode = properties.stackNode;
  5299. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  5300. const param = params[ i ];
  5301. let start = null, end = null, name = null, type = null, condition = null, update = null;
  5302. if ( param.isNode ) {
  5303. type = 'int';
  5304. name = this.getVarName( i );
  5305. start = '0';
  5306. end = param.build( builder, type );
  5307. condition = '<';
  5308. } else {
  5309. type = param.type || 'int';
  5310. name = param.name || this.getVarName( i );
  5311. start = param.start;
  5312. end = param.end;
  5313. condition = param.condition;
  5314. update = param.update;
  5315. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  5316. else if ( start && start.isNode ) start = start.build( builder, type );
  5317. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  5318. else if ( end && end.isNode ) end = end.build( builder, type );
  5319. if ( start !== undefined && end === undefined ) {
  5320. start = start + ' - 1';
  5321. end = '0';
  5322. condition = '>=';
  5323. } else if ( end !== undefined && start === undefined ) {
  5324. start = '0';
  5325. condition = '<';
  5326. }
  5327. if ( condition === undefined ) {
  5328. if ( Number( start ) > Number( end ) ) {
  5329. condition = '>=';
  5330. } else {
  5331. condition = '<';
  5332. }
  5333. }
  5334. }
  5335. const internalParam = { start, end, condition };
  5336. //
  5337. const startSnippet = internalParam.start;
  5338. const endSnippet = internalParam.end;
  5339. let declarationSnippet = '';
  5340. let conditionalSnippet = '';
  5341. let updateSnippet = '';
  5342. if ( ! update ) {
  5343. if ( type === 'int' || type === 'uint' ) {
  5344. if ( condition.includes( '<' ) ) update = '++';
  5345. else update = '--';
  5346. } else {
  5347. if ( condition.includes( '<' ) ) update = '+= 1.';
  5348. else update = '-= 1.';
  5349. }
  5350. }
  5351. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  5352. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  5353. updateSnippet += name + ' ' + update;
  5354. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  5355. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  5356. }
  5357. const stackSnippet = stackNode.build( builder, 'void' );
  5358. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  5359. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  5360. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  5361. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  5362. }
  5363. builder.addFlowTab();
  5364. return returnsSnippet;
  5365. }
  5366. }
  5367. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  5368. const Continue = () => expression( 'continue' ).append();
  5369. const Break = () => expression( 'break' ).append();
  5370. //
  5371. const loop = ( ...params ) => { // @deprecated, r168
  5372. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  5373. return Loop( ...params );
  5374. };
  5375. const _morphTextures = /*@__PURE__*/ new WeakMap();
  5376. const _morphVec4 = /*@__PURE__*/ new Vector4();
  5377. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  5378. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  5379. const y = texelIndex.div( width );
  5380. const x = texelIndex.sub( y.mul( width ) );
  5381. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  5382. return bufferAttrib.mul( influence );
  5383. } );
  5384. function getEntry( geometry ) {
  5385. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  5386. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  5387. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  5388. // instead of using attributes, the WebGL 2 code path encodes morph targets
  5389. // into an array of data textures. Each layer represents a single morph target.
  5390. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  5391. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  5392. let entry = _morphTextures.get( geometry );
  5393. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  5394. if ( entry !== undefined ) entry.texture.dispose();
  5395. const morphTargets = geometry.morphAttributes.position || [];
  5396. const morphNormals = geometry.morphAttributes.normal || [];
  5397. const morphColors = geometry.morphAttributes.color || [];
  5398. let vertexDataCount = 0;
  5399. if ( hasMorphPosition === true ) vertexDataCount = 1;
  5400. if ( hasMorphNormals === true ) vertexDataCount = 2;
  5401. if ( hasMorphColors === true ) vertexDataCount = 3;
  5402. let width = geometry.attributes.position.count * vertexDataCount;
  5403. let height = 1;
  5404. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  5405. if ( width > maxTextureSize ) {
  5406. height = Math.ceil( width / maxTextureSize );
  5407. width = maxTextureSize;
  5408. }
  5409. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  5410. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  5411. bufferTexture.type = FloatType;
  5412. bufferTexture.needsUpdate = true;
  5413. // fill buffer
  5414. const vertexDataStride = vertexDataCount * 4;
  5415. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  5416. const morphTarget = morphTargets[ i ];
  5417. const morphNormal = morphNormals[ i ];
  5418. const morphColor = morphColors[ i ];
  5419. const offset = width * height * 4 * i;
  5420. for ( let j = 0; j < morphTarget.count; j ++ ) {
  5421. const stride = j * vertexDataStride;
  5422. if ( hasMorphPosition === true ) {
  5423. _morphVec4.fromBufferAttribute( morphTarget, j );
  5424. buffer[ offset + stride + 0 ] = _morphVec4.x;
  5425. buffer[ offset + stride + 1 ] = _morphVec4.y;
  5426. buffer[ offset + stride + 2 ] = _morphVec4.z;
  5427. buffer[ offset + stride + 3 ] = 0;
  5428. }
  5429. if ( hasMorphNormals === true ) {
  5430. _morphVec4.fromBufferAttribute( morphNormal, j );
  5431. buffer[ offset + stride + 4 ] = _morphVec4.x;
  5432. buffer[ offset + stride + 5 ] = _morphVec4.y;
  5433. buffer[ offset + stride + 6 ] = _morphVec4.z;
  5434. buffer[ offset + stride + 7 ] = 0;
  5435. }
  5436. if ( hasMorphColors === true ) {
  5437. _morphVec4.fromBufferAttribute( morphColor, j );
  5438. buffer[ offset + stride + 8 ] = _morphVec4.x;
  5439. buffer[ offset + stride + 9 ] = _morphVec4.y;
  5440. buffer[ offset + stride + 10 ] = _morphVec4.z;
  5441. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  5442. }
  5443. }
  5444. }
  5445. entry = {
  5446. count: morphTargetsCount,
  5447. texture: bufferTexture,
  5448. stride: vertexDataCount,
  5449. size: new Vector2( width, height )
  5450. };
  5451. _morphTextures.set( geometry, entry );
  5452. function disposeTexture() {
  5453. bufferTexture.dispose();
  5454. _morphTextures.delete( geometry );
  5455. geometry.removeEventListener( 'dispose', disposeTexture );
  5456. }
  5457. geometry.addEventListener( 'dispose', disposeTexture );
  5458. }
  5459. return entry;
  5460. }
  5461. class MorphNode extends Node {
  5462. static get type() {
  5463. return 'MorphNode';
  5464. }
  5465. constructor( mesh ) {
  5466. super( 'void' );
  5467. this.mesh = mesh;
  5468. this.morphBaseInfluence = uniform( 1 );
  5469. this.updateType = NodeUpdateType.OBJECT;
  5470. }
  5471. setup( builder ) {
  5472. const { geometry } = builder;
  5473. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  5474. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  5475. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  5476. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  5477. // nodes
  5478. const { texture: bufferMap, stride, size } = getEntry( geometry );
  5479. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  5480. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  5481. const width = int( size.width );
  5482. Loop( morphTargetsCount, ( { i } ) => {
  5483. const influence = float( 0 ).toVar();
  5484. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  5485. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  5486. } else {
  5487. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  5488. }
  5489. if ( hasMorphPosition === true ) {
  5490. positionLocal.addAssign( getMorph( {
  5491. bufferMap,
  5492. influence,
  5493. stride,
  5494. width,
  5495. depth: i,
  5496. offset: int( 0 )
  5497. } ) );
  5498. }
  5499. if ( hasMorphNormals === true ) {
  5500. normalLocal.addAssign( getMorph( {
  5501. bufferMap,
  5502. influence,
  5503. stride,
  5504. width,
  5505. depth: i,
  5506. offset: int( 1 )
  5507. } ) );
  5508. }
  5509. } );
  5510. }
  5511. update() {
  5512. const morphBaseInfluence = this.morphBaseInfluence;
  5513. if ( this.mesh.geometry.morphTargetsRelative ) {
  5514. morphBaseInfluence.value = 1;
  5515. } else {
  5516. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  5517. }
  5518. }
  5519. }
  5520. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  5521. class LightingNode extends Node {
  5522. static get type() {
  5523. return 'LightingNode';
  5524. }
  5525. constructor() {
  5526. super( 'vec3' );
  5527. this.isLightingNode = true;
  5528. }
  5529. generate( /*builder*/ ) {
  5530. console.warn( 'Abstract function.' );
  5531. }
  5532. }
  5533. class AONode extends LightingNode {
  5534. static get type() {
  5535. return 'AONode';
  5536. }
  5537. constructor( aoNode = null ) {
  5538. super();
  5539. this.aoNode = aoNode;
  5540. }
  5541. setup( builder ) {
  5542. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  5543. }
  5544. }
  5545. class LightingContextNode extends ContextNode {
  5546. static get type() {
  5547. return 'LightingContextNode';
  5548. }
  5549. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  5550. super( node );
  5551. this.lightingModel = lightingModel;
  5552. this.backdropNode = backdropNode;
  5553. this.backdropAlphaNode = backdropAlphaNode;
  5554. this._value = null;
  5555. }
  5556. getContext() {
  5557. const { backdropNode, backdropAlphaNode } = this;
  5558. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  5559. directSpecular = vec3().toVar( 'directSpecular' ),
  5560. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  5561. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  5562. const reflectedLight = {
  5563. directDiffuse,
  5564. directSpecular,
  5565. indirectDiffuse,
  5566. indirectSpecular
  5567. };
  5568. const context = {
  5569. radiance: vec3().toVar( 'radiance' ),
  5570. irradiance: vec3().toVar( 'irradiance' ),
  5571. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  5572. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  5573. reflectedLight,
  5574. backdrop: backdropNode,
  5575. backdropAlpha: backdropAlphaNode
  5576. };
  5577. return context;
  5578. }
  5579. setup( builder ) {
  5580. this.value = this._value || ( this._value = this.getContext() );
  5581. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  5582. return super.setup( builder );
  5583. }
  5584. }
  5585. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  5586. class IrradianceNode extends LightingNode {
  5587. static get type() {
  5588. return 'IrradianceNode';
  5589. }
  5590. constructor( node ) {
  5591. super();
  5592. this.node = node;
  5593. }
  5594. setup( builder ) {
  5595. builder.context.irradiance.addAssign( this.node );
  5596. }
  5597. }
  5598. let screenSizeVec, viewportVec;
  5599. class ScreenNode extends Node {
  5600. static get type() {
  5601. return 'ScreenNode';
  5602. }
  5603. constructor( scope ) {
  5604. super();
  5605. this.scope = scope;
  5606. this.isViewportNode = true;
  5607. }
  5608. getNodeType() {
  5609. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  5610. else return 'vec2';
  5611. }
  5612. getUpdateType() {
  5613. let updateType = NodeUpdateType.NONE;
  5614. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  5615. updateType = NodeUpdateType.RENDER;
  5616. }
  5617. this.updateType = updateType;
  5618. return updateType;
  5619. }
  5620. update( { renderer } ) {
  5621. const renderTarget = renderer.getRenderTarget();
  5622. if ( this.scope === ScreenNode.VIEWPORT ) {
  5623. if ( renderTarget !== null ) {
  5624. viewportVec.copy( renderTarget.viewport );
  5625. } else {
  5626. renderer.getViewport( viewportVec );
  5627. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  5628. }
  5629. } else {
  5630. if ( renderTarget !== null ) {
  5631. screenSizeVec.width = renderTarget.width;
  5632. screenSizeVec.height = renderTarget.height;
  5633. } else {
  5634. renderer.getDrawingBufferSize( screenSizeVec );
  5635. }
  5636. }
  5637. }
  5638. setup( /*builder*/ ) {
  5639. const scope = this.scope;
  5640. let output = null;
  5641. if ( scope === ScreenNode.SIZE ) {
  5642. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  5643. } else if ( scope === ScreenNode.VIEWPORT ) {
  5644. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  5645. } else {
  5646. output = vec2( screenCoordinate.div( screenSize ) );
  5647. }
  5648. return output;
  5649. }
  5650. generate( builder ) {
  5651. if ( this.scope === ScreenNode.COORDINATE ) {
  5652. let coord = builder.getFragCoord();
  5653. if ( builder.isFlipY() ) {
  5654. // follow webgpu standards
  5655. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  5656. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  5657. }
  5658. return coord;
  5659. }
  5660. return super.generate( builder );
  5661. }
  5662. }
  5663. ScreenNode.COORDINATE = 'coordinate';
  5664. ScreenNode.VIEWPORT = 'viewport';
  5665. ScreenNode.SIZE = 'size';
  5666. ScreenNode.UV = 'uv';
  5667. // Screen
  5668. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  5669. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  5670. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  5671. // Viewport
  5672. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  5673. const viewportSize = viewport.zw;
  5674. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  5675. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  5676. // Deprecated
  5677. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  5678. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  5679. return screenSize;
  5680. }, 'vec2' ).once() )();
  5681. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  5682. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  5683. return screenUV;
  5684. }, 'vec2' ).once() )();
  5685. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  5686. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  5687. return screenUV.flipY();
  5688. }, 'vec2' ).once() )();
  5689. const _size$4 = /*@__PURE__*/ new Vector2();
  5690. class ViewportTextureNode extends TextureNode {
  5691. static get type() {
  5692. return 'ViewportTextureNode';
  5693. }
  5694. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  5695. if ( framebufferTexture === null ) {
  5696. framebufferTexture = new FramebufferTexture();
  5697. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  5698. }
  5699. super( framebufferTexture, uvNode, levelNode );
  5700. this.generateMipmaps = false;
  5701. this.isOutputTextureNode = true;
  5702. this.updateBeforeType = NodeUpdateType.FRAME;
  5703. }
  5704. updateBefore( frame ) {
  5705. const renderer = frame.renderer;
  5706. renderer.getDrawingBufferSize( _size$4 );
  5707. //
  5708. const framebufferTexture = this.value;
  5709. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  5710. framebufferTexture.image.width = _size$4.width;
  5711. framebufferTexture.image.height = _size$4.height;
  5712. framebufferTexture.needsUpdate = true;
  5713. }
  5714. //
  5715. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  5716. framebufferTexture.generateMipmaps = this.generateMipmaps;
  5717. renderer.copyFramebufferToTexture( framebufferTexture );
  5718. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  5719. }
  5720. clone() {
  5721. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  5722. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  5723. return viewportTextureNode;
  5724. }
  5725. }
  5726. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  5727. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  5728. let sharedDepthbuffer = null;
  5729. class ViewportDepthTextureNode extends ViewportTextureNode {
  5730. static get type() {
  5731. return 'ViewportDepthTextureNode';
  5732. }
  5733. constructor( uvNode = screenUV, levelNode = null ) {
  5734. if ( sharedDepthbuffer === null ) {
  5735. sharedDepthbuffer = new DepthTexture();
  5736. }
  5737. super( uvNode, levelNode, sharedDepthbuffer );
  5738. }
  5739. }
  5740. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  5741. class ViewportDepthNode extends Node {
  5742. static get type() {
  5743. return 'ViewportDepthNode';
  5744. }
  5745. constructor( scope, valueNode = null ) {
  5746. super( 'float' );
  5747. this.scope = scope;
  5748. this.valueNode = valueNode;
  5749. this.isViewportDepthNode = true;
  5750. }
  5751. generate( builder ) {
  5752. const { scope } = this;
  5753. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  5754. return builder.getFragDepth();
  5755. }
  5756. return super.generate( builder );
  5757. }
  5758. setup( { camera } ) {
  5759. const { scope } = this;
  5760. const value = this.valueNode;
  5761. let node = null;
  5762. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  5763. if ( value !== null ) {
  5764. node = depthBase().assign( value );
  5765. }
  5766. } else if ( scope === ViewportDepthNode.DEPTH ) {
  5767. if ( camera.isPerspectiveCamera ) {
  5768. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  5769. } else {
  5770. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5771. }
  5772. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  5773. if ( value !== null ) {
  5774. if ( camera.isPerspectiveCamera ) {
  5775. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  5776. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  5777. } else {
  5778. node = value;
  5779. }
  5780. } else {
  5781. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5782. }
  5783. }
  5784. return node;
  5785. }
  5786. }
  5787. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  5788. ViewportDepthNode.DEPTH = 'depth';
  5789. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  5790. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  5791. // -near maps to 0; -far maps to 1
  5792. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  5793. // maps orthographic depth in [ 0, 1 ] to viewZ
  5794. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  5795. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  5796. // -near maps to 0; -far maps to 1
  5797. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  5798. // maps perspective depth in [ 0, 1 ] to viewZ
  5799. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  5800. // -near maps to 0; -far maps to 1
  5801. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  5802. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  5803. // The final logarithmic depth formula used here is adapted from one described in an
  5804. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  5805. // which was an improvement upon an earlier formula one described in an
  5806. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  5807. // Ulrich's formula is the following:
  5808. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  5809. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  5810. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  5811. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  5812. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  5813. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  5814. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  5815. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  5816. // be used, and ultimately Ulrich's "near plane" version was chosen.
  5817. // Outerra eventually made another improvement to their original "C-constant" variant,
  5818. // but it still does not incorporate the camera near plane (for this version,
  5819. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  5820. // Here we make 4 changes to Ulrich's formula:
  5821. // 1. Clamp the camera near plane so we don't divide by 0.
  5822. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  5823. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  5824. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  5825. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  5826. // so we do the same here, hence the 'viewZ.negate()' call.
  5827. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  5828. near = near.max( 1e-6 ).toVar();
  5829. const numerator = log2( viewZ.negate().div( near ) );
  5830. const denominator = log2( far.div( near ) );
  5831. return numerator.div( denominator );
  5832. };
  5833. // maps logarithmic depth in [ 0, 1 ] to viewZ
  5834. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  5835. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  5836. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  5837. // a negative viewZ).
  5838. const exponent = depth.mul( log( far.div( near ) ) );
  5839. return float( Math.E ).pow( exponent ).mul( near ).negate();
  5840. };
  5841. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  5842. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  5843. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  5844. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  5845. depth.assign = ( value ) => depthBase( value );
  5846. class BuiltinNode extends Node {
  5847. constructor( name ) {
  5848. super( 'float' );
  5849. this.name = name;
  5850. this.isBuiltinNode = true;
  5851. }
  5852. generate( /* builder */ ) {
  5853. return this.name;
  5854. }
  5855. }
  5856. const builtin = nodeProxy( BuiltinNode );
  5857. class ClippingNode extends Node {
  5858. static get type() {
  5859. return 'ClippingNode';
  5860. }
  5861. constructor( scope = ClippingNode.DEFAULT ) {
  5862. super();
  5863. this.scope = scope;
  5864. }
  5865. setup( builder ) {
  5866. super.setup( builder );
  5867. const clippingContext = builder.clippingContext;
  5868. const { intersectionPlanes, unionPlanes } = clippingContext;
  5869. this.hardwareClipping = builder.material.hardwareClipping;
  5870. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  5871. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  5872. } else if ( this.scope === ClippingNode.HARDWARE ) {
  5873. return this.setupHardwareClipping( unionPlanes, builder );
  5874. } else {
  5875. return this.setupDefault( intersectionPlanes, unionPlanes );
  5876. }
  5877. }
  5878. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  5879. return Fn( () => {
  5880. const distanceToPlane = float().toVar( 'distanceToPlane' );
  5881. const distanceGradient = float().toVar( 'distanceToGradient' );
  5882. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  5883. const numUnionPlanes = unionPlanes.length;
  5884. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  5885. const clippingPlanes = uniformArray( unionPlanes );
  5886. Loop( numUnionPlanes, ( { i } ) => {
  5887. const plane = clippingPlanes.element( i );
  5888. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  5889. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  5890. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  5891. } );
  5892. }
  5893. const numIntersectionPlanes = intersectionPlanes.length;
  5894. if ( numIntersectionPlanes > 0 ) {
  5895. const clippingPlanes = uniformArray( intersectionPlanes );
  5896. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  5897. Loop( numIntersectionPlanes, ( { i } ) => {
  5898. const plane = clippingPlanes.element( i );
  5899. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  5900. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  5901. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  5902. } );
  5903. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  5904. }
  5905. diffuseColor.a.mulAssign( clipOpacity );
  5906. diffuseColor.a.equal( 0.0 ).discard();
  5907. } )();
  5908. }
  5909. setupDefault( intersectionPlanes, unionPlanes ) {
  5910. return Fn( () => {
  5911. const numUnionPlanes = unionPlanes.length;
  5912. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  5913. const clippingPlanes = uniformArray( unionPlanes );
  5914. Loop( numUnionPlanes, ( { i } ) => {
  5915. const plane = clippingPlanes.element( i );
  5916. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  5917. } );
  5918. }
  5919. const numIntersectionPlanes = intersectionPlanes.length;
  5920. if ( numIntersectionPlanes > 0 ) {
  5921. const clippingPlanes = uniformArray( intersectionPlanes );
  5922. const clipped = bool( true ).toVar( 'clipped' );
  5923. Loop( numIntersectionPlanes, ( { i } ) => {
  5924. const plane = clippingPlanes.element( i );
  5925. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  5926. } );
  5927. clipped.discard();
  5928. }
  5929. } )();
  5930. }
  5931. setupHardwareClipping( unionPlanes, builder ) {
  5932. const numUnionPlanes = unionPlanes.length;
  5933. builder.enableHardwareClipping( numUnionPlanes );
  5934. return Fn( () => {
  5935. const clippingPlanes = uniformArray( unionPlanes );
  5936. const hw_clip_distances = builtin( builder.getClipDistance() );
  5937. Loop( numUnionPlanes, ( { i } ) => {
  5938. const plane = clippingPlanes.element( i );
  5939. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  5940. hw_clip_distances.element( i ).assign( distance );
  5941. } );
  5942. } )();
  5943. }
  5944. }
  5945. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  5946. ClippingNode.DEFAULT = 'default';
  5947. ClippingNode.HARDWARE = 'hardware';
  5948. const clipping = () => nodeObject( new ClippingNode() );
  5949. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  5950. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  5951. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  5952. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  5953. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  5954. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  5955. } );
  5956. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  5957. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  5958. } );
  5959. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  5960. // Find the discretized derivatives of our coordinates
  5961. const maxDeriv = max$1(
  5962. length( dFdx( position.xyz ) ),
  5963. length( dFdy( position.xyz ) )
  5964. );
  5965. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  5966. // Find two nearest log-discretized noise scales
  5967. const pixScales = vec2(
  5968. exp2( floor( log2( pixScale ) ) ),
  5969. exp2( ceil( log2( pixScale ) ) )
  5970. );
  5971. // Compute alpha thresholds at our two noise scales
  5972. const alpha = vec2(
  5973. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  5974. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  5975. );
  5976. // Factor to interpolate lerp with
  5977. const lerpFactor = fract( log2( pixScale ) );
  5978. // Interpolate alpha threshold from noise at two scales
  5979. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  5980. // Pass into CDF to compute uniformly distrib threshold
  5981. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  5982. const cases = vec3(
  5983. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  5984. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  5985. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  5986. // Find our final, uniformly distributed alpha threshold (ατ)
  5987. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  5988. // Avoids ατ == 0. Could also do ατ =1-ατ
  5989. return clamp( threshold, 1.0e-6, 1.0 );
  5990. } ).setLayout( {
  5991. name: 'getAlphaHashThreshold',
  5992. type: 'float',
  5993. inputs: [
  5994. { name: 'position', type: 'vec3' }
  5995. ]
  5996. } );
  5997. class NodeMaterial extends Material {
  5998. static get type() {
  5999. return 'NodeMaterial';
  6000. }
  6001. get type() {
  6002. return this.constructor.type;
  6003. }
  6004. set type( _value ) { /* */ }
  6005. constructor() {
  6006. super();
  6007. this.isNodeMaterial = true;
  6008. this.forceSinglePass = false;
  6009. this.fog = true;
  6010. this.lights = false;
  6011. this.hardwareClipping = false;
  6012. this.lightsNode = null;
  6013. this.envNode = null;
  6014. this.aoNode = null;
  6015. this.colorNode = null;
  6016. this.normalNode = null;
  6017. this.opacityNode = null;
  6018. this.backdropNode = null;
  6019. this.backdropAlphaNode = null;
  6020. this.alphaTestNode = null;
  6021. this.positionNode = null;
  6022. this.geometryNode = null;
  6023. this.depthNode = null;
  6024. this.shadowPositionNode = null;
  6025. this.receivedShadowNode = null;
  6026. this.castShadowNode = null;
  6027. this.outputNode = null;
  6028. this.mrtNode = null;
  6029. this.fragmentNode = null;
  6030. this.vertexNode = null;
  6031. }
  6032. customProgramCacheKey() {
  6033. return this.type + getCacheKey$1( this );
  6034. }
  6035. build( builder ) {
  6036. this.setup( builder );
  6037. }
  6038. setupObserver( builder ) {
  6039. return new NodeMaterialObserver( builder );
  6040. }
  6041. setup( builder ) {
  6042. builder.context.setupNormal = () => this.setupNormal( builder );
  6043. const renderer = builder.renderer;
  6044. const renderTarget = renderer.getRenderTarget();
  6045. // < VERTEX STAGE >
  6046. builder.addStack();
  6047. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  6048. if ( this.geometryNode !== null ) {
  6049. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  6050. }
  6051. builder.addFlow( 'vertex', builder.removeStack() );
  6052. // < FRAGMENT STAGE >
  6053. builder.addStack();
  6054. let resultNode;
  6055. const clippingNode = this.setupClipping( builder );
  6056. if ( this.depthWrite === true ) {
  6057. // only write depth if depth buffer is configured
  6058. if ( renderTarget !== null ) {
  6059. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  6060. } else {
  6061. if ( renderer.depth === true ) this.setupDepth( builder );
  6062. }
  6063. }
  6064. if ( this.fragmentNode === null ) {
  6065. this.setupDiffuseColor( builder );
  6066. this.setupVariants( builder );
  6067. const outgoingLightNode = this.setupLighting( builder );
  6068. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  6069. // force unsigned floats - useful for RenderTargets
  6070. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  6071. resultNode = this.setupOutput( builder, basicOutput );
  6072. // OUTPUT NODE
  6073. output.assign( resultNode );
  6074. //
  6075. if ( this.outputNode !== null ) resultNode = this.outputNode;
  6076. // MRT
  6077. if ( renderTarget !== null ) {
  6078. const mrt = renderer.getMRT();
  6079. const materialMRT = this.mrtNode;
  6080. if ( mrt !== null ) {
  6081. resultNode = mrt;
  6082. if ( materialMRT !== null ) {
  6083. resultNode = mrt.merge( materialMRT );
  6084. }
  6085. } else if ( materialMRT !== null ) {
  6086. resultNode = materialMRT;
  6087. }
  6088. }
  6089. } else {
  6090. let fragmentNode = this.fragmentNode;
  6091. if ( fragmentNode.isOutputStructNode !== true ) {
  6092. fragmentNode = vec4( fragmentNode );
  6093. }
  6094. resultNode = this.setupOutput( builder, fragmentNode );
  6095. }
  6096. builder.stack.outputNode = resultNode;
  6097. builder.addFlow( 'fragment', builder.removeStack() );
  6098. // < MONITOR >
  6099. builder.monitor = this.setupObserver( builder );
  6100. }
  6101. setupClipping( builder ) {
  6102. if ( builder.clippingContext === null ) return null;
  6103. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  6104. let result = null;
  6105. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  6106. const samples = builder.renderer.samples;
  6107. if ( this.alphaToCoverage && samples > 1 ) {
  6108. // to be added to flow when the color/alpha value has been determined
  6109. result = clippingAlpha();
  6110. } else {
  6111. builder.stack.add( clipping() );
  6112. }
  6113. }
  6114. return result;
  6115. }
  6116. setupHardwareClipping( builder ) {
  6117. this.hardwareClipping = false;
  6118. if ( builder.clippingContext === null ) return;
  6119. const candidateCount = builder.clippingContext.unionPlanes.length;
  6120. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  6121. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  6122. builder.stack.add( hardwareClipping() );
  6123. this.hardwareClipping = true;
  6124. }
  6125. return;
  6126. }
  6127. setupDepth( builder ) {
  6128. const { renderer, camera } = builder;
  6129. // Depth
  6130. let depthNode = this.depthNode;
  6131. if ( depthNode === null ) {
  6132. const mrt = renderer.getMRT();
  6133. if ( mrt && mrt.has( 'depth' ) ) {
  6134. depthNode = mrt.get( 'depth' );
  6135. } else if ( renderer.logarithmicDepthBuffer === true ) {
  6136. if ( camera.isPerspectiveCamera ) {
  6137. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  6138. } else {
  6139. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6140. }
  6141. }
  6142. }
  6143. if ( depthNode !== null ) {
  6144. depth.assign( depthNode ).append();
  6145. }
  6146. }
  6147. setupPosition( builder ) {
  6148. const { object } = builder;
  6149. const geometry = object.geometry;
  6150. builder.addStack();
  6151. // Vertex
  6152. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  6153. morphReference( object ).append();
  6154. }
  6155. if ( object.isSkinnedMesh === true ) {
  6156. skinningReference( object ).append();
  6157. }
  6158. if ( this.displacementMap ) {
  6159. const displacementMap = materialReference( 'displacementMap', 'texture' );
  6160. const displacementScale = materialReference( 'displacementScale', 'float' );
  6161. const displacementBias = materialReference( 'displacementBias', 'float' );
  6162. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  6163. }
  6164. if ( object.isBatchedMesh ) {
  6165. batch( object ).append();
  6166. }
  6167. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  6168. instancedMesh( object ).append();
  6169. }
  6170. if ( this.positionNode !== null ) {
  6171. positionLocal.assign( this.positionNode );
  6172. }
  6173. this.setupHardwareClipping( builder );
  6174. const mvp = modelViewProjection();
  6175. builder.context.vertex = builder.removeStack();
  6176. builder.context.mvp = mvp;
  6177. return mvp;
  6178. }
  6179. setupDiffuseColor( { object, geometry } ) {
  6180. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  6181. // VERTEX COLORS
  6182. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  6183. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  6184. }
  6185. // Instanced colors
  6186. if ( object.instanceColor ) {
  6187. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  6188. colorNode = instanceColor.mul( colorNode );
  6189. }
  6190. if ( object.isBatchedMesh && object._colorsTexture ) {
  6191. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  6192. colorNode = batchColor.mul( colorNode );
  6193. }
  6194. // COLOR
  6195. diffuseColor.assign( colorNode );
  6196. // OPACITY
  6197. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  6198. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  6199. // ALPHA TEST
  6200. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  6201. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  6202. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  6203. }
  6204. // ALPHA HASH
  6205. if ( this.alphaHash === true ) {
  6206. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  6207. }
  6208. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  6209. diffuseColor.a.assign( 1.0 );
  6210. }
  6211. }
  6212. setupVariants( /*builder*/ ) {
  6213. // Interface function.
  6214. }
  6215. setupOutgoingLight() {
  6216. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  6217. }
  6218. setupNormal() {
  6219. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  6220. }
  6221. setupEnvironment( /*builder*/ ) {
  6222. let node = null;
  6223. if ( this.envNode ) {
  6224. node = this.envNode;
  6225. } else if ( this.envMap ) {
  6226. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  6227. }
  6228. return node;
  6229. }
  6230. setupLightMap( builder ) {
  6231. let node = null;
  6232. if ( builder.material.lightMap ) {
  6233. node = new IrradianceNode( materialLightMap );
  6234. }
  6235. return node;
  6236. }
  6237. setupLights( builder ) {
  6238. const materialLightsNode = [];
  6239. //
  6240. const envNode = this.setupEnvironment( builder );
  6241. if ( envNode && envNode.isLightingNode ) {
  6242. materialLightsNode.push( envNode );
  6243. }
  6244. const lightMapNode = this.setupLightMap( builder );
  6245. if ( lightMapNode && lightMapNode.isLightingNode ) {
  6246. materialLightsNode.push( lightMapNode );
  6247. }
  6248. if ( this.aoNode !== null || builder.material.aoMap ) {
  6249. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  6250. materialLightsNode.push( new AONode( aoNode ) );
  6251. }
  6252. let lightsN = this.lightsNode || builder.lightsNode;
  6253. if ( materialLightsNode.length > 0 ) {
  6254. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  6255. }
  6256. return lightsN;
  6257. }
  6258. setupLightingModel( /*builder*/ ) {
  6259. // Interface function.
  6260. }
  6261. setupLighting( builder ) {
  6262. const { material } = builder;
  6263. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  6264. // OUTGOING LIGHT
  6265. const lights = this.lights === true || this.lightsNode !== null;
  6266. const lightsNode = lights ? this.setupLights( builder ) : null;
  6267. let outgoingLightNode = this.setupOutgoingLight( builder );
  6268. if ( lightsNode && lightsNode.getScope().hasLights ) {
  6269. const lightingModel = this.setupLightingModel( builder );
  6270. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  6271. } else if ( backdropNode !== null ) {
  6272. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  6273. }
  6274. // EMISSIVE
  6275. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  6276. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  6277. outgoingLightNode = outgoingLightNode.add( emissive );
  6278. }
  6279. return outgoingLightNode;
  6280. }
  6281. setupOutput( builder, outputNode ) {
  6282. // FOG
  6283. if ( this.fog === true ) {
  6284. const fogNode = builder.fogNode;
  6285. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  6286. }
  6287. return outputNode;
  6288. }
  6289. setDefaultValues( material ) {
  6290. // This approach is to reuse the native refreshUniforms*
  6291. // and turn available the use of features like transmission and environment in core
  6292. for ( const property in material ) {
  6293. const value = material[ property ];
  6294. if ( this[ property ] === undefined ) {
  6295. this[ property ] = value;
  6296. if ( value && value.clone ) this[ property ] = value.clone();
  6297. }
  6298. }
  6299. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  6300. for ( const key in descriptors ) {
  6301. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  6302. descriptors[ key ].get !== undefined ) {
  6303. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  6304. }
  6305. }
  6306. }
  6307. toJSON( meta ) {
  6308. const isRoot = ( meta === undefined || typeof meta === 'string' );
  6309. if ( isRoot ) {
  6310. meta = {
  6311. textures: {},
  6312. images: {},
  6313. nodes: {}
  6314. };
  6315. }
  6316. const data = Material.prototype.toJSON.call( this, meta );
  6317. const nodeChildren = getNodeChildren( this );
  6318. data.inputNodes = {};
  6319. for ( const { property, childNode } of nodeChildren ) {
  6320. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  6321. }
  6322. // TODO: Copied from Object3D.toJSON
  6323. function extractFromCache( cache ) {
  6324. const values = [];
  6325. for ( const key in cache ) {
  6326. const data = cache[ key ];
  6327. delete data.metadata;
  6328. values.push( data );
  6329. }
  6330. return values;
  6331. }
  6332. if ( isRoot ) {
  6333. const textures = extractFromCache( meta.textures );
  6334. const images = extractFromCache( meta.images );
  6335. const nodes = extractFromCache( meta.nodes );
  6336. if ( textures.length > 0 ) data.textures = textures;
  6337. if ( images.length > 0 ) data.images = images;
  6338. if ( nodes.length > 0 ) data.nodes = nodes;
  6339. }
  6340. return data;
  6341. }
  6342. copy( source ) {
  6343. this.lightsNode = source.lightsNode;
  6344. this.envNode = source.envNode;
  6345. this.colorNode = source.colorNode;
  6346. this.normalNode = source.normalNode;
  6347. this.opacityNode = source.opacityNode;
  6348. this.backdropNode = source.backdropNode;
  6349. this.backdropAlphaNode = source.backdropAlphaNode;
  6350. this.alphaTestNode = source.alphaTestNode;
  6351. this.positionNode = source.positionNode;
  6352. this.geometryNode = source.geometryNode;
  6353. this.depthNode = source.depthNode;
  6354. this.shadowPositionNode = source.shadowPositionNode;
  6355. this.receivedShadowNode = source.receivedShadowNode;
  6356. this.castShadowNode = source.castShadowNode;
  6357. this.outputNode = source.outputNode;
  6358. this.mrtNode = source.mrtNode;
  6359. this.fragmentNode = source.fragmentNode;
  6360. this.vertexNode = source.vertexNode;
  6361. return super.copy( source );
  6362. }
  6363. }
  6364. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  6365. class InstancedPointsNodeMaterial extends NodeMaterial {
  6366. static get type() {
  6367. return 'InstancedPointsNodeMaterial';
  6368. }
  6369. constructor( params = {} ) {
  6370. super();
  6371. this.lights = false;
  6372. this.useAlphaToCoverage = true;
  6373. this.useColor = params.vertexColors;
  6374. this.pointWidth = 1;
  6375. this.pointColorNode = null;
  6376. this.pointWidthNode = null;
  6377. this.setDefaultValues( _defaultValues$e );
  6378. this.setValues( params );
  6379. }
  6380. setup( builder ) {
  6381. this.setupShaders( builder );
  6382. super.setup( builder );
  6383. }
  6384. setupShaders( { renderer } ) {
  6385. const useAlphaToCoverage = this.alphaToCoverage;
  6386. const useColor = this.useColor;
  6387. this.vertexNode = Fn( () => {
  6388. const instancePosition = attribute( 'instancePosition' ).xyz;
  6389. // camera space
  6390. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  6391. const aspect = viewport.z.div( viewport.w );
  6392. // clip space
  6393. const clipPos = cameraProjectionMatrix.mul( mvPos );
  6394. // offset in ndc space
  6395. const offset = positionGeometry.xy.toVar();
  6396. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  6397. offset.assign( offset.div( viewport.z ) );
  6398. offset.y.assign( offset.y.mul( aspect ) );
  6399. // back to clip space
  6400. offset.assign( offset.mul( clipPos.w ) );
  6401. //clipPos.xy += offset;
  6402. clipPos.addAssign( vec4( offset, 0, 0 ) );
  6403. return clipPos;
  6404. } )();
  6405. this.fragmentNode = Fn( () => {
  6406. const alpha = float( 1 ).toVar();
  6407. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  6408. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  6409. const dlen = float( len2.fwidth() ).toVar();
  6410. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  6411. } else {
  6412. len2.greaterThan( 1.0 ).discard();
  6413. }
  6414. let pointColorNode;
  6415. if ( this.pointColorNode ) {
  6416. pointColorNode = this.pointColorNode;
  6417. } else {
  6418. if ( useColor ) {
  6419. const instanceColor = attribute( 'instanceColor' );
  6420. pointColorNode = instanceColor.mul( materialColor );
  6421. } else {
  6422. pointColorNode = materialColor;
  6423. }
  6424. }
  6425. alpha.mulAssign( materialOpacity );
  6426. return vec4( pointColorNode, alpha );
  6427. } )();
  6428. }
  6429. get alphaToCoverage() {
  6430. return this.useAlphaToCoverage;
  6431. }
  6432. set alphaToCoverage( value ) {
  6433. if ( this.useAlphaToCoverage !== value ) {
  6434. this.useAlphaToCoverage = value;
  6435. this.needsUpdate = true;
  6436. }
  6437. }
  6438. }
  6439. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  6440. class LineBasicNodeMaterial extends NodeMaterial {
  6441. static get type() {
  6442. return 'LineBasicNodeMaterial';
  6443. }
  6444. constructor( parameters ) {
  6445. super();
  6446. this.isLineBasicNodeMaterial = true;
  6447. this.lights = false;
  6448. this.setDefaultValues( _defaultValues$d );
  6449. this.setValues( parameters );
  6450. }
  6451. }
  6452. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  6453. class LineDashedNodeMaterial extends NodeMaterial {
  6454. static get type() {
  6455. return 'LineDashedNodeMaterial';
  6456. }
  6457. constructor( parameters ) {
  6458. super();
  6459. this.isLineDashedNodeMaterial = true;
  6460. this.lights = false;
  6461. this.setDefaultValues( _defaultValues$c );
  6462. this.dashOffset = 0;
  6463. this.offsetNode = null;
  6464. this.dashScaleNode = null;
  6465. this.dashSizeNode = null;
  6466. this.gapSizeNode = null;
  6467. this.setValues( parameters );
  6468. }
  6469. setupVariants() {
  6470. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  6471. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  6472. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  6473. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  6474. dashSize.assign( dashSizeNode );
  6475. gapSize.assign( gapSizeNode );
  6476. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  6477. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  6478. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  6479. }
  6480. }
  6481. let _sharedFramebuffer = null;
  6482. class ViewportSharedTextureNode extends ViewportTextureNode {
  6483. static get type() {
  6484. return 'ViewportSharedTextureNode';
  6485. }
  6486. constructor( uvNode = screenUV, levelNode = null ) {
  6487. if ( _sharedFramebuffer === null ) {
  6488. _sharedFramebuffer = new FramebufferTexture();
  6489. }
  6490. super( uvNode, levelNode, _sharedFramebuffer );
  6491. }
  6492. updateReference() {
  6493. return this;
  6494. }
  6495. }
  6496. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  6497. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  6498. class Line2NodeMaterial extends NodeMaterial {
  6499. static get type() {
  6500. return 'Line2NodeMaterial';
  6501. }
  6502. constructor( params = {} ) {
  6503. super();
  6504. this.lights = false;
  6505. this.setDefaultValues( _defaultValues$b );
  6506. this.useAlphaToCoverage = true;
  6507. this.useColor = params.vertexColors;
  6508. this.useDash = params.dashed;
  6509. this.useWorldUnits = false;
  6510. this.dashOffset = 0;
  6511. this.lineWidth = 1;
  6512. this.lineColorNode = null;
  6513. this.offsetNode = null;
  6514. this.dashScaleNode = null;
  6515. this.dashSizeNode = null;
  6516. this.gapSizeNode = null;
  6517. this.blending = NoBlending;
  6518. this.setValues( params );
  6519. }
  6520. setup( builder ) {
  6521. this.setupShaders( builder );
  6522. super.setup( builder );
  6523. }
  6524. setupShaders( { renderer } ) {
  6525. const useAlphaToCoverage = this.alphaToCoverage;
  6526. const useColor = this.useColor;
  6527. const useDash = this.dashed;
  6528. const useWorldUnits = this.worldUnits;
  6529. const trimSegment = Fn( ( { start, end } ) => {
  6530. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  6531. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  6532. const nearEstimate = b.mul( - 0.5 ).div( a );
  6533. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  6534. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  6535. } ).setLayout( {
  6536. name: 'trimSegment',
  6537. type: 'vec4',
  6538. inputs: [
  6539. { name: 'start', type: 'vec4' },
  6540. { name: 'end', type: 'vec4' }
  6541. ]
  6542. } );
  6543. this.vertexNode = Fn( () => {
  6544. const instanceStart = attribute( 'instanceStart' );
  6545. const instanceEnd = attribute( 'instanceEnd' );
  6546. // camera space
  6547. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  6548. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  6549. if ( useDash ) {
  6550. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  6551. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  6552. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  6553. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  6554. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  6555. lineDistance = lineDistance.add( offsetNode );
  6556. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  6557. }
  6558. if ( useWorldUnits ) {
  6559. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  6560. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  6561. }
  6562. const aspect = viewport.z.div( viewport.w );
  6563. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  6564. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  6565. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  6566. // perhaps there is a more elegant solution -- WestLangley
  6567. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  6568. If( perspective, () => {
  6569. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  6570. end.assign( trimSegment( { start: start, end: end } ) );
  6571. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  6572. start.assign( trimSegment( { start: end, end: start } ) );
  6573. } );
  6574. } );
  6575. // clip space
  6576. const clipStart = cameraProjectionMatrix.mul( start );
  6577. const clipEnd = cameraProjectionMatrix.mul( end );
  6578. // ndc space
  6579. const ndcStart = clipStart.xyz.div( clipStart.w );
  6580. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  6581. // direction
  6582. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  6583. // account for clip-space aspect ratio
  6584. dir.x.assign( dir.x.mul( aspect ) );
  6585. dir.assign( dir.normalize() );
  6586. const clip = vec4().toVar();
  6587. if ( useWorldUnits ) {
  6588. // get the offset direction as perpendicular to the view vector
  6589. const worldDir = end.xyz.sub( start.xyz ).normalize();
  6590. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  6591. const worldUp = worldDir.cross( tmpFwd ).normalize();
  6592. const worldFwd = worldDir.cross( worldUp );
  6593. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  6594. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  6595. // height offset
  6596. const hw = materialLineWidth.mul( 0.5 );
  6597. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  6598. // don't extend the line if we're rendering dashes because we
  6599. // won't be rendering the endcaps
  6600. if ( ! useDash ) {
  6601. // cap extension
  6602. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  6603. // add width to the box
  6604. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  6605. // endcaps
  6606. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  6607. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  6608. } );
  6609. }
  6610. // project the worldpos
  6611. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  6612. // shift the depth of the projected points so the line
  6613. // segments overlap neatly
  6614. const clipPose = vec3().toVar();
  6615. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  6616. clip.z.assign( clipPose.z.mul( clip.w ) );
  6617. } else {
  6618. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  6619. // undo aspect ratio adjustment
  6620. dir.x.assign( dir.x.div( aspect ) );
  6621. offset.x.assign( offset.x.div( aspect ) );
  6622. // sign flip
  6623. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  6624. // endcaps
  6625. If( positionGeometry.y.lessThan( 0.0 ), () => {
  6626. offset.assign( offset.sub( dir ) );
  6627. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  6628. offset.assign( offset.add( dir ) );
  6629. } );
  6630. // adjust for linewidth
  6631. offset.assign( offset.mul( materialLineWidth ) );
  6632. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  6633. offset.assign( offset.div( viewport.w ) );
  6634. // select end
  6635. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  6636. // back to clip space
  6637. offset.assign( offset.mul( clip.w ) );
  6638. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  6639. }
  6640. return clip;
  6641. } )();
  6642. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  6643. const p13 = p1.sub( p3 );
  6644. const p43 = p4.sub( p3 );
  6645. const p21 = p2.sub( p1 );
  6646. const d1343 = p13.dot( p43 );
  6647. const d4321 = p43.dot( p21 );
  6648. const d1321 = p13.dot( p21 );
  6649. const d4343 = p43.dot( p43 );
  6650. const d2121 = p21.dot( p21 );
  6651. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  6652. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  6653. const mua = numer.div( denom ).clamp();
  6654. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  6655. return vec2( mua, mub );
  6656. } );
  6657. this.colorNode = Fn( () => {
  6658. const vUv = uv();
  6659. if ( useDash ) {
  6660. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  6661. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  6662. dashSize.assign( dashSizeNode );
  6663. gapSize.assign( gapSizeNode );
  6664. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  6665. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  6666. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  6667. }
  6668. const alpha = float( 1 ).toVar( 'alpha' );
  6669. if ( useWorldUnits ) {
  6670. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  6671. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  6672. // Find the closest points on the view ray and the line segment
  6673. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  6674. const lineDir = worldEnd.sub( worldStart );
  6675. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  6676. const p1 = worldStart.add( lineDir.mul( params.x ) );
  6677. const p2 = rayEnd.mul( params.y );
  6678. const delta = p1.sub( p2 );
  6679. const len = delta.length();
  6680. const norm = len.div( materialLineWidth );
  6681. if ( ! useDash ) {
  6682. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  6683. const dnorm = norm.fwidth();
  6684. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  6685. } else {
  6686. norm.greaterThan( 0.5 ).discard();
  6687. }
  6688. }
  6689. } else {
  6690. // round endcaps
  6691. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  6692. const a = vUv.x;
  6693. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  6694. const len2 = a.mul( a ).add( b.mul( b ) );
  6695. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  6696. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  6697. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  6698. } );
  6699. } else {
  6700. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  6701. const a = vUv.x;
  6702. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  6703. const len2 = a.mul( a ).add( b.mul( b ) );
  6704. len2.greaterThan( 1.0 ).discard();
  6705. } );
  6706. }
  6707. }
  6708. let lineColorNode;
  6709. if ( this.lineColorNode ) {
  6710. lineColorNode = this.lineColorNode;
  6711. } else {
  6712. if ( useColor ) {
  6713. const instanceColorStart = attribute( 'instanceColorStart' );
  6714. const instanceColorEnd = attribute( 'instanceColorEnd' );
  6715. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  6716. lineColorNode = instanceColor.mul( materialColor );
  6717. } else {
  6718. lineColorNode = materialColor;
  6719. }
  6720. }
  6721. return vec4( lineColorNode, alpha );
  6722. } )();
  6723. if ( this.transparent ) {
  6724. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  6725. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  6726. }
  6727. }
  6728. get worldUnits() {
  6729. return this.useWorldUnits;
  6730. }
  6731. set worldUnits( value ) {
  6732. if ( this.useWorldUnits !== value ) {
  6733. this.useWorldUnits = value;
  6734. this.needsUpdate = true;
  6735. }
  6736. }
  6737. get dashed() {
  6738. return this.useDash;
  6739. }
  6740. set dashed( value ) {
  6741. if ( this.useDash !== value ) {
  6742. this.useDash = value;
  6743. this.needsUpdate = true;
  6744. }
  6745. }
  6746. get alphaToCoverage() {
  6747. return this.useAlphaToCoverage;
  6748. }
  6749. set alphaToCoverage( value ) {
  6750. if ( this.useAlphaToCoverage !== value ) {
  6751. this.useAlphaToCoverage = value;
  6752. this.needsUpdate = true;
  6753. }
  6754. }
  6755. }
  6756. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  6757. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  6758. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  6759. class MeshNormalNodeMaterial extends NodeMaterial {
  6760. static get type() {
  6761. return 'MeshNormalNodeMaterial';
  6762. }
  6763. constructor( parameters ) {
  6764. super();
  6765. this.lights = false;
  6766. this.isMeshNormalNodeMaterial = true;
  6767. this.setDefaultValues( _defaultValues$a );
  6768. this.setValues( parameters );
  6769. }
  6770. setupDiffuseColor() {
  6771. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  6772. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  6773. }
  6774. }
  6775. class EquirectUVNode extends TempNode {
  6776. static get type() {
  6777. return 'EquirectUVNode';
  6778. }
  6779. constructor( dirNode = positionWorldDirection ) {
  6780. super( 'vec2' );
  6781. this.dirNode = dirNode;
  6782. }
  6783. setup() {
  6784. const dir = this.dirNode;
  6785. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  6786. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  6787. return vec2( u, v );
  6788. }
  6789. }
  6790. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  6791. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  6792. class CubeRenderTarget extends WebGLCubeRenderTarget {
  6793. constructor( size = 1, options = {} ) {
  6794. super( size, options );
  6795. this.isCubeRenderTarget = true;
  6796. }
  6797. fromEquirectangularTexture( renderer, texture$1 ) {
  6798. const currentMinFilter = texture$1.minFilter;
  6799. const currentGenerateMipmaps = texture$1.generateMipmaps;
  6800. texture$1.generateMipmaps = true;
  6801. this.texture.type = texture$1.type;
  6802. this.texture.colorSpace = texture$1.colorSpace;
  6803. this.texture.generateMipmaps = texture$1.generateMipmaps;
  6804. this.texture.minFilter = texture$1.minFilter;
  6805. this.texture.magFilter = texture$1.magFilter;
  6806. const geometry = new BoxGeometry( 5, 5, 5 );
  6807. const uvNode = equirectUV( positionWorldDirection );
  6808. const material = new NodeMaterial();
  6809. material.colorNode = texture( texture$1, uvNode, 0 );
  6810. material.side = BackSide;
  6811. material.blending = NoBlending;
  6812. const mesh = new Mesh( geometry, material );
  6813. const scene = new Scene();
  6814. scene.add( mesh );
  6815. // Avoid blurred poles
  6816. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  6817. const camera = new CubeCamera( 1, 10, this );
  6818. const currentMRT = renderer.getMRT();
  6819. renderer.setMRT( null );
  6820. camera.update( renderer, scene );
  6821. renderer.setMRT( currentMRT );
  6822. texture$1.minFilter = currentMinFilter;
  6823. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  6824. mesh.geometry.dispose();
  6825. mesh.material.dispose();
  6826. return this;
  6827. }
  6828. }
  6829. const _cache$1 = new WeakMap();
  6830. class CubeMapNode extends TempNode {
  6831. static get type() {
  6832. return 'CubeMapNode';
  6833. }
  6834. constructor( envNode ) {
  6835. super( 'vec3' );
  6836. this.envNode = envNode;
  6837. this._cubeTexture = null;
  6838. this._cubeTextureNode = cubeTexture();
  6839. const defaultTexture = new CubeTexture();
  6840. defaultTexture.isRenderTargetTexture = true;
  6841. this._defaultTexture = defaultTexture;
  6842. this.updateBeforeType = NodeUpdateType.RENDER;
  6843. }
  6844. updateBefore( frame ) {
  6845. const { renderer, material } = frame;
  6846. const envNode = this.envNode;
  6847. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  6848. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  6849. if ( texture && texture.isTexture ) {
  6850. const mapping = texture.mapping;
  6851. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  6852. // check for converted cubemap map
  6853. if ( _cache$1.has( texture ) ) {
  6854. const cubeMap = _cache$1.get( texture );
  6855. mapTextureMapping( cubeMap, texture.mapping );
  6856. this._cubeTexture = cubeMap;
  6857. } else {
  6858. // create cube map from equirectangular map
  6859. const image = texture.image;
  6860. if ( isEquirectangularMapReady$1( image ) ) {
  6861. const renderTarget = new CubeRenderTarget( image.height );
  6862. renderTarget.fromEquirectangularTexture( renderer, texture );
  6863. mapTextureMapping( renderTarget.texture, texture.mapping );
  6864. this._cubeTexture = renderTarget.texture;
  6865. _cache$1.set( texture, renderTarget.texture );
  6866. texture.addEventListener( 'dispose', onTextureDispose );
  6867. } else {
  6868. // default cube texture as fallback when equirectangular texture is not yet loaded
  6869. this._cubeTexture = this._defaultTexture;
  6870. }
  6871. }
  6872. //
  6873. this._cubeTextureNode.value = this._cubeTexture;
  6874. } else {
  6875. // envNode already refers to a cube map
  6876. this._cubeTextureNode = this.envNode;
  6877. }
  6878. }
  6879. }
  6880. }
  6881. setup( builder ) {
  6882. this.updateBefore( builder );
  6883. return this._cubeTextureNode;
  6884. }
  6885. }
  6886. function isEquirectangularMapReady$1( image ) {
  6887. if ( image === null || image === undefined ) return false;
  6888. return image.height > 0;
  6889. }
  6890. function onTextureDispose( event ) {
  6891. const texture = event.target;
  6892. texture.removeEventListener( 'dispose', onTextureDispose );
  6893. const renderTarget = _cache$1.get( texture );
  6894. if ( renderTarget !== undefined ) {
  6895. _cache$1.delete( texture );
  6896. renderTarget.dispose();
  6897. }
  6898. }
  6899. function mapTextureMapping( texture, mapping ) {
  6900. if ( mapping === EquirectangularReflectionMapping ) {
  6901. texture.mapping = CubeReflectionMapping;
  6902. } else if ( mapping === EquirectangularRefractionMapping ) {
  6903. texture.mapping = CubeRefractionMapping;
  6904. }
  6905. }
  6906. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  6907. class BasicEnvironmentNode extends LightingNode {
  6908. static get type() {
  6909. return 'BasicEnvironmentNode';
  6910. }
  6911. constructor( envNode = null ) {
  6912. super();
  6913. this.envNode = envNode;
  6914. }
  6915. setup( builder ) {
  6916. // environment property is used in the finish() method of BasicLightingModel
  6917. builder.context.environment = cubeMapNode( this.envNode );
  6918. }
  6919. }
  6920. class BasicLightMapNode extends LightingNode {
  6921. static get type() {
  6922. return 'BasicLightMapNode';
  6923. }
  6924. constructor( lightMapNode = null ) {
  6925. super();
  6926. this.lightMapNode = lightMapNode;
  6927. }
  6928. setup( builder ) {
  6929. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  6930. const RECIPROCAL_PI = float( 1 / Math.PI );
  6931. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  6932. }
  6933. }
  6934. /**
  6935. * Abstract class for implementing lighting models. The module defines
  6936. * multiple methods that concrete lighting models can implement. These
  6937. * methods are executed at different points during the light evaluation
  6938. * process.
  6939. */
  6940. class LightingModel {
  6941. /**
  6942. * This method is intended for setting up lighting model and context data
  6943. * which are later used in the evaluation process.
  6944. *
  6945. * @param {ContextNode} input - The current node context.
  6946. * @param {StackNode} stack - The current stack.
  6947. * @param {NodeBuilder} builder - The current node builder.
  6948. */
  6949. start( /*input, stack, builder*/ ) { }
  6950. /**
  6951. * This method is intended for executing final tasks like final updates
  6952. * to the outgoing light.
  6953. *
  6954. * @param {ContextNode} input - The current node context.
  6955. * @param {StackNode} stack - The current stack.
  6956. * @param {NodeBuilder} builder - The current node builder.
  6957. */
  6958. finish( /*input, stack, builder*/ ) { }
  6959. /**
  6960. * This method is intended for implementing the direct light term and
  6961. * executed during the build process of directional, point and spot light nodes.
  6962. *
  6963. * @param {Object} input - The input data.
  6964. * @param {StackNode} stack - The current stack.
  6965. * @param {NodeBuilder} builder - The current node builder.
  6966. */
  6967. direct( /*input, stack, builder*/ ) { }
  6968. /**
  6969. * This method is intended for implementing the direct light term for
  6970. * rect area light nodes.
  6971. *
  6972. * @param {Object} input - The input data.
  6973. * @param {StackNode} stack - The current stack.
  6974. * @param {NodeBuilder} builder - The current node builder.
  6975. */
  6976. directRectArea( /*input, stack, builder*/ ) {}
  6977. /**
  6978. * This method is intended for implementing the indirect light term.
  6979. *
  6980. * @param {ContextNode} input - The current node context.
  6981. * @param {StackNode} stack - The current stack.
  6982. * @param {NodeBuilder} builder - The current node builder.
  6983. */
  6984. indirect( /*input, stack, builder*/ ) { }
  6985. /**
  6986. * This method is intended for implementing the ambient occlusion term.
  6987. * Unlike other methods, this method must be called manually by the lighting
  6988. * model in its indirect term.
  6989. *
  6990. * @param {ContextNode} input - The current node context.
  6991. * @param {StackNode} stack - The current stack.
  6992. * @param {NodeBuilder} builder - The current node builder.
  6993. */
  6994. ambientOcclusion( /*input, stack, builder*/ ) { }
  6995. }
  6996. class BasicLightingModel extends LightingModel {
  6997. constructor() {
  6998. super();
  6999. }
  7000. indirect( context, stack, builder ) {
  7001. const ambientOcclusion = context.ambientOcclusion;
  7002. const reflectedLight = context.reflectedLight;
  7003. const irradianceLightMap = builder.context.irradianceLightMap;
  7004. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  7005. // accumulation (baked indirect lighting only)
  7006. if ( irradianceLightMap ) {
  7007. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  7008. } else {
  7009. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  7010. }
  7011. // modulation
  7012. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7013. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  7014. }
  7015. finish( context, stack, builder ) {
  7016. const material = builder.material;
  7017. const outgoingLight = context.outgoingLight;
  7018. const envNode = builder.context.environment;
  7019. if ( envNode ) {
  7020. switch ( material.combine ) {
  7021. case MultiplyOperation:
  7022. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  7023. break;
  7024. case MixOperation:
  7025. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  7026. break;
  7027. case AddOperation:
  7028. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  7029. break;
  7030. default:
  7031. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  7032. break;
  7033. }
  7034. }
  7035. }
  7036. }
  7037. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  7038. class MeshBasicNodeMaterial extends NodeMaterial {
  7039. static get type() {
  7040. return 'MeshBasicNodeMaterial';
  7041. }
  7042. constructor( parameters ) {
  7043. super();
  7044. this.isMeshBasicNodeMaterial = true;
  7045. this.lights = true;
  7046. this.setDefaultValues( _defaultValues$9 );
  7047. this.setValues( parameters );
  7048. }
  7049. setupNormal() {
  7050. return normalView; // see #28839
  7051. }
  7052. setupEnvironment( builder ) {
  7053. const envNode = super.setupEnvironment( builder );
  7054. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  7055. }
  7056. setupLightMap( builder ) {
  7057. let node = null;
  7058. if ( builder.material.lightMap ) {
  7059. node = new BasicLightMapNode( materialLightMap );
  7060. }
  7061. return node;
  7062. }
  7063. setupOutgoingLight() {
  7064. return diffuseColor.rgb;
  7065. }
  7066. setupLightingModel() {
  7067. return new BasicLightingModel();
  7068. }
  7069. }
  7070. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  7071. // Original approximation by Christophe Schlick '94
  7072. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  7073. // Optimized variant (presented by Epic at SIGGRAPH '13)
  7074. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  7075. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  7076. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  7077. } ); // validated
  7078. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  7079. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  7080. } ); // validated
  7081. const G_BlinnPhong_Implicit = () => float( 0.25 );
  7082. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  7083. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  7084. } );
  7085. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  7086. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  7087. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  7088. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  7089. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  7090. const G = G_BlinnPhong_Implicit();
  7091. const D = D_BlinnPhong( { dotNH } );
  7092. return F.mul( G ).mul( D );
  7093. } );
  7094. class PhongLightingModel extends BasicLightingModel {
  7095. constructor( specular = true ) {
  7096. super();
  7097. this.specular = specular;
  7098. }
  7099. direct( { lightDirection, lightColor, reflectedLight } ) {
  7100. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  7101. const irradiance = dotNL.mul( lightColor );
  7102. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7103. if ( this.specular === true ) {
  7104. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  7105. }
  7106. }
  7107. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  7108. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7109. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7110. }
  7111. }
  7112. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  7113. class MeshLambertNodeMaterial extends NodeMaterial {
  7114. static get type() {
  7115. return 'MeshLambertNodeMaterial';
  7116. }
  7117. constructor( parameters ) {
  7118. super();
  7119. this.isMeshLambertNodeMaterial = true;
  7120. this.lights = true;
  7121. this.setDefaultValues( _defaultValues$8 );
  7122. this.setValues( parameters );
  7123. }
  7124. setupEnvironment( builder ) {
  7125. const envNode = super.setupEnvironment( builder );
  7126. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  7127. }
  7128. setupLightingModel( /*builder*/ ) {
  7129. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  7130. }
  7131. }
  7132. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  7133. class MeshPhongNodeMaterial extends NodeMaterial {
  7134. static get type() {
  7135. return 'MeshPhongNodeMaterial';
  7136. }
  7137. constructor( parameters ) {
  7138. super();
  7139. this.isMeshPhongNodeMaterial = true;
  7140. this.lights = true;
  7141. this.shininessNode = null;
  7142. this.specularNode = null;
  7143. this.setDefaultValues( _defaultValues$7 );
  7144. this.setValues( parameters );
  7145. }
  7146. setupEnvironment( builder ) {
  7147. const envNode = super.setupEnvironment( builder );
  7148. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  7149. }
  7150. setupLightingModel( /*builder*/ ) {
  7151. return new PhongLightingModel();
  7152. }
  7153. setupVariants() {
  7154. // SHININESS
  7155. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  7156. shininess.assign( shininessNode );
  7157. // SPECULAR COLOR
  7158. const specularNode = this.specularNode || materialSpecular;
  7159. specularColor.assign( specularNode );
  7160. }
  7161. copy( source ) {
  7162. this.shininessNode = source.shininessNode;
  7163. this.specularNode = source.specularNode;
  7164. return super.copy( source );
  7165. }
  7166. }
  7167. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  7168. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7169. return float( 0 );
  7170. }
  7171. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  7172. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  7173. return geometryRoughness;
  7174. } );
  7175. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  7176. const { roughness } = inputs;
  7177. const geometryRoughness = getGeometryRoughness();
  7178. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  7179. roughnessFactor = roughnessFactor.add( geometryRoughness );
  7180. roughnessFactor = roughnessFactor.min( 1.0 );
  7181. return roughnessFactor;
  7182. } );
  7183. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  7184. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  7185. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  7186. const a2 = alpha.pow2();
  7187. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  7188. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  7189. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  7190. } ).setLayout( {
  7191. name: 'V_GGX_SmithCorrelated',
  7192. type: 'float',
  7193. inputs: [
  7194. { name: 'alpha', type: 'float' },
  7195. { name: 'dotNL', type: 'float' },
  7196. { name: 'dotNV', type: 'float' }
  7197. ]
  7198. } ); // validated
  7199. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  7200. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  7201. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  7202. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  7203. const v = div( 0.5, gv.add( gl ) );
  7204. return v.saturate();
  7205. } ).setLayout( {
  7206. name: 'V_GGX_SmithCorrelated_Anisotropic',
  7207. type: 'float',
  7208. inputs: [
  7209. { name: 'alphaT', type: 'float', qualifier: 'in' },
  7210. { name: 'alphaB', type: 'float', qualifier: 'in' },
  7211. { name: 'dotTV', type: 'float', qualifier: 'in' },
  7212. { name: 'dotBV', type: 'float', qualifier: 'in' },
  7213. { name: 'dotTL', type: 'float', qualifier: 'in' },
  7214. { name: 'dotBL', type: 'float', qualifier: 'in' },
  7215. { name: 'dotNV', type: 'float', qualifier: 'in' },
  7216. { name: 'dotNL', type: 'float', qualifier: 'in' }
  7217. ]
  7218. } );
  7219. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  7220. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  7221. // alpha is "roughness squared" in Disney’s reparameterization
  7222. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  7223. const a2 = alpha.pow2();
  7224. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  7225. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  7226. } ).setLayout( {
  7227. name: 'D_GGX',
  7228. type: 'float',
  7229. inputs: [
  7230. { name: 'alpha', type: 'float' },
  7231. { name: 'dotNH', type: 'float' }
  7232. ]
  7233. } ); // validated
  7234. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  7235. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  7236. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  7237. const a2 = alphaT.mul( alphaB );
  7238. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  7239. const v2 = v.dot( v );
  7240. const w2 = a2.div( v2 );
  7241. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  7242. } ).setLayout( {
  7243. name: 'D_GGX_Anisotropic',
  7244. type: 'float',
  7245. inputs: [
  7246. { name: 'alphaT', type: 'float', qualifier: 'in' },
  7247. { name: 'alphaB', type: 'float', qualifier: 'in' },
  7248. { name: 'dotNH', type: 'float', qualifier: 'in' },
  7249. { name: 'dotTH', type: 'float', qualifier: 'in' },
  7250. { name: 'dotBH', type: 'float', qualifier: 'in' }
  7251. ]
  7252. } );
  7253. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  7254. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  7255. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  7256. const normalView = inputs.normalView || transformedNormalView;
  7257. const alpha = roughness.pow2(); // UE4's roughness
  7258. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  7259. const dotNL = normalView.dot( lightDirection ).clamp();
  7260. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  7261. const dotNH = normalView.dot( halfDir ).clamp();
  7262. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  7263. let F = F_Schlick( { f0, f90, dotVH } );
  7264. let V, D;
  7265. if ( defined( USE_IRIDESCENCE ) ) {
  7266. F = iridescence.mix( F, f );
  7267. }
  7268. if ( defined( USE_ANISOTROPY ) ) {
  7269. const dotTL = anisotropyT.dot( lightDirection );
  7270. const dotTV = anisotropyT.dot( positionViewDirection );
  7271. const dotTH = anisotropyT.dot( halfDir );
  7272. const dotBL = anisotropyB.dot( lightDirection );
  7273. const dotBV = anisotropyB.dot( positionViewDirection );
  7274. const dotBH = anisotropyB.dot( halfDir );
  7275. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  7276. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  7277. } else {
  7278. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  7279. D = D_GGX( { alpha, dotNH } );
  7280. }
  7281. return F.mul( V ).mul( D );
  7282. } ); // validated
  7283. // Analytical approximation of the DFG LUT, one half of the
  7284. // split-sum approximation used in indirect specular lighting.
  7285. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  7286. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  7287. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  7288. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  7289. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  7290. const r = roughness.mul( c0 ).add( c1 );
  7291. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  7292. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  7293. return fab;
  7294. } ).setLayout( {
  7295. name: 'DFGApprox',
  7296. type: 'vec2',
  7297. inputs: [
  7298. { name: 'roughness', type: 'float' },
  7299. { name: 'dotNV', type: 'vec3' }
  7300. ]
  7301. } );
  7302. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  7303. const { dotNV, specularColor, specularF90, roughness } = inputs;
  7304. const fab = DFGApprox( { dotNV, roughness } );
  7305. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  7306. } );
  7307. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  7308. const x = dotVH.oneMinus().saturate();
  7309. const x2 = x.mul( x );
  7310. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  7311. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  7312. } ).setLayout( {
  7313. name: 'Schlick_to_F0',
  7314. type: 'vec3',
  7315. inputs: [
  7316. { name: 'f', type: 'vec3' },
  7317. { name: 'f90', type: 'float' },
  7318. { name: 'dotVH', type: 'float' }
  7319. ]
  7320. } );
  7321. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  7322. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  7323. const alpha = roughness.pow2();
  7324. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  7325. const invAlpha = float( 1.0 ).div( alpha );
  7326. const cos2h = dotNH.pow2();
  7327. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  7328. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  7329. } ).setLayout( {
  7330. name: 'D_Charlie',
  7331. type: 'float',
  7332. inputs: [
  7333. { name: 'roughness', type: 'float' },
  7334. { name: 'dotNH', type: 'float' }
  7335. ]
  7336. } );
  7337. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  7338. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  7339. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  7340. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  7341. } ).setLayout( {
  7342. name: 'V_Neubelt',
  7343. type: 'float',
  7344. inputs: [
  7345. { name: 'dotNV', type: 'float' },
  7346. { name: 'dotNL', type: 'float' }
  7347. ]
  7348. } );
  7349. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  7350. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  7351. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  7352. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  7353. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  7354. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  7355. const V = V_Neubelt( { dotNV, dotNL } );
  7356. return sheen.mul( D ).mul( V );
  7357. } );
  7358. // Rect Area Light
  7359. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  7360. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  7361. // code: https://github.com/selfshadow/ltc_code/
  7362. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  7363. const LUT_SIZE = 64.0;
  7364. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  7365. const LUT_BIAS = 0.5 / LUT_SIZE;
  7366. const dotNV = N.dot( V ).saturate();
  7367. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  7368. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  7369. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  7370. return uv;
  7371. } ).setLayout( {
  7372. name: 'LTC_Uv',
  7373. type: 'vec2',
  7374. inputs: [
  7375. { name: 'N', type: 'vec3' },
  7376. { name: 'V', type: 'vec3' },
  7377. { name: 'roughness', type: 'float' }
  7378. ]
  7379. } );
  7380. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  7381. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  7382. // An approximation of the form factor of a horizon-clipped rectangle.
  7383. const l = f.length();
  7384. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  7385. } ).setLayout( {
  7386. name: 'LTC_ClippedSphereFormFactor',
  7387. type: 'float',
  7388. inputs: [
  7389. { name: 'f', type: 'vec3' }
  7390. ]
  7391. } );
  7392. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  7393. const x = v1.dot( v2 );
  7394. const y = x.abs().toVar();
  7395. // rational polynomial approximation to theta / sin( theta ) / 2PI
  7396. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  7397. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  7398. const v = a.div( b );
  7399. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  7400. return v1.cross( v2 ).mul( theta_sintheta );
  7401. } ).setLayout( {
  7402. name: 'LTC_EdgeVectorFormFactor',
  7403. type: 'vec3',
  7404. inputs: [
  7405. { name: 'v1', type: 'vec3' },
  7406. { name: 'v2', type: 'vec3' }
  7407. ]
  7408. } );
  7409. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  7410. // bail if point is on back side of plane of light
  7411. // assumes ccw winding order of light vertices
  7412. const v1 = p1.sub( p0 ).toVar();
  7413. const v2 = p3.sub( p0 ).toVar();
  7414. const lightNormal = v1.cross( v2 );
  7415. const result = vec3().toVar();
  7416. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  7417. // construct orthonormal basis around N
  7418. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  7419. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  7420. // compute transform
  7421. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  7422. // transform rect
  7423. // & project rect onto sphere
  7424. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  7425. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  7426. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  7427. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  7428. // calculate vector form factor
  7429. const vectorFormFactor = vec3( 0 ).toVar();
  7430. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  7431. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  7432. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  7433. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  7434. // adjust for horizon clipping
  7435. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  7436. } );
  7437. return result;
  7438. } ).setLayout( {
  7439. name: 'LTC_Evaluate',
  7440. type: 'vec3',
  7441. inputs: [
  7442. { name: 'N', type: 'vec3' },
  7443. { name: 'V', type: 'vec3' },
  7444. { name: 'P', type: 'vec3' },
  7445. { name: 'mInv', type: 'mat3' },
  7446. { name: 'p0', type: 'vec3' },
  7447. { name: 'p1', type: 'vec3' },
  7448. { name: 'p2', type: 'vec3' },
  7449. { name: 'p3', type: 'vec3' }
  7450. ]
  7451. } );
  7452. // Mipped Bicubic Texture Filtering by N8
  7453. // https://www.shadertoy.com/view/Dl2SDW
  7454. const bC = 1.0 / 6.0;
  7455. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  7456. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  7457. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  7458. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  7459. const g0 = ( a ) => w0( a ).add( w1( a ) );
  7460. const g1 = ( a ) => w2( a ).add( w3( a ) );
  7461. // h0 and h1 are the two offset functions
  7462. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  7463. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  7464. const bicubic = ( textureNode, texelSize, lod ) => {
  7465. const uv = textureNode.uvNode;
  7466. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  7467. const iuv = floor( uvScaled );
  7468. const fuv = fract( uvScaled );
  7469. const g0x = g0( fuv.x );
  7470. const g1x = g1( fuv.x );
  7471. const h0x = h0( fuv.x );
  7472. const h1x = h1( fuv.x );
  7473. const h0y = h0( fuv.y );
  7474. const h1y = h1( fuv.y );
  7475. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  7476. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  7477. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  7478. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  7479. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  7480. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  7481. return a.add( b );
  7482. };
  7483. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  7484. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  7485. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  7486. const fLodSizeInv = div( 1.0, fLodSize );
  7487. const cLodSizeInv = div( 1.0, cLodSize );
  7488. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  7489. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  7490. return fract( lodNode ).mix( fSample, cSample );
  7491. } );
  7492. //
  7493. // Transmission
  7494. //
  7495. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  7496. // Direction of refracted light.
  7497. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  7498. // Compute rotation-independent scaling of the model matrix.
  7499. const modelScale = vec3(
  7500. length( modelMatrix[ 0 ].xyz ),
  7501. length( modelMatrix[ 1 ].xyz ),
  7502. length( modelMatrix[ 2 ].xyz )
  7503. );
  7504. // The thickness is specified in local space.
  7505. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  7506. } ).setLayout( {
  7507. name: 'getVolumeTransmissionRay',
  7508. type: 'vec3',
  7509. inputs: [
  7510. { name: 'n', type: 'vec3' },
  7511. { name: 'v', type: 'vec3' },
  7512. { name: 'thickness', type: 'float' },
  7513. { name: 'ior', type: 'float' },
  7514. { name: 'modelMatrix', type: 'mat4' }
  7515. ]
  7516. } );
  7517. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  7518. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  7519. // an IOR of 1.5 results in the default amount of microfacet refraction.
  7520. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  7521. } ).setLayout( {
  7522. name: 'applyIorToRoughness',
  7523. type: 'float',
  7524. inputs: [
  7525. { name: 'roughness', type: 'float' },
  7526. { name: 'ior', type: 'float' }
  7527. ]
  7528. } );
  7529. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  7530. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  7531. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  7532. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  7533. const transmissionSample = vTexture.uv( fragCoord );
  7534. //const transmissionSample = viewportMipTexture( fragCoord );
  7535. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  7536. return textureBicubic( transmissionSample, lod );
  7537. } );
  7538. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  7539. If( attenuationDistance.notEqual( 0 ), () => {
  7540. // Compute light attenuation using Beer's law.
  7541. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  7542. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  7543. return transmittance;
  7544. } );
  7545. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  7546. return vec3( 1.0 );
  7547. } ).setLayout( {
  7548. name: 'volumeAttenuation',
  7549. type: 'vec3',
  7550. inputs: [
  7551. { name: 'transmissionDistance', type: 'float' },
  7552. { name: 'attenuationColor', type: 'vec3' },
  7553. { name: 'attenuationDistance', type: 'float' }
  7554. ]
  7555. } );
  7556. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  7557. let transmittedLight, transmittance;
  7558. if ( dispersion ) {
  7559. transmittedLight = vec4().toVar();
  7560. transmittance = vec3().toVar();
  7561. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  7562. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  7563. Loop( { start: 0, end: 3 }, ( { i } ) => {
  7564. const ior = iors.element( i );
  7565. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  7566. const refractedRayExit = position.add( transmissionRay );
  7567. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  7568. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  7569. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  7570. refractionCoords.addAssign( 1.0 );
  7571. refractionCoords.divAssign( 2.0 );
  7572. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  7573. // Sample framebuffer to get pixel the refracted ray hits.
  7574. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  7575. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  7576. transmittedLight.a.addAssign( transmissionSample.a );
  7577. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  7578. } );
  7579. transmittedLight.a.divAssign( 3.0 );
  7580. } else {
  7581. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  7582. const refractedRayExit = position.add( transmissionRay );
  7583. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  7584. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  7585. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  7586. refractionCoords.addAssign( 1.0 );
  7587. refractionCoords.divAssign( 2.0 );
  7588. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  7589. // Sample framebuffer to get pixel the refracted ray hits.
  7590. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  7591. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  7592. }
  7593. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  7594. const dotNV = n.dot( v ).clamp();
  7595. // Get the specular component.
  7596. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  7597. dotNV,
  7598. specularColor,
  7599. specularF90,
  7600. roughness
  7601. } ) );
  7602. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  7603. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  7604. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  7605. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  7606. } );
  7607. //
  7608. // Iridescence
  7609. //
  7610. // XYZ to linear-sRGB color space
  7611. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  7612. 3.2404542, - 0.9692660, 0.0556434,
  7613. - 1.5371385, 1.8760108, - 0.2040259,
  7614. - 0.4985314, 0.0415560, 1.0572252
  7615. );
  7616. // Assume air interface for top
  7617. // Note: We don't handle the case fresnel0 == 1
  7618. const Fresnel0ToIor = ( fresnel0 ) => {
  7619. const sqrtF0 = fresnel0.sqrt();
  7620. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  7621. };
  7622. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  7623. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  7624. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  7625. };
  7626. // Fresnel equations for dielectric/dielectric interfaces.
  7627. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  7628. // Evaluation XYZ sensitivity curves in Fourier space
  7629. const evalSensitivity = ( OPD, shift ) => {
  7630. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  7631. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  7632. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  7633. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  7634. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  7635. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  7636. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  7637. const rgb = XYZ_TO_REC709.mul( xyz );
  7638. return rgb;
  7639. };
  7640. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  7641. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  7642. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  7643. // Evaluate the cosTheta on the base layer (Snell law)
  7644. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  7645. // Handle TIR:
  7646. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  7647. If( cosTheta2Sq.lessThan( 0 ), () => {
  7648. return vec3( 1.0 );
  7649. } );
  7650. const cosTheta2 = cosTheta2Sq.sqrt();
  7651. // First interface
  7652. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  7653. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  7654. //const R21 = R12;
  7655. const T121 = R12.oneMinus();
  7656. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  7657. const phi21 = float( Math.PI ).sub( phi12 );
  7658. // Second interface
  7659. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  7660. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  7661. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  7662. const phi23 = vec3(
  7663. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  7664. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  7665. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  7666. );
  7667. // Phase shift
  7668. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  7669. const phi = vec3( phi21 ).add( phi23 );
  7670. // Compound terms
  7671. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  7672. const r123 = R123.sqrt();
  7673. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  7674. // Reflectance term for m = 0 (DC term amplitude)
  7675. const C0 = R12.add( Rs );
  7676. const I = C0.toVar();
  7677. // Reflectance term for m > 0 (pairs of diracs)
  7678. const Cm = Rs.sub( T121 ).toVar();
  7679. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  7680. Cm.mulAssign( r123 );
  7681. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  7682. I.addAssign( Cm.mul( Sm ) );
  7683. } );
  7684. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  7685. return I.max( vec3( 0.0 ) );
  7686. } ).setLayout( {
  7687. name: 'evalIridescence',
  7688. type: 'vec3',
  7689. inputs: [
  7690. { name: 'outsideIOR', type: 'float' },
  7691. { name: 'eta2', type: 'float' },
  7692. { name: 'cosTheta1', type: 'float' },
  7693. { name: 'thinFilmThickness', type: 'float' },
  7694. { name: 'baseF0', type: 'vec3' }
  7695. ]
  7696. } );
  7697. //
  7698. // Sheen
  7699. //
  7700. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  7701. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  7702. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  7703. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  7704. const dotNV = normal.dot( viewDir ).saturate();
  7705. const r2 = roughness.pow2();
  7706. const a = select(
  7707. roughness.lessThan( 0.25 ),
  7708. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  7709. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  7710. );
  7711. const b = select(
  7712. roughness.lessThan( 0.25 ),
  7713. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  7714. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  7715. );
  7716. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  7717. return DG.mul( 1.0 / Math.PI ).saturate();
  7718. } );
  7719. const clearcoatF0 = vec3( 0.04 );
  7720. const clearcoatF90 = float( 1 );
  7721. //
  7722. class PhysicalLightingModel extends LightingModel {
  7723. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  7724. super();
  7725. this.clearcoat = clearcoat;
  7726. this.sheen = sheen;
  7727. this.iridescence = iridescence;
  7728. this.anisotropy = anisotropy;
  7729. this.transmission = transmission;
  7730. this.dispersion = dispersion;
  7731. this.clearcoatRadiance = null;
  7732. this.clearcoatSpecularDirect = null;
  7733. this.clearcoatSpecularIndirect = null;
  7734. this.sheenSpecularDirect = null;
  7735. this.sheenSpecularIndirect = null;
  7736. this.iridescenceFresnel = null;
  7737. this.iridescenceF0 = null;
  7738. }
  7739. start( context ) {
  7740. if ( this.clearcoat === true ) {
  7741. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  7742. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  7743. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  7744. }
  7745. if ( this.sheen === true ) {
  7746. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  7747. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  7748. }
  7749. if ( this.iridescence === true ) {
  7750. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  7751. this.iridescenceFresnel = evalIridescence( {
  7752. outsideIOR: float( 1.0 ),
  7753. eta2: iridescenceIOR,
  7754. cosTheta1: dotNVi,
  7755. thinFilmThickness: iridescenceThickness,
  7756. baseF0: specularColor
  7757. } );
  7758. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  7759. }
  7760. if ( this.transmission === true ) {
  7761. const position = positionWorld;
  7762. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  7763. const n = transformedNormalWorld;
  7764. context.backdrop = getIBLVolumeRefraction(
  7765. n,
  7766. v,
  7767. roughness,
  7768. diffuseColor,
  7769. specularColor,
  7770. specularF90, // specularF90
  7771. position, // positionWorld
  7772. modelWorldMatrix, // modelMatrix
  7773. cameraViewMatrix, // viewMatrix
  7774. cameraProjectionMatrix, // projMatrix
  7775. ior,
  7776. thickness,
  7777. attenuationColor,
  7778. attenuationDistance,
  7779. this.dispersion ? dispersion : null
  7780. );
  7781. context.backdropAlpha = transmission;
  7782. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  7783. }
  7784. }
  7785. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  7786. // Approximates multi-scattering in order to preserve energy.
  7787. // http://www.jcgt.org/published/0008/01/03/
  7788. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  7789. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  7790. const fab = DFGApprox( { roughness, dotNV } );
  7791. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  7792. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  7793. const Ess = fab.x.add( fab.y );
  7794. const Ems = Ess.oneMinus();
  7795. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  7796. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  7797. singleScatter.addAssign( FssEss );
  7798. multiScatter.addAssign( Fms.mul( Ems ) );
  7799. }
  7800. direct( { lightDirection, lightColor, reflectedLight } ) {
  7801. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  7802. const irradiance = dotNL.mul( lightColor );
  7803. if ( this.sheen === true ) {
  7804. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  7805. }
  7806. if ( this.clearcoat === true ) {
  7807. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  7808. const ccIrradiance = dotNLcc.mul( lightColor );
  7809. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  7810. }
  7811. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7812. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  7813. }
  7814. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  7815. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  7816. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  7817. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  7818. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  7819. const N = transformedNormalView;
  7820. const V = positionViewDirection;
  7821. const P = positionView.toVar();
  7822. const uv = LTC_Uv( { N, V, roughness } );
  7823. const t1 = ltc_1.uv( uv ).toVar();
  7824. const t2 = ltc_2.uv( uv ).toVar();
  7825. const mInv = mat3(
  7826. vec3( t1.x, 0, t1.y ),
  7827. vec3( 0, 1, 0 ),
  7828. vec3( t1.z, 0, t1.w )
  7829. ).toVar();
  7830. // LTC Fresnel Approximation by Stephen Hill
  7831. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  7832. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  7833. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  7834. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  7835. }
  7836. indirect( context, stack, builder ) {
  7837. this.indirectDiffuse( context, stack, builder );
  7838. this.indirectSpecular( context, stack, builder );
  7839. this.ambientOcclusion( context, stack, builder );
  7840. }
  7841. indirectDiffuse( { irradiance, reflectedLight } ) {
  7842. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7843. }
  7844. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  7845. if ( this.sheen === true ) {
  7846. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  7847. sheen,
  7848. IBLSheenBRDF( {
  7849. normal: transformedNormalView,
  7850. viewDir: positionViewDirection,
  7851. roughness: sheenRoughness
  7852. } )
  7853. ) );
  7854. }
  7855. if ( this.clearcoat === true ) {
  7856. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  7857. const clearcoatEnv = EnvironmentBRDF( {
  7858. dotNV: dotNVcc,
  7859. specularColor: clearcoatF0,
  7860. specularF90: clearcoatF90,
  7861. roughness: clearcoatRoughness
  7862. } );
  7863. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  7864. }
  7865. // Both indirect specular and indirect diffuse light accumulate here
  7866. const singleScattering = vec3().toVar( 'singleScattering' );
  7867. const multiScattering = vec3().toVar( 'multiScattering' );
  7868. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  7869. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  7870. const totalScattering = singleScattering.add( multiScattering );
  7871. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  7872. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  7873. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  7874. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  7875. }
  7876. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  7877. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  7878. const aoNV = dotNV.add( ambientOcclusion );
  7879. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  7880. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  7881. if ( this.clearcoat === true ) {
  7882. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  7883. }
  7884. if ( this.sheen === true ) {
  7885. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  7886. }
  7887. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7888. reflectedLight.indirectSpecular.mulAssign( aoNode );
  7889. }
  7890. finish( context ) {
  7891. const { outgoingLight } = context;
  7892. if ( this.clearcoat === true ) {
  7893. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  7894. const Fcc = F_Schlick( {
  7895. dotVH: dotNVcc,
  7896. f0: clearcoatF0,
  7897. f90: clearcoatF90
  7898. } );
  7899. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  7900. outgoingLight.assign( clearcoatLight );
  7901. }
  7902. if ( this.sheen === true ) {
  7903. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  7904. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  7905. outgoingLight.assign( sheenLight );
  7906. }
  7907. }
  7908. }
  7909. // These defines must match with PMREMGenerator
  7910. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  7911. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  7912. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  7913. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  7914. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  7915. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  7916. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  7917. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  7918. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  7919. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  7920. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  7921. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  7922. // These shader functions convert between the UV coordinates of a single face of
  7923. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  7924. // sampling a textureCube (not generally normalized ).
  7925. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  7926. const absDirection = vec3( abs( direction ) ).toVar();
  7927. const face = float( - 1.0 ).toVar();
  7928. If( absDirection.x.greaterThan( absDirection.z ), () => {
  7929. If( absDirection.x.greaterThan( absDirection.y ), () => {
  7930. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  7931. } ).Else( () => {
  7932. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  7933. } );
  7934. } ).Else( () => {
  7935. If( absDirection.z.greaterThan( absDirection.y ), () => {
  7936. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  7937. } ).Else( () => {
  7938. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  7939. } );
  7940. } );
  7941. return face;
  7942. } ).setLayout( {
  7943. name: 'getFace',
  7944. type: 'float',
  7945. inputs: [
  7946. { name: 'direction', type: 'vec3' }
  7947. ]
  7948. } );
  7949. // RH coordinate system; PMREM face-indexing convention
  7950. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  7951. const uv = vec2().toVar();
  7952. If( face.equal( 0.0 ), () => {
  7953. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  7954. } ).ElseIf( face.equal( 1.0 ), () => {
  7955. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  7956. } ).ElseIf( face.equal( 2.0 ), () => {
  7957. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  7958. } ).ElseIf( face.equal( 3.0 ), () => {
  7959. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  7960. } ).ElseIf( face.equal( 4.0 ), () => {
  7961. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  7962. } ).Else( () => {
  7963. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  7964. } );
  7965. return mul( 0.5, uv.add( 1.0 ) );
  7966. } ).setLayout( {
  7967. name: 'getUV',
  7968. type: 'vec2',
  7969. inputs: [
  7970. { name: 'direction', type: 'vec3' },
  7971. { name: 'face', type: 'float' }
  7972. ]
  7973. } );
  7974. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  7975. const mip = float( 0.0 ).toVar();
  7976. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  7977. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  7978. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  7979. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  7980. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  7981. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  7982. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  7983. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  7984. } ).Else( () => {
  7985. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  7986. } );
  7987. return mip;
  7988. } ).setLayout( {
  7989. name: 'roughnessToMip',
  7990. type: 'float',
  7991. inputs: [
  7992. { name: 'roughness', type: 'float' }
  7993. ]
  7994. } );
  7995. // RH coordinate system; PMREM face-indexing convention
  7996. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  7997. const uv = uv_immutable.toVar();
  7998. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  7999. const direction = vec3( uv, 1.0 ).toVar();
  8000. If( face.equal( 0.0 ), () => {
  8001. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  8002. } ).ElseIf( face.equal( 1.0 ), () => {
  8003. direction.assign( direction.xzy );
  8004. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  8005. } ).ElseIf( face.equal( 2.0 ), () => {
  8006. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  8007. } ).ElseIf( face.equal( 3.0 ), () => {
  8008. direction.assign( direction.zyx );
  8009. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  8010. } ).ElseIf( face.equal( 4.0 ), () => {
  8011. direction.assign( direction.xzy );
  8012. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  8013. } ).ElseIf( face.equal( 5.0 ), () => {
  8014. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  8015. } );
  8016. return direction;
  8017. } ).setLayout( {
  8018. name: 'getDirection',
  8019. type: 'vec3',
  8020. inputs: [
  8021. { name: 'uv', type: 'vec2' },
  8022. { name: 'face', type: 'float' }
  8023. ]
  8024. } );
  8025. //
  8026. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  8027. const roughness = float( roughness_immutable );
  8028. const sampleDir = vec3( sampleDir_immutable );
  8029. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  8030. const mipF = fract( mip );
  8031. const mipInt = floor( mip );
  8032. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  8033. If( mipF.notEqual( 0.0 ), () => {
  8034. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  8035. color0.assign( mix( color0, color1, mipF ) );
  8036. } );
  8037. return color0;
  8038. } );
  8039. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  8040. const mipInt = float( mipInt_immutable ).toVar();
  8041. const direction = vec3( direction_immutable );
  8042. const face = float( getFace( direction ) ).toVar();
  8043. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  8044. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  8045. const faceSize = float( exp2( mipInt ) ).toVar();
  8046. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  8047. If( face.greaterThan( 2.0 ), () => {
  8048. uv.y.addAssign( faceSize );
  8049. face.subAssign( 3.0 );
  8050. } );
  8051. uv.x.addAssign( face.mul( faceSize ) );
  8052. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  8053. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  8054. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  8055. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  8056. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  8057. } );
  8058. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  8059. const cosTheta = cos( theta );
  8060. // Rodrigues' axis-angle rotation
  8061. const sampleDirection = outputDirection.mul( cosTheta )
  8062. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  8063. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  8064. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  8065. } );
  8066. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  8067. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  8068. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  8069. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  8070. } );
  8071. axis.assign( normalize( axis ) );
  8072. const gl_FragColor = vec3().toVar();
  8073. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  8074. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  8075. If( i.greaterThanEqual( samples ), () => {
  8076. Break();
  8077. } );
  8078. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  8079. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  8080. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  8081. } );
  8082. return vec4( gl_FragColor, 1 );
  8083. } );
  8084. let _generator = null;
  8085. const _cache = new WeakMap();
  8086. function _generateCubeUVSize( imageHeight ) {
  8087. const maxMip = Math.log2( imageHeight ) - 2;
  8088. const texelHeight = 1.0 / imageHeight;
  8089. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  8090. return { texelWidth, texelHeight, maxMip };
  8091. }
  8092. function _getPMREMFromTexture( texture ) {
  8093. let cacheTexture = _cache.get( texture );
  8094. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  8095. if ( pmremVersion !== texture.pmremVersion ) {
  8096. const image = texture.image;
  8097. if ( texture.isCubeTexture ) {
  8098. if ( isCubeMapReady( image ) ) {
  8099. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  8100. } else {
  8101. return null;
  8102. }
  8103. } else {
  8104. if ( isEquirectangularMapReady( image ) ) {
  8105. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  8106. } else {
  8107. return null;
  8108. }
  8109. }
  8110. cacheTexture.pmremVersion = texture.pmremVersion;
  8111. _cache.set( texture, cacheTexture );
  8112. }
  8113. return cacheTexture.texture;
  8114. }
  8115. class PMREMNode extends TempNode {
  8116. static get type() {
  8117. return 'PMREMNode';
  8118. }
  8119. constructor( value, uvNode = null, levelNode = null ) {
  8120. super( 'vec3' );
  8121. this._value = value;
  8122. this._pmrem = null;
  8123. this.uvNode = uvNode;
  8124. this.levelNode = levelNode;
  8125. this._generator = null;
  8126. const defaultTexture = new Texture();
  8127. defaultTexture.isRenderTargetTexture = true;
  8128. this._texture = texture( defaultTexture );
  8129. this._width = uniform( 0 );
  8130. this._height = uniform( 0 );
  8131. this._maxMip = uniform( 0 );
  8132. this.updateBeforeType = NodeUpdateType.RENDER;
  8133. }
  8134. set value( value ) {
  8135. this._value = value;
  8136. this._pmrem = null;
  8137. }
  8138. get value() {
  8139. return this._value;
  8140. }
  8141. updateFromTexture( texture ) {
  8142. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  8143. this._texture.value = texture;
  8144. this._width.value = cubeUVSize.texelWidth;
  8145. this._height.value = cubeUVSize.texelHeight;
  8146. this._maxMip.value = cubeUVSize.maxMip;
  8147. }
  8148. updateBefore() {
  8149. let pmrem = this._pmrem;
  8150. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  8151. const texture = this._value;
  8152. if ( pmremVersion !== texture.pmremVersion ) {
  8153. if ( texture.isPMREMTexture === true ) {
  8154. pmrem = texture;
  8155. } else {
  8156. pmrem = _getPMREMFromTexture( texture );
  8157. }
  8158. if ( pmrem !== null ) {
  8159. this._pmrem = pmrem;
  8160. this.updateFromTexture( pmrem );
  8161. }
  8162. }
  8163. }
  8164. setup( builder ) {
  8165. if ( _generator === null ) {
  8166. _generator = builder.createPMREMGenerator();
  8167. }
  8168. //
  8169. this.updateBefore( builder );
  8170. //
  8171. let uvNode = this.uvNode;
  8172. if ( uvNode === null && builder.context.getUV ) {
  8173. uvNode = builder.context.getUV( this );
  8174. }
  8175. //
  8176. const texture = this.value;
  8177. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  8178. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8179. }
  8180. //
  8181. let levelNode = this.levelNode;
  8182. if ( levelNode === null && builder.context.getTextureLevel ) {
  8183. levelNode = builder.context.getTextureLevel( this );
  8184. }
  8185. //
  8186. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  8187. }
  8188. }
  8189. function isCubeMapReady( image ) {
  8190. if ( image === null || image === undefined ) return false;
  8191. let count = 0;
  8192. const length = 6;
  8193. for ( let i = 0; i < length; i ++ ) {
  8194. if ( image[ i ] !== undefined ) count ++;
  8195. }
  8196. return count === length;
  8197. }
  8198. function isEquirectangularMapReady( image ) {
  8199. if ( image === null || image === undefined ) return false;
  8200. return image.height > 0;
  8201. }
  8202. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  8203. const _envNodeCache = new WeakMap();
  8204. class EnvironmentNode extends LightingNode {
  8205. static get type() {
  8206. return 'EnvironmentNode';
  8207. }
  8208. constructor( envNode = null ) {
  8209. super();
  8210. this.envNode = envNode;
  8211. }
  8212. setup( builder ) {
  8213. const { material } = builder;
  8214. let envNode = this.envNode;
  8215. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  8216. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  8217. let cacheEnvNode = _envNodeCache.get( value );
  8218. if ( cacheEnvNode === undefined ) {
  8219. cacheEnvNode = pmremTexture( value );
  8220. _envNodeCache.set( value, cacheEnvNode );
  8221. }
  8222. envNode = cacheEnvNode;
  8223. }
  8224. //
  8225. const envMap = material.envMap;
  8226. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  8227. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  8228. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  8229. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  8230. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  8231. const isolateRadiance = cache( radiance );
  8232. const isolateIrradiance = cache( irradiance );
  8233. //
  8234. builder.context.radiance.addAssign( isolateRadiance );
  8235. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  8236. //
  8237. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  8238. if ( clearcoatRadiance ) {
  8239. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  8240. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  8241. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  8242. }
  8243. }
  8244. }
  8245. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  8246. let reflectVec = null;
  8247. return {
  8248. getUV: () => {
  8249. if ( reflectVec === null ) {
  8250. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  8251. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  8252. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  8253. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  8254. }
  8255. return reflectVec;
  8256. },
  8257. getTextureLevel: () => {
  8258. return roughnessNode;
  8259. }
  8260. };
  8261. };
  8262. const createIrradianceContext = ( normalWorldNode ) => {
  8263. return {
  8264. getUV: () => {
  8265. return normalWorldNode;
  8266. },
  8267. getTextureLevel: () => {
  8268. return float( 1.0 );
  8269. }
  8270. };
  8271. };
  8272. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  8273. class MeshStandardNodeMaterial extends NodeMaterial {
  8274. static get type() {
  8275. return 'MeshStandardNodeMaterial';
  8276. }
  8277. constructor( parameters ) {
  8278. super();
  8279. this.isMeshStandardNodeMaterial = true;
  8280. this.lights = true;
  8281. this.emissiveNode = null;
  8282. this.metalnessNode = null;
  8283. this.roughnessNode = null;
  8284. this.setDefaultValues( _defaultValues$6 );
  8285. this.setValues( parameters );
  8286. }
  8287. setupEnvironment( builder ) {
  8288. let envNode = super.setupEnvironment( builder );
  8289. if ( envNode === null && builder.environmentNode ) {
  8290. envNode = builder.environmentNode;
  8291. }
  8292. return envNode ? new EnvironmentNode( envNode ) : null;
  8293. }
  8294. setupLightingModel( /*builder*/ ) {
  8295. return new PhysicalLightingModel();
  8296. }
  8297. setupSpecular() {
  8298. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  8299. specularColor.assign( specularColorNode );
  8300. specularF90.assign( 1.0 );
  8301. }
  8302. setupVariants() {
  8303. // METALNESS
  8304. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  8305. metalness.assign( metalnessNode );
  8306. // ROUGHNESS
  8307. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  8308. roughnessNode = getRoughness( { roughness: roughnessNode } );
  8309. roughness.assign( roughnessNode );
  8310. // SPECULAR COLOR
  8311. this.setupSpecular();
  8312. // DIFFUSE COLOR
  8313. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  8314. }
  8315. copy( source ) {
  8316. this.emissiveNode = source.emissiveNode;
  8317. this.metalnessNode = source.metalnessNode;
  8318. this.roughnessNode = source.roughnessNode;
  8319. return super.copy( source );
  8320. }
  8321. }
  8322. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  8323. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  8324. static get type() {
  8325. return 'MeshPhysicalNodeMaterial';
  8326. }
  8327. constructor( parameters ) {
  8328. super();
  8329. this.isMeshPhysicalNodeMaterial = true;
  8330. this.clearcoatNode = null;
  8331. this.clearcoatRoughnessNode = null;
  8332. this.clearcoatNormalNode = null;
  8333. this.sheenNode = null;
  8334. this.sheenRoughnessNode = null;
  8335. this.iridescenceNode = null;
  8336. this.iridescenceIORNode = null;
  8337. this.iridescenceThicknessNode = null;
  8338. this.specularIntensityNode = null;
  8339. this.specularColorNode = null;
  8340. this.iorNode = null;
  8341. this.transmissionNode = null;
  8342. this.thicknessNode = null;
  8343. this.attenuationDistanceNode = null;
  8344. this.attenuationColorNode = null;
  8345. this.dispersionNode = null;
  8346. this.anisotropyNode = null;
  8347. this.setDefaultValues( _defaultValues$5 );
  8348. this.setValues( parameters );
  8349. }
  8350. get useClearcoat() {
  8351. return this.clearcoat > 0 || this.clearcoatNode !== null;
  8352. }
  8353. get useIridescence() {
  8354. return this.iridescence > 0 || this.iridescenceNode !== null;
  8355. }
  8356. get useSheen() {
  8357. return this.sheen > 0 || this.sheenNode !== null;
  8358. }
  8359. get useAnisotropy() {
  8360. return this.anisotropy > 0 || this.anisotropyNode !== null;
  8361. }
  8362. get useTransmission() {
  8363. return this.transmission > 0 || this.transmissionNode !== null;
  8364. }
  8365. get useDispersion() {
  8366. return this.dispersion > 0 || this.dispersionNode !== null;
  8367. }
  8368. setupSpecular() {
  8369. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  8370. ior.assign( iorNode );
  8371. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  8372. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  8373. }
  8374. setupLightingModel( /*builder*/ ) {
  8375. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  8376. }
  8377. setupVariants( builder ) {
  8378. super.setupVariants( builder );
  8379. // CLEARCOAT
  8380. if ( this.useClearcoat ) {
  8381. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  8382. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  8383. clearcoat.assign( clearcoatNode );
  8384. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  8385. }
  8386. // SHEEN
  8387. if ( this.useSheen ) {
  8388. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  8389. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  8390. sheen.assign( sheenNode );
  8391. sheenRoughness.assign( sheenRoughnessNode );
  8392. }
  8393. // IRIDESCENCE
  8394. if ( this.useIridescence ) {
  8395. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  8396. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  8397. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  8398. iridescence.assign( iridescenceNode );
  8399. iridescenceIOR.assign( iridescenceIORNode );
  8400. iridescenceThickness.assign( iridescenceThicknessNode );
  8401. }
  8402. // ANISOTROPY
  8403. if ( this.useAnisotropy ) {
  8404. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  8405. anisotropy.assign( anisotropyV.length() );
  8406. If( anisotropy.equal( 0.0 ), () => {
  8407. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  8408. } ).Else( () => {
  8409. anisotropyV.divAssign( vec2( anisotropy ) );
  8410. anisotropy.assign( anisotropy.saturate() );
  8411. } );
  8412. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  8413. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  8414. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  8415. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  8416. }
  8417. // TRANSMISSION
  8418. if ( this.useTransmission ) {
  8419. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  8420. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  8421. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  8422. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  8423. transmission.assign( transmissionNode );
  8424. thickness.assign( thicknessNode );
  8425. attenuationDistance.assign( attenuationDistanceNode );
  8426. attenuationColor.assign( attenuationColorNode );
  8427. if ( this.useDispersion ) {
  8428. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  8429. dispersion.assign( dispersionNode );
  8430. }
  8431. }
  8432. }
  8433. setupClearcoatNormal() {
  8434. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  8435. }
  8436. setup( builder ) {
  8437. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  8438. super.setup( builder );
  8439. }
  8440. copy( source ) {
  8441. this.clearcoatNode = source.clearcoatNode;
  8442. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  8443. this.clearcoatNormalNode = source.clearcoatNormalNode;
  8444. this.sheenNode = source.sheenNode;
  8445. this.sheenRoughnessNode = source.sheenRoughnessNode;
  8446. this.iridescenceNode = source.iridescenceNode;
  8447. this.iridescenceIORNode = source.iridescenceIORNode;
  8448. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  8449. this.specularIntensityNode = source.specularIntensityNode;
  8450. this.specularColorNode = source.specularColorNode;
  8451. this.transmissionNode = source.transmissionNode;
  8452. this.thicknessNode = source.thicknessNode;
  8453. this.attenuationDistanceNode = source.attenuationDistanceNode;
  8454. this.attenuationColorNode = source.attenuationColorNode;
  8455. this.dispersionNode = source.dispersionNode;
  8456. this.anisotropyNode = source.anisotropyNode;
  8457. return super.copy( source );
  8458. }
  8459. }
  8460. class SSSLightingModel extends PhysicalLightingModel {
  8461. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  8462. super( useClearcoat, useSheen, useIridescence );
  8463. this.useSSS = useSSS;
  8464. }
  8465. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  8466. if ( this.useSSS === true ) {
  8467. const material = builder.material;
  8468. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  8469. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  8470. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  8471. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  8472. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  8473. }
  8474. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  8475. }
  8476. }
  8477. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  8478. static get type() {
  8479. return 'MeshSSSNodeMaterial';
  8480. }
  8481. constructor( parameters ) {
  8482. super( parameters );
  8483. this.thicknessColorNode = null;
  8484. this.thicknessDistortionNode = float( 0.1 );
  8485. this.thicknessAmbientNode = float( 0.0 );
  8486. this.thicknessAttenuationNode = float( .1 );
  8487. this.thicknessPowerNode = float( 2.0 );
  8488. this.thicknessScaleNode = float( 10.0 );
  8489. }
  8490. get useSSS() {
  8491. return this.thicknessColorNode !== null;
  8492. }
  8493. setupLightingModel( /*builder*/ ) {
  8494. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  8495. }
  8496. copy( source ) {
  8497. this.thicknessColorNode = source.thicknessColorNode;
  8498. this.thicknessDistortionNode = source.thicknessDistortionNode;
  8499. this.thicknessAmbientNode = source.thicknessAmbientNode;
  8500. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  8501. this.thicknessPowerNode = source.thicknessPowerNode;
  8502. this.thicknessScaleNode = source.thicknessScaleNode;
  8503. return super.copy( source );
  8504. }
  8505. }
  8506. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  8507. // dotNL will be from -1.0 to 1.0
  8508. const dotNL = normal.dot( lightDirection );
  8509. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  8510. if ( builder.material.gradientMap ) {
  8511. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  8512. return vec3( gradientMap.r );
  8513. } else {
  8514. const fw = coord.fwidth().mul( 0.5 );
  8515. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  8516. }
  8517. } );
  8518. class ToonLightingModel extends LightingModel {
  8519. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  8520. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  8521. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  8522. }
  8523. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  8524. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  8525. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  8526. }
  8527. }
  8528. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  8529. class MeshToonNodeMaterial extends NodeMaterial {
  8530. static get type() {
  8531. return 'MeshToonNodeMaterial';
  8532. }
  8533. constructor( parameters ) {
  8534. super();
  8535. this.isMeshToonNodeMaterial = true;
  8536. this.lights = true;
  8537. this.setDefaultValues( _defaultValues$4 );
  8538. this.setValues( parameters );
  8539. }
  8540. setupLightingModel( /*builder*/ ) {
  8541. return new ToonLightingModel();
  8542. }
  8543. }
  8544. class MatcapUVNode extends TempNode {
  8545. static get type() {
  8546. return 'MatcapUVNode';
  8547. }
  8548. constructor() {
  8549. super( 'vec2' );
  8550. }
  8551. setup() {
  8552. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  8553. const y = positionViewDirection.cross( x );
  8554. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  8555. }
  8556. }
  8557. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  8558. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  8559. class MeshMatcapNodeMaterial extends NodeMaterial {
  8560. static get type() {
  8561. return 'MeshMatcapNodeMaterial';
  8562. }
  8563. constructor( parameters ) {
  8564. super();
  8565. this.lights = false;
  8566. this.isMeshMatcapNodeMaterial = true;
  8567. this.setDefaultValues( _defaultValues$3 );
  8568. this.setValues( parameters );
  8569. }
  8570. setupVariants( builder ) {
  8571. const uv = matcapUV;
  8572. let matcapColor;
  8573. if ( builder.material.matcap ) {
  8574. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  8575. } else {
  8576. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  8577. }
  8578. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  8579. }
  8580. }
  8581. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  8582. class PointsNodeMaterial extends NodeMaterial {
  8583. static get type() {
  8584. return 'PointsNodeMaterial';
  8585. }
  8586. constructor( parameters ) {
  8587. super();
  8588. this.isPointsNodeMaterial = true;
  8589. this.lights = false;
  8590. this.transparent = true;
  8591. this.sizeNode = null;
  8592. this.setDefaultValues( _defaultValues$2 );
  8593. this.setValues( parameters );
  8594. }
  8595. copy( source ) {
  8596. this.sizeNode = source.sizeNode;
  8597. return super.copy( source );
  8598. }
  8599. }
  8600. class RotateNode extends TempNode {
  8601. static get type() {
  8602. return 'RotateNode';
  8603. }
  8604. constructor( positionNode, rotationNode ) {
  8605. super();
  8606. this.positionNode = positionNode;
  8607. this.rotationNode = rotationNode;
  8608. }
  8609. getNodeType( builder ) {
  8610. return this.positionNode.getNodeType( builder );
  8611. }
  8612. setup( builder ) {
  8613. const { rotationNode, positionNode } = this;
  8614. const nodeType = this.getNodeType( builder );
  8615. if ( nodeType === 'vec2' ) {
  8616. const cosAngle = rotationNode.cos();
  8617. const sinAngle = rotationNode.sin();
  8618. const rotationMatrix = mat2(
  8619. cosAngle, sinAngle,
  8620. sinAngle.negate(), cosAngle
  8621. );
  8622. return rotationMatrix.mul( positionNode );
  8623. } else {
  8624. const rotation = rotationNode;
  8625. const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  8626. const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  8627. const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  8628. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  8629. }
  8630. }
  8631. }
  8632. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  8633. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  8634. class SpriteNodeMaterial extends NodeMaterial {
  8635. static get type() {
  8636. return 'SpriteNodeMaterial';
  8637. }
  8638. constructor( parameters ) {
  8639. super();
  8640. this.isSpriteNodeMaterial = true;
  8641. this.lights = false;
  8642. this._useSizeAttenuation = true;
  8643. this.positionNode = null;
  8644. this.rotationNode = null;
  8645. this.scaleNode = null;
  8646. this.setDefaultValues( _defaultValues$1 );
  8647. this.setValues( parameters );
  8648. }
  8649. setupPosition( { object, camera, context } ) {
  8650. const sizeAttenuation = this.sizeAttenuation;
  8651. // < VERTEX STAGE >
  8652. const { positionNode, rotationNode, scaleNode } = this;
  8653. const vertex = positionLocal;
  8654. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  8655. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  8656. if ( scaleNode !== null ) {
  8657. scale = scale.mul( scaleNode );
  8658. }
  8659. if ( ! sizeAttenuation ) {
  8660. if ( camera.isPerspectiveCamera ) {
  8661. scale = scale.mul( mvPosition.z.negate() );
  8662. } else {
  8663. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  8664. scale = scale.mul( orthoScale.mul( 2 ) );
  8665. }
  8666. }
  8667. let alignedPosition = vertex.xy;
  8668. if ( object.center && object.center.isVector2 === true ) {
  8669. const center = reference$1( 'center', 'vec2' );
  8670. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  8671. }
  8672. alignedPosition = alignedPosition.mul( scale );
  8673. const rotation = float( rotationNode || materialRotation );
  8674. const rotatedPosition = rotate( alignedPosition, rotation );
  8675. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  8676. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  8677. context.vertex = vertex;
  8678. return modelViewProjection;
  8679. }
  8680. copy( source ) {
  8681. this.positionNode = source.positionNode;
  8682. this.rotationNode = source.rotationNode;
  8683. this.scaleNode = source.scaleNode;
  8684. return super.copy( source );
  8685. }
  8686. get sizeAttenuation() {
  8687. return this._useSizeAttenuation;
  8688. }
  8689. set sizeAttenuation( value ) {
  8690. if ( this._useSizeAttenuation !== value ) {
  8691. this._useSizeAttenuation = value;
  8692. this.needsUpdate = true;
  8693. }
  8694. }
  8695. }
  8696. class ShadowMaskModel extends LightingModel {
  8697. constructor() {
  8698. super();
  8699. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  8700. }
  8701. direct( { shadowMask } ) {
  8702. this.shadowNode.mulAssign( shadowMask );
  8703. }
  8704. finish( context ) {
  8705. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  8706. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  8707. }
  8708. }
  8709. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  8710. class ShadowNodeMaterial extends NodeMaterial {
  8711. static get type() {
  8712. return 'ShadowNodeMaterial';
  8713. }
  8714. constructor( parameters ) {
  8715. super();
  8716. this.isShadowNodeMaterial = true;
  8717. this.lights = true;
  8718. this.setDefaultValues( _defaultValues );
  8719. this.setValues( parameters );
  8720. }
  8721. setupLightingModel( /*builder*/ ) {
  8722. return new ShadowMaskModel();
  8723. }
  8724. }
  8725. const normal = Fn( ( { texture, uv } ) => {
  8726. const epsilon = 0.0001;
  8727. const ret = vec3().toVar();
  8728. If( uv.x.lessThan( epsilon ), () => {
  8729. ret.assign( vec3( 1, 0, 0 ) );
  8730. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  8731. ret.assign( vec3( 0, 1, 0 ) );
  8732. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  8733. ret.assign( vec3( 0, 0, 1 ) );
  8734. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  8735. ret.assign( vec3( - 1, 0, 0 ) );
  8736. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  8737. ret.assign( vec3( 0, - 1, 0 ) );
  8738. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  8739. ret.assign( vec3( 0, 0, - 1 ) );
  8740. } ).Else( () => {
  8741. const step = 0.01;
  8742. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  8743. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  8744. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  8745. ret.assign( vec3( x, y, z ) );
  8746. } );
  8747. return ret.normalize();
  8748. } );
  8749. class Texture3DNode extends TextureNode {
  8750. static get type() {
  8751. return 'Texture3DNode';
  8752. }
  8753. constructor( value, uvNode = null, levelNode = null ) {
  8754. super( value, uvNode, levelNode );
  8755. this.isTexture3DNode = true;
  8756. }
  8757. getInputType( /*builder*/ ) {
  8758. return 'texture3D';
  8759. }
  8760. getDefaultUV() {
  8761. return vec3( 0.5, 0.5, 0.5 );
  8762. }
  8763. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  8764. setupUV( builder, uvNode ) {
  8765. return uvNode;
  8766. }
  8767. generateUV( builder, uvNode ) {
  8768. return uvNode.build( builder, 'vec3' );
  8769. }
  8770. normal( uvNode ) {
  8771. return normal( { texture: this, uv: uvNode } );
  8772. }
  8773. }
  8774. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  8775. class VolumeNodeMaterial extends NodeMaterial {
  8776. static get type() {
  8777. return 'VolumeNodeMaterial';
  8778. }
  8779. constructor( params = {} ) {
  8780. super();
  8781. this.lights = false;
  8782. this.isVolumeNodeMaterial = true;
  8783. this.testNode = null;
  8784. this.setValues( params );
  8785. }
  8786. setup( builder ) {
  8787. const map = texture3D( this.map, null, 0 );
  8788. const hitBox = Fn( ( { orig, dir } ) => {
  8789. const box_min = vec3( - 0.5 );
  8790. const box_max = vec3( 0.5 );
  8791. const inv_dir = dir.reciprocal();
  8792. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  8793. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  8794. const tmin = min$1( tmin_tmp, tmax_tmp );
  8795. const tmax = max$1( tmin_tmp, tmax_tmp );
  8796. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  8797. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  8798. return vec2( t0, t1 );
  8799. } );
  8800. this.fragmentNode = Fn( () => {
  8801. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  8802. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  8803. const rayDir = vDirection.normalize();
  8804. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  8805. bounds.x.greaterThan( bounds.y ).discard();
  8806. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  8807. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  8808. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  8809. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  8810. delta.divAssign( materialReference( 'steps', 'float' ) );
  8811. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  8812. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  8813. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  8814. if ( this.testNode !== null ) {
  8815. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  8816. } else {
  8817. // default to show surface of mesh
  8818. ac.a.assign( 1 );
  8819. Break();
  8820. }
  8821. p.addAssign( rayDir.mul( delta ) );
  8822. } );
  8823. ac.a.equal( 0 ).discard();
  8824. return vec4( ac );
  8825. } )();
  8826. super.setup( builder );
  8827. }
  8828. }
  8829. class Animation {
  8830. constructor( nodes, info ) {
  8831. this.nodes = nodes;
  8832. this.info = info;
  8833. this._context = self;
  8834. this._animationLoop = null;
  8835. this._requestId = null;
  8836. }
  8837. start() {
  8838. const update = ( time, frame ) => {
  8839. this._requestId = this._context.requestAnimationFrame( update );
  8840. if ( this.info.autoReset === true ) this.info.reset();
  8841. this.nodes.nodeFrame.update();
  8842. this.info.frame = this.nodes.nodeFrame.frameId;
  8843. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  8844. };
  8845. update();
  8846. }
  8847. stop() {
  8848. this._context.cancelAnimationFrame( this._requestId );
  8849. this._requestId = null;
  8850. }
  8851. setAnimationLoop( callback ) {
  8852. this._animationLoop = callback;
  8853. }
  8854. setContext( context ) {
  8855. this._context = context;
  8856. }
  8857. dispose() {
  8858. this.stop();
  8859. }
  8860. }
  8861. class ChainMap {
  8862. constructor() {
  8863. this.weakMap = new WeakMap();
  8864. }
  8865. get( keys ) {
  8866. let map = this.weakMap;
  8867. for ( let i = 0; i < keys.length; i ++ ) {
  8868. map = map.get( keys[ i ] );
  8869. if ( map === undefined ) return undefined;
  8870. }
  8871. return map.get( keys[ keys.length - 1 ] );
  8872. }
  8873. set( keys, value ) {
  8874. let map = this.weakMap;
  8875. for ( let i = 0; i < keys.length; i ++ ) {
  8876. const key = keys[ i ];
  8877. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  8878. map = map.get( key );
  8879. }
  8880. return map.set( keys[ keys.length - 1 ], value );
  8881. }
  8882. delete( keys ) {
  8883. let map = this.weakMap;
  8884. for ( let i = 0; i < keys.length; i ++ ) {
  8885. map = map.get( keys[ i ] );
  8886. if ( map === undefined ) return false;
  8887. }
  8888. return map.delete( keys[ keys.length - 1 ] );
  8889. }
  8890. }
  8891. let _id$8 = 0;
  8892. function getKeys( obj ) {
  8893. const keys = Object.keys( obj );
  8894. let proto = Object.getPrototypeOf( obj );
  8895. while ( proto ) {
  8896. const descriptors = Object.getOwnPropertyDescriptors( proto );
  8897. for ( const key in descriptors ) {
  8898. if ( descriptors[ key ] !== undefined ) {
  8899. const descriptor = descriptors[ key ];
  8900. if ( descriptor && typeof descriptor.get === 'function' ) {
  8901. keys.push( key );
  8902. }
  8903. }
  8904. }
  8905. proto = Object.getPrototypeOf( proto );
  8906. }
  8907. return keys;
  8908. }
  8909. class RenderObject {
  8910. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  8911. this._nodes = nodes;
  8912. this._geometries = geometries;
  8913. this.id = _id$8 ++;
  8914. this.renderer = renderer;
  8915. this.object = object;
  8916. this.material = material;
  8917. this.scene = scene;
  8918. this.camera = camera;
  8919. this.lightsNode = lightsNode;
  8920. this.context = renderContext;
  8921. this.geometry = object.geometry;
  8922. this.version = material.version;
  8923. this.drawRange = null;
  8924. this.attributes = null;
  8925. this.pipeline = null;
  8926. this.vertexBuffers = null;
  8927. this.drawParams = null;
  8928. this.bundle = null;
  8929. this.clippingContext = clippingContext;
  8930. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  8931. this.initialNodesCacheKey = this.getDynamicCacheKey();
  8932. this.initialCacheKey = this.getCacheKey();
  8933. this._nodeBuilderState = null;
  8934. this._bindings = null;
  8935. this._monitor = null;
  8936. this.onDispose = null;
  8937. this.isRenderObject = true;
  8938. this.onMaterialDispose = () => {
  8939. this.dispose();
  8940. };
  8941. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  8942. }
  8943. updateClipping( parent ) {
  8944. this.clippingContext = parent;
  8945. }
  8946. get clippingNeedsUpdate() {
  8947. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  8948. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  8949. return true;
  8950. }
  8951. get hardwareClippingPlanes() {
  8952. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  8953. }
  8954. getNodeBuilderState() {
  8955. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  8956. }
  8957. getMonitor() {
  8958. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  8959. }
  8960. getBindings() {
  8961. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  8962. }
  8963. getIndex() {
  8964. return this._geometries.getIndex( this );
  8965. }
  8966. getIndirect() {
  8967. return this._geometries.getIndirect( this );
  8968. }
  8969. getChainArray() {
  8970. return [ this.object, this.material, this.context, this.lightsNode ];
  8971. }
  8972. setGeometry( geometry ) {
  8973. this.geometry = geometry;
  8974. this.attributes = null;
  8975. }
  8976. getAttributes() {
  8977. if ( this.attributes !== null ) return this.attributes;
  8978. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  8979. const geometry = this.geometry;
  8980. const attributes = [];
  8981. const vertexBuffers = new Set();
  8982. for ( const nodeAttribute of nodeAttributes ) {
  8983. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  8984. if ( attribute === undefined ) continue;
  8985. attributes.push( attribute );
  8986. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  8987. vertexBuffers.add( bufferAttribute );
  8988. }
  8989. this.attributes = attributes;
  8990. this.vertexBuffers = Array.from( vertexBuffers.values() );
  8991. return attributes;
  8992. }
  8993. getVertexBuffers() {
  8994. if ( this.vertexBuffers === null ) this.getAttributes();
  8995. return this.vertexBuffers;
  8996. }
  8997. getDrawParameters() {
  8998. const { object, material, geometry, group, drawRange } = this;
  8999. const drawParams = this.drawParams || ( this.drawParams = {
  9000. vertexCount: 0,
  9001. firstVertex: 0,
  9002. instanceCount: 0,
  9003. firstInstance: 0
  9004. } );
  9005. const index = this.getIndex();
  9006. const hasIndex = ( index !== null );
  9007. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  9008. if ( instanceCount === 0 ) return null;
  9009. drawParams.instanceCount = instanceCount;
  9010. if ( object.isBatchedMesh === true ) return drawParams;
  9011. let rangeFactor = 1;
  9012. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  9013. rangeFactor = 2;
  9014. }
  9015. let firstVertex = drawRange.start * rangeFactor;
  9016. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  9017. if ( group !== null ) {
  9018. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  9019. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  9020. }
  9021. const position = geometry.attributes.position;
  9022. let itemCount = Infinity;
  9023. if ( hasIndex ) {
  9024. itemCount = index.count;
  9025. } else if ( position !== undefined && position !== null ) {
  9026. itemCount = position.count;
  9027. }
  9028. firstVertex = Math.max( firstVertex, 0 );
  9029. lastVertex = Math.min( lastVertex, itemCount );
  9030. const count = lastVertex - firstVertex;
  9031. if ( count < 0 || count === Infinity ) return null;
  9032. drawParams.vertexCount = count;
  9033. drawParams.firstVertex = firstVertex;
  9034. return drawParams;
  9035. }
  9036. getGeometryCacheKey() {
  9037. const { geometry } = this;
  9038. let cacheKey = '';
  9039. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  9040. const attribute = geometry.attributes[ name ];
  9041. cacheKey += name + ',';
  9042. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  9043. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  9044. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  9045. if ( attribute.normalized ) cacheKey += 'n,';
  9046. }
  9047. if ( geometry.index ) {
  9048. cacheKey += 'index,';
  9049. }
  9050. return cacheKey;
  9051. }
  9052. getMaterialCacheKey() {
  9053. const { object, material } = this;
  9054. let cacheKey = material.customProgramCacheKey();
  9055. for ( const property of getKeys( material ) ) {
  9056. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  9057. const value = material[ property ];
  9058. let valueKey;
  9059. if ( value !== null ) {
  9060. // some material values require a formatting
  9061. const type = typeof value;
  9062. if ( type === 'number' ) {
  9063. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  9064. } else if ( type === 'object' ) {
  9065. valueKey = '{';
  9066. if ( value.isTexture ) {
  9067. valueKey += value.mapping;
  9068. }
  9069. valueKey += '}';
  9070. } else {
  9071. valueKey = String( value );
  9072. }
  9073. } else {
  9074. valueKey = String( value );
  9075. }
  9076. cacheKey += /*property + ':' +*/ valueKey + ',';
  9077. }
  9078. cacheKey += this.clippingContextCacheKey + ',';
  9079. if ( object.geometry ) {
  9080. cacheKey += this.getGeometryCacheKey();
  9081. }
  9082. if ( object.skeleton ) {
  9083. cacheKey += object.skeleton.bones.length + ',';
  9084. }
  9085. if ( object.morphTargetInfluences ) {
  9086. cacheKey += object.morphTargetInfluences.length + ',';
  9087. }
  9088. if ( object.isBatchedMesh ) {
  9089. cacheKey += object._matricesTexture.uuid + ',';
  9090. if ( object._colorsTexture !== null ) {
  9091. cacheKey += object._colorsTexture.uuid + ',';
  9092. }
  9093. }
  9094. if ( object.count > 1 ) {
  9095. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  9096. cacheKey += object.uuid + ',';
  9097. }
  9098. cacheKey += object.receiveShadow + ',';
  9099. return hashString( cacheKey );
  9100. }
  9101. get needsGeometryUpdate() {
  9102. return this.geometry.id !== this.object.geometry.id;
  9103. }
  9104. get needsUpdate() {
  9105. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  9106. }
  9107. getDynamicCacheKey() {
  9108. // Environment Nodes Cache Key
  9109. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  9110. if ( this.object.receiveShadow ) {
  9111. cacheKey += 1;
  9112. }
  9113. return cacheKey;
  9114. }
  9115. getCacheKey() {
  9116. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  9117. }
  9118. dispose() {
  9119. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  9120. this.onDispose();
  9121. }
  9122. }
  9123. const chainArray = [];
  9124. class RenderObjects {
  9125. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  9126. this.renderer = renderer;
  9127. this.nodes = nodes;
  9128. this.geometries = geometries;
  9129. this.pipelines = pipelines;
  9130. this.bindings = bindings;
  9131. this.info = info;
  9132. this.chainMaps = {};
  9133. }
  9134. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  9135. const chainMap = this.getChainMap( passId );
  9136. // reuse chainArray
  9137. chainArray[ 0 ] = object;
  9138. chainArray[ 1 ] = material;
  9139. chainArray[ 2 ] = renderContext;
  9140. chainArray[ 3 ] = lightsNode;
  9141. let renderObject = chainMap.get( chainArray );
  9142. if ( renderObject === undefined ) {
  9143. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  9144. chainMap.set( chainArray, renderObject );
  9145. } else {
  9146. renderObject.updateClipping( clippingContext );
  9147. if ( renderObject.needsGeometryUpdate ) {
  9148. renderObject.setGeometry( object.geometry );
  9149. }
  9150. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  9151. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  9152. renderObject.dispose();
  9153. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  9154. } else {
  9155. renderObject.version = material.version;
  9156. }
  9157. }
  9158. }
  9159. return renderObject;
  9160. }
  9161. getChainMap( passId = 'default' ) {
  9162. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  9163. }
  9164. dispose() {
  9165. this.chainMaps = {};
  9166. }
  9167. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  9168. const chainMap = this.getChainMap( passId );
  9169. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  9170. renderObject.onDispose = () => {
  9171. this.pipelines.delete( renderObject );
  9172. this.bindings.delete( renderObject );
  9173. this.nodes.delete( renderObject );
  9174. chainMap.delete( renderObject.getChainArray() );
  9175. };
  9176. return renderObject;
  9177. }
  9178. }
  9179. class DataMap {
  9180. constructor() {
  9181. this.data = new WeakMap();
  9182. }
  9183. get( object ) {
  9184. let map = this.data.get( object );
  9185. if ( map === undefined ) {
  9186. map = {};
  9187. this.data.set( object, map );
  9188. }
  9189. return map;
  9190. }
  9191. delete( object ) {
  9192. let map;
  9193. if ( this.data.has( object ) ) {
  9194. map = this.data.get( object );
  9195. this.data.delete( object );
  9196. }
  9197. return map;
  9198. }
  9199. has( object ) {
  9200. return this.data.has( object );
  9201. }
  9202. dispose() {
  9203. this.data = new WeakMap();
  9204. }
  9205. }
  9206. const AttributeType = {
  9207. VERTEX: 1,
  9208. INDEX: 2,
  9209. STORAGE: 3,
  9210. INDIRECT: 4
  9211. };
  9212. // size of a chunk in bytes (STD140 layout)
  9213. const GPU_CHUNK_BYTES = 16;
  9214. // @TODO: Move to src/constants.js
  9215. const BlendColorFactor = 211;
  9216. const OneMinusBlendColorFactor = 212;
  9217. class Attributes extends DataMap {
  9218. constructor( backend ) {
  9219. super();
  9220. this.backend = backend;
  9221. }
  9222. delete( attribute ) {
  9223. const attributeData = super.delete( attribute );
  9224. if ( attributeData !== undefined ) {
  9225. this.backend.destroyAttribute( attribute );
  9226. }
  9227. return attributeData;
  9228. }
  9229. update( attribute, type ) {
  9230. const data = this.get( attribute );
  9231. if ( data.version === undefined ) {
  9232. if ( type === AttributeType.VERTEX ) {
  9233. this.backend.createAttribute( attribute );
  9234. } else if ( type === AttributeType.INDEX ) {
  9235. this.backend.createIndexAttribute( attribute );
  9236. } else if ( type === AttributeType.STORAGE ) {
  9237. this.backend.createStorageAttribute( attribute );
  9238. } else if ( type === AttributeType.INDIRECT ) {
  9239. this.backend.createIndirectStorageAttribute( attribute );
  9240. }
  9241. data.version = this._getBufferAttribute( attribute ).version;
  9242. } else {
  9243. const bufferAttribute = this._getBufferAttribute( attribute );
  9244. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  9245. this.backend.updateAttribute( attribute );
  9246. data.version = bufferAttribute.version;
  9247. }
  9248. }
  9249. }
  9250. _getBufferAttribute( attribute ) {
  9251. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9252. return attribute;
  9253. }
  9254. }
  9255. function arrayNeedsUint32( array ) {
  9256. // assumes larger values usually on last
  9257. for ( let i = array.length - 1; i >= 0; -- i ) {
  9258. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  9259. }
  9260. return false;
  9261. }
  9262. function getWireframeVersion( geometry ) {
  9263. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  9264. }
  9265. function getWireframeIndex( geometry ) {
  9266. const indices = [];
  9267. const geometryIndex = geometry.index;
  9268. const geometryPosition = geometry.attributes.position;
  9269. if ( geometryIndex !== null ) {
  9270. const array = geometryIndex.array;
  9271. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9272. const a = array[ i + 0 ];
  9273. const b = array[ i + 1 ];
  9274. const c = array[ i + 2 ];
  9275. indices.push( a, b, b, c, c, a );
  9276. }
  9277. } else {
  9278. const array = geometryPosition.array;
  9279. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9280. const a = i + 0;
  9281. const b = i + 1;
  9282. const c = i + 2;
  9283. indices.push( a, b, b, c, c, a );
  9284. }
  9285. }
  9286. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9287. attribute.version = getWireframeVersion( geometry );
  9288. return attribute;
  9289. }
  9290. class Geometries extends DataMap {
  9291. constructor( attributes, info ) {
  9292. super();
  9293. this.attributes = attributes;
  9294. this.info = info;
  9295. this.wireframes = new WeakMap();
  9296. this.attributeCall = new WeakMap();
  9297. }
  9298. has( renderObject ) {
  9299. const geometry = renderObject.geometry;
  9300. return super.has( geometry ) && this.get( geometry ).initialized === true;
  9301. }
  9302. updateForRender( renderObject ) {
  9303. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  9304. this.updateAttributes( renderObject );
  9305. }
  9306. initGeometry( renderObject ) {
  9307. const geometry = renderObject.geometry;
  9308. const geometryData = this.get( geometry );
  9309. geometryData.initialized = true;
  9310. this.info.memory.geometries ++;
  9311. const onDispose = () => {
  9312. this.info.memory.geometries --;
  9313. const index = geometry.index;
  9314. const geometryAttributes = renderObject.getAttributes();
  9315. if ( index !== null ) {
  9316. this.attributes.delete( index );
  9317. }
  9318. for ( const geometryAttribute of geometryAttributes ) {
  9319. this.attributes.delete( geometryAttribute );
  9320. }
  9321. const wireframeAttribute = this.wireframes.get( geometry );
  9322. if ( wireframeAttribute !== undefined ) {
  9323. this.attributes.delete( wireframeAttribute );
  9324. }
  9325. geometry.removeEventListener( 'dispose', onDispose );
  9326. };
  9327. geometry.addEventListener( 'dispose', onDispose );
  9328. }
  9329. updateAttributes( renderObject ) {
  9330. // attributes
  9331. const attributes = renderObject.getAttributes();
  9332. for ( const attribute of attributes ) {
  9333. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  9334. this.updateAttribute( attribute, AttributeType.STORAGE );
  9335. } else {
  9336. this.updateAttribute( attribute, AttributeType.VERTEX );
  9337. }
  9338. }
  9339. // indexes
  9340. const index = this.getIndex( renderObject );
  9341. if ( index !== null ) {
  9342. this.updateAttribute( index, AttributeType.INDEX );
  9343. }
  9344. // indirect
  9345. const indirect = renderObject.geometry.indirect;
  9346. if ( indirect !== null ) {
  9347. this.updateAttribute( indirect, AttributeType.INDIRECT );
  9348. }
  9349. }
  9350. updateAttribute( attribute, type ) {
  9351. const callId = this.info.render.calls;
  9352. if ( ! attribute.isInterleavedBufferAttribute ) {
  9353. if ( this.attributeCall.get( attribute ) !== callId ) {
  9354. this.attributes.update( attribute, type );
  9355. this.attributeCall.set( attribute, callId );
  9356. }
  9357. } else {
  9358. if ( this.attributeCall.get( attribute ) === undefined ) {
  9359. this.attributes.update( attribute, type );
  9360. this.attributeCall.set( attribute, callId );
  9361. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  9362. this.attributes.update( attribute, type );
  9363. this.attributeCall.set( attribute.data, callId );
  9364. this.attributeCall.set( attribute, callId );
  9365. }
  9366. }
  9367. }
  9368. getIndirect( renderObject ) {
  9369. return renderObject.geometry.indirect;
  9370. }
  9371. getIndex( renderObject ) {
  9372. const { geometry, material } = renderObject;
  9373. let index = geometry.index;
  9374. if ( material.wireframe === true ) {
  9375. const wireframes = this.wireframes;
  9376. let wireframeAttribute = wireframes.get( geometry );
  9377. if ( wireframeAttribute === undefined ) {
  9378. wireframeAttribute = getWireframeIndex( geometry );
  9379. wireframes.set( geometry, wireframeAttribute );
  9380. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  9381. this.attributes.delete( wireframeAttribute );
  9382. wireframeAttribute = getWireframeIndex( geometry );
  9383. wireframes.set( geometry, wireframeAttribute );
  9384. }
  9385. index = wireframeAttribute;
  9386. }
  9387. return index;
  9388. }
  9389. }
  9390. class Info {
  9391. constructor() {
  9392. this.autoReset = true;
  9393. this.frame = 0;
  9394. this.calls = 0;
  9395. this.render = {
  9396. calls: 0,
  9397. frameCalls: 0,
  9398. drawCalls: 0,
  9399. triangles: 0,
  9400. points: 0,
  9401. lines: 0,
  9402. timestamp: 0,
  9403. previousFrameCalls: 0,
  9404. timestampCalls: 0
  9405. };
  9406. this.compute = {
  9407. calls: 0,
  9408. frameCalls: 0,
  9409. timestamp: 0,
  9410. previousFrameCalls: 0,
  9411. timestampCalls: 0
  9412. };
  9413. this.memory = {
  9414. geometries: 0,
  9415. textures: 0
  9416. };
  9417. }
  9418. update( object, count, instanceCount ) {
  9419. this.render.drawCalls ++;
  9420. if ( object.isMesh || object.isSprite ) {
  9421. this.render.triangles += instanceCount * ( count / 3 );
  9422. } else if ( object.isPoints ) {
  9423. this.render.points += instanceCount * count;
  9424. } else if ( object.isLineSegments ) {
  9425. this.render.lines += instanceCount * ( count / 2 );
  9426. } else if ( object.isLine ) {
  9427. this.render.lines += instanceCount * ( count - 1 );
  9428. } else {
  9429. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  9430. }
  9431. }
  9432. updateTimestamp( type, time ) {
  9433. if ( this[ type ].timestampCalls === 0 ) {
  9434. this[ type ].timestamp = 0;
  9435. }
  9436. this[ type ].timestamp += time;
  9437. this[ type ].timestampCalls ++;
  9438. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  9439. this[ type ].timestampCalls = 0;
  9440. }
  9441. }
  9442. reset() {
  9443. const previousRenderFrameCalls = this.render.frameCalls;
  9444. this.render.previousFrameCalls = previousRenderFrameCalls;
  9445. const previousComputeFrameCalls = this.compute.frameCalls;
  9446. this.compute.previousFrameCalls = previousComputeFrameCalls;
  9447. this.render.drawCalls = 0;
  9448. this.render.frameCalls = 0;
  9449. this.compute.frameCalls = 0;
  9450. this.render.triangles = 0;
  9451. this.render.points = 0;
  9452. this.render.lines = 0;
  9453. }
  9454. dispose() {
  9455. this.reset();
  9456. this.calls = 0;
  9457. this.render.calls = 0;
  9458. this.compute.calls = 0;
  9459. this.render.timestamp = 0;
  9460. this.compute.timestamp = 0;
  9461. this.memory.geometries = 0;
  9462. this.memory.textures = 0;
  9463. }
  9464. }
  9465. class Pipeline {
  9466. constructor( cacheKey ) {
  9467. this.cacheKey = cacheKey;
  9468. this.usedTimes = 0;
  9469. }
  9470. }
  9471. class RenderPipeline extends Pipeline {
  9472. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  9473. super( cacheKey );
  9474. this.vertexProgram = vertexProgram;
  9475. this.fragmentProgram = fragmentProgram;
  9476. }
  9477. }
  9478. class ComputePipeline extends Pipeline {
  9479. constructor( cacheKey, computeProgram ) {
  9480. super( cacheKey );
  9481. this.computeProgram = computeProgram;
  9482. this.isComputePipeline = true;
  9483. }
  9484. }
  9485. let _id$7 = 0;
  9486. class ProgrammableStage {
  9487. constructor( code, type, transforms = null, attributes = null ) {
  9488. this.id = _id$7 ++;
  9489. this.code = code;
  9490. this.stage = type;
  9491. this.transforms = transforms;
  9492. this.attributes = attributes;
  9493. this.usedTimes = 0;
  9494. }
  9495. }
  9496. class Pipelines extends DataMap {
  9497. constructor( backend, nodes ) {
  9498. super();
  9499. this.backend = backend;
  9500. this.nodes = nodes;
  9501. this.bindings = null; // set by the bindings
  9502. this.caches = new Map();
  9503. this.programs = {
  9504. vertex: new Map(),
  9505. fragment: new Map(),
  9506. compute: new Map()
  9507. };
  9508. }
  9509. getForCompute( computeNode, bindings ) {
  9510. const { backend } = this;
  9511. const data = this.get( computeNode );
  9512. if ( this._needsComputeUpdate( computeNode ) ) {
  9513. const previousPipeline = data.pipeline;
  9514. if ( previousPipeline ) {
  9515. previousPipeline.usedTimes --;
  9516. previousPipeline.computeProgram.usedTimes --;
  9517. }
  9518. // get shader
  9519. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  9520. // programmable stage
  9521. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  9522. if ( stageCompute === undefined ) {
  9523. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  9524. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  9525. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  9526. backend.createProgram( stageCompute );
  9527. }
  9528. // determine compute pipeline
  9529. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  9530. let pipeline = this.caches.get( cacheKey );
  9531. if ( pipeline === undefined ) {
  9532. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  9533. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  9534. }
  9535. // keep track of all used times
  9536. pipeline.usedTimes ++;
  9537. stageCompute.usedTimes ++;
  9538. //
  9539. data.version = computeNode.version;
  9540. data.pipeline = pipeline;
  9541. }
  9542. return data.pipeline;
  9543. }
  9544. getForRender( renderObject, promises = null ) {
  9545. const { backend } = this;
  9546. const data = this.get( renderObject );
  9547. if ( this._needsRenderUpdate( renderObject ) ) {
  9548. const previousPipeline = data.pipeline;
  9549. if ( previousPipeline ) {
  9550. previousPipeline.usedTimes --;
  9551. previousPipeline.vertexProgram.usedTimes --;
  9552. previousPipeline.fragmentProgram.usedTimes --;
  9553. }
  9554. // get shader
  9555. const nodeBuilderState = renderObject.getNodeBuilderState();
  9556. // programmable stages
  9557. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  9558. if ( stageVertex === undefined ) {
  9559. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  9560. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  9561. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  9562. backend.createProgram( stageVertex );
  9563. }
  9564. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  9565. if ( stageFragment === undefined ) {
  9566. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  9567. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  9568. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  9569. backend.createProgram( stageFragment );
  9570. }
  9571. // determine render pipeline
  9572. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  9573. let pipeline = this.caches.get( cacheKey );
  9574. if ( pipeline === undefined ) {
  9575. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  9576. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  9577. } else {
  9578. renderObject.pipeline = pipeline;
  9579. }
  9580. // keep track of all used times
  9581. pipeline.usedTimes ++;
  9582. stageVertex.usedTimes ++;
  9583. stageFragment.usedTimes ++;
  9584. //
  9585. data.pipeline = pipeline;
  9586. }
  9587. return data.pipeline;
  9588. }
  9589. delete( object ) {
  9590. const pipeline = this.get( object ).pipeline;
  9591. if ( pipeline ) {
  9592. // pipeline
  9593. pipeline.usedTimes --;
  9594. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  9595. // programs
  9596. if ( pipeline.isComputePipeline ) {
  9597. pipeline.computeProgram.usedTimes --;
  9598. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  9599. } else {
  9600. pipeline.fragmentProgram.usedTimes --;
  9601. pipeline.vertexProgram.usedTimes --;
  9602. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  9603. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  9604. }
  9605. }
  9606. return super.delete( object );
  9607. }
  9608. dispose() {
  9609. super.dispose();
  9610. this.caches = new Map();
  9611. this.programs = {
  9612. vertex: new Map(),
  9613. fragment: new Map(),
  9614. compute: new Map()
  9615. };
  9616. }
  9617. updateForRender( renderObject ) {
  9618. this.getForRender( renderObject );
  9619. }
  9620. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  9621. // check for existing pipeline
  9622. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  9623. let pipeline = this.caches.get( cacheKey );
  9624. if ( pipeline === undefined ) {
  9625. pipeline = new ComputePipeline( cacheKey, stageCompute );
  9626. this.caches.set( cacheKey, pipeline );
  9627. this.backend.createComputePipeline( pipeline, bindings );
  9628. }
  9629. return pipeline;
  9630. }
  9631. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  9632. // check for existing pipeline
  9633. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  9634. let pipeline = this.caches.get( cacheKey );
  9635. if ( pipeline === undefined ) {
  9636. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  9637. this.caches.set( cacheKey, pipeline );
  9638. renderObject.pipeline = pipeline;
  9639. this.backend.createRenderPipeline( renderObject, promises );
  9640. }
  9641. return pipeline;
  9642. }
  9643. _getComputeCacheKey( computeNode, stageCompute ) {
  9644. return computeNode.id + ',' + stageCompute.id;
  9645. }
  9646. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  9647. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  9648. }
  9649. _releasePipeline( pipeline ) {
  9650. this.caches.delete( pipeline.cacheKey );
  9651. }
  9652. _releaseProgram( program ) {
  9653. const code = program.code;
  9654. const stage = program.stage;
  9655. this.programs[ stage ].delete( code );
  9656. }
  9657. _needsComputeUpdate( computeNode ) {
  9658. const data = this.get( computeNode );
  9659. return data.pipeline === undefined || data.version !== computeNode.version;
  9660. }
  9661. _needsRenderUpdate( renderObject ) {
  9662. const data = this.get( renderObject );
  9663. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  9664. }
  9665. }
  9666. class Bindings extends DataMap {
  9667. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  9668. super();
  9669. this.backend = backend;
  9670. this.textures = textures;
  9671. this.pipelines = pipelines;
  9672. this.attributes = attributes;
  9673. this.nodes = nodes;
  9674. this.info = info;
  9675. this.pipelines.bindings = this; // assign bindings to pipelines
  9676. }
  9677. getForRender( renderObject ) {
  9678. const bindings = renderObject.getBindings();
  9679. for ( const bindGroup of bindings ) {
  9680. const groupData = this.get( bindGroup );
  9681. if ( groupData.bindGroup === undefined ) {
  9682. // each object defines an array of bindings (ubos, textures, samplers etc.)
  9683. this._init( bindGroup );
  9684. this.backend.createBindings( bindGroup, bindings, 0 );
  9685. groupData.bindGroup = bindGroup;
  9686. }
  9687. }
  9688. return bindings;
  9689. }
  9690. getForCompute( computeNode ) {
  9691. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  9692. for ( const bindGroup of bindings ) {
  9693. const groupData = this.get( bindGroup );
  9694. if ( groupData.bindGroup === undefined ) {
  9695. this._init( bindGroup );
  9696. this.backend.createBindings( bindGroup, bindings, 0 );
  9697. groupData.bindGroup = bindGroup;
  9698. }
  9699. }
  9700. return bindings;
  9701. }
  9702. updateForCompute( computeNode ) {
  9703. this._updateBindings( this.getForCompute( computeNode ) );
  9704. }
  9705. updateForRender( renderObject ) {
  9706. this._updateBindings( this.getForRender( renderObject ) );
  9707. }
  9708. _updateBindings( bindings ) {
  9709. for ( const bindGroup of bindings ) {
  9710. this._update( bindGroup, bindings );
  9711. }
  9712. }
  9713. _init( bindGroup ) {
  9714. for ( const binding of bindGroup.bindings ) {
  9715. if ( binding.isSampledTexture ) {
  9716. this.textures.updateTexture( binding.texture );
  9717. } else if ( binding.isStorageBuffer ) {
  9718. const attribute = binding.attribute;
  9719. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  9720. this.attributes.update( attribute, attributeType );
  9721. }
  9722. }
  9723. }
  9724. _update( bindGroup, bindings ) {
  9725. const { backend } = this;
  9726. let needsBindingsUpdate = false;
  9727. let cacheBindings = true;
  9728. let cacheIndex = 0;
  9729. let version = 0;
  9730. // iterate over all bindings and check if buffer updates or a new binding group is required
  9731. for ( const binding of bindGroup.bindings ) {
  9732. if ( binding.isNodeUniformsGroup ) {
  9733. const updated = this.nodes.updateGroup( binding );
  9734. if ( ! updated ) continue;
  9735. }
  9736. if ( binding.isUniformBuffer ) {
  9737. const updated = binding.update();
  9738. if ( updated ) {
  9739. backend.updateBinding( binding );
  9740. }
  9741. } else if ( binding.isSampler ) {
  9742. binding.update();
  9743. } else if ( binding.isSampledTexture ) {
  9744. const texturesTextureData = this.textures.get( binding.texture );
  9745. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  9746. const updated = binding.update();
  9747. const texture = binding.texture;
  9748. if ( updated ) {
  9749. this.textures.updateTexture( texture );
  9750. }
  9751. const textureData = backend.get( texture );
  9752. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  9753. cacheBindings = false;
  9754. } else {
  9755. cacheIndex = cacheIndex * 10 + texture.id;
  9756. version += texture.version;
  9757. }
  9758. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  9759. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  9760. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  9761. this.textures.updateTexture( texture );
  9762. needsBindingsUpdate = true;
  9763. }
  9764. if ( texture.isStorageTexture === true ) {
  9765. const textureData = this.get( texture );
  9766. if ( binding.store === true ) {
  9767. textureData.needsMipmap = true;
  9768. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  9769. this.backend.generateMipmaps( texture );
  9770. textureData.needsMipmap = false;
  9771. }
  9772. }
  9773. }
  9774. }
  9775. if ( needsBindingsUpdate === true ) {
  9776. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  9777. }
  9778. }
  9779. }
  9780. function painterSortStable( a, b ) {
  9781. if ( a.groupOrder !== b.groupOrder ) {
  9782. return a.groupOrder - b.groupOrder;
  9783. } else if ( a.renderOrder !== b.renderOrder ) {
  9784. return a.renderOrder - b.renderOrder;
  9785. } else if ( a.material.id !== b.material.id ) {
  9786. return a.material.id - b.material.id;
  9787. } else if ( a.z !== b.z ) {
  9788. return a.z - b.z;
  9789. } else {
  9790. return a.id - b.id;
  9791. }
  9792. }
  9793. function reversePainterSortStable( a, b ) {
  9794. if ( a.groupOrder !== b.groupOrder ) {
  9795. return a.groupOrder - b.groupOrder;
  9796. } else if ( a.renderOrder !== b.renderOrder ) {
  9797. return a.renderOrder - b.renderOrder;
  9798. } else if ( a.z !== b.z ) {
  9799. return b.z - a.z;
  9800. } else {
  9801. return a.id - b.id;
  9802. }
  9803. }
  9804. function needsDoublePass( material ) {
  9805. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  9806. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  9807. }
  9808. class RenderList {
  9809. constructor( lighting, scene, camera ) {
  9810. this.renderItems = [];
  9811. this.renderItemsIndex = 0;
  9812. this.opaque = [];
  9813. this.transparentDoublePass = [];
  9814. this.transparent = [];
  9815. this.bundles = [];
  9816. this.lightsNode = lighting.getNode( scene, camera );
  9817. this.lightsArray = [];
  9818. this.scene = scene;
  9819. this.camera = camera;
  9820. this.occlusionQueryCount = 0;
  9821. }
  9822. begin() {
  9823. this.renderItemsIndex = 0;
  9824. this.opaque.length = 0;
  9825. this.transparentDoublePass.length = 0;
  9826. this.transparent.length = 0;
  9827. this.bundles.length = 0;
  9828. this.lightsArray.length = 0;
  9829. this.occlusionQueryCount = 0;
  9830. return this;
  9831. }
  9832. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  9833. let renderItem = this.renderItems[ this.renderItemsIndex ];
  9834. if ( renderItem === undefined ) {
  9835. renderItem = {
  9836. id: object.id,
  9837. object: object,
  9838. geometry: geometry,
  9839. material: material,
  9840. groupOrder: groupOrder,
  9841. renderOrder: object.renderOrder,
  9842. z: z,
  9843. group: group,
  9844. clippingContext: clippingContext
  9845. };
  9846. this.renderItems[ this.renderItemsIndex ] = renderItem;
  9847. } else {
  9848. renderItem.id = object.id;
  9849. renderItem.object = object;
  9850. renderItem.geometry = geometry;
  9851. renderItem.material = material;
  9852. renderItem.groupOrder = groupOrder;
  9853. renderItem.renderOrder = object.renderOrder;
  9854. renderItem.z = z;
  9855. renderItem.group = group;
  9856. renderItem.clippingContext = clippingContext;
  9857. }
  9858. this.renderItemsIndex ++;
  9859. return renderItem;
  9860. }
  9861. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  9862. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  9863. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  9864. if ( material.transparent === true || material.transmission > 0 ) {
  9865. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  9866. this.transparent.push( renderItem );
  9867. } else {
  9868. this.opaque.push( renderItem );
  9869. }
  9870. }
  9871. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  9872. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  9873. if ( material.transparent === true || material.transmission > 0 ) {
  9874. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  9875. this.transparent.unshift( renderItem );
  9876. } else {
  9877. this.opaque.unshift( renderItem );
  9878. }
  9879. }
  9880. pushBundle( group ) {
  9881. this.bundles.push( group );
  9882. }
  9883. pushLight( light ) {
  9884. this.lightsArray.push( light );
  9885. }
  9886. sort( customOpaqueSort, customTransparentSort ) {
  9887. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  9888. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  9889. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  9890. }
  9891. finish() {
  9892. // update lights
  9893. this.lightsNode.setLights( this.lightsArray );
  9894. // Clear references from inactive renderItems in the list
  9895. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  9896. const renderItem = this.renderItems[ i ];
  9897. if ( renderItem.id === null ) break;
  9898. renderItem.id = null;
  9899. renderItem.object = null;
  9900. renderItem.geometry = null;
  9901. renderItem.material = null;
  9902. renderItem.groupOrder = null;
  9903. renderItem.renderOrder = null;
  9904. renderItem.z = null;
  9905. renderItem.group = null;
  9906. renderItem.clippingContext = null;
  9907. }
  9908. }
  9909. }
  9910. class RenderLists {
  9911. constructor( lighting ) {
  9912. this.lighting = lighting;
  9913. this.lists = new ChainMap();
  9914. }
  9915. get( scene, camera ) {
  9916. const lists = this.lists;
  9917. const keys = [ scene, camera ];
  9918. let list = lists.get( keys );
  9919. if ( list === undefined ) {
  9920. list = new RenderList( this.lighting, scene, camera );
  9921. lists.set( keys, list );
  9922. }
  9923. return list;
  9924. }
  9925. dispose() {
  9926. this.lists = new ChainMap();
  9927. }
  9928. }
  9929. let id = 0;
  9930. class RenderContext {
  9931. constructor() {
  9932. this.id = id ++;
  9933. this.color = true;
  9934. this.clearColor = true;
  9935. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  9936. this.depth = true;
  9937. this.clearDepth = true;
  9938. this.clearDepthValue = 1;
  9939. this.stencil = false;
  9940. this.clearStencil = true;
  9941. this.clearStencilValue = 1;
  9942. this.viewport = false;
  9943. this.viewportValue = new Vector4();
  9944. this.scissor = false;
  9945. this.scissorValue = new Vector4();
  9946. this.textures = null;
  9947. this.depthTexture = null;
  9948. this.activeCubeFace = 0;
  9949. this.sampleCount = 1;
  9950. this.width = 0;
  9951. this.height = 0;
  9952. this.isRenderContext = true;
  9953. }
  9954. getCacheKey() {
  9955. return getCacheKey( this );
  9956. }
  9957. }
  9958. function getCacheKey( renderContext ) {
  9959. const { textures, activeCubeFace } = renderContext;
  9960. const values = [ activeCubeFace ];
  9961. for ( const texture of textures ) {
  9962. values.push( texture.id );
  9963. }
  9964. return hashArray( values );
  9965. }
  9966. class RenderContexts {
  9967. constructor() {
  9968. this.chainMaps = {};
  9969. }
  9970. get( scene, camera, renderTarget = null ) {
  9971. const chainKey = [ scene, camera ];
  9972. let attachmentState;
  9973. if ( renderTarget === null ) {
  9974. attachmentState = 'default';
  9975. } else {
  9976. const format = renderTarget.texture.format;
  9977. const count = renderTarget.textures.length;
  9978. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  9979. }
  9980. const chainMap = this.getChainMap( attachmentState );
  9981. let renderState = chainMap.get( chainKey );
  9982. if ( renderState === undefined ) {
  9983. renderState = new RenderContext();
  9984. chainMap.set( chainKey, renderState );
  9985. }
  9986. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  9987. return renderState;
  9988. }
  9989. getChainMap( attachmentState ) {
  9990. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  9991. }
  9992. dispose() {
  9993. this.chainMaps = {};
  9994. }
  9995. }
  9996. const _size$3 = /*@__PURE__*/ new Vector3();
  9997. class Textures extends DataMap {
  9998. constructor( renderer, backend, info ) {
  9999. super();
  10000. this.renderer = renderer;
  10001. this.backend = backend;
  10002. this.info = info;
  10003. }
  10004. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  10005. const renderTargetData = this.get( renderTarget );
  10006. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  10007. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  10008. const textures = renderTarget.textures;
  10009. const size = this.getSize( textures[ 0 ] );
  10010. const mipWidth = size.width >> activeMipmapLevel;
  10011. const mipHeight = size.height >> activeMipmapLevel;
  10012. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  10013. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  10014. let textureNeedsUpdate = false;
  10015. if ( depthTexture === undefined && useDepthTexture ) {
  10016. depthTexture = new DepthTexture();
  10017. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  10018. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  10019. depthTexture.image.width = mipWidth;
  10020. depthTexture.image.height = mipHeight;
  10021. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  10022. }
  10023. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  10024. textureNeedsUpdate = true;
  10025. if ( depthTexture ) {
  10026. depthTexture.needsUpdate = true;
  10027. depthTexture.image.width = mipWidth;
  10028. depthTexture.image.height = mipHeight;
  10029. }
  10030. }
  10031. renderTargetData.width = size.width;
  10032. renderTargetData.height = size.height;
  10033. renderTargetData.textures = textures;
  10034. renderTargetData.depthTexture = depthTexture || null;
  10035. renderTargetData.depth = renderTarget.depthBuffer;
  10036. renderTargetData.stencil = renderTarget.stencilBuffer;
  10037. renderTargetData.renderTarget = renderTarget;
  10038. if ( renderTargetData.sampleCount !== sampleCount ) {
  10039. textureNeedsUpdate = true;
  10040. if ( depthTexture ) {
  10041. depthTexture.needsUpdate = true;
  10042. }
  10043. renderTargetData.sampleCount = sampleCount;
  10044. }
  10045. //
  10046. const options = { sampleCount };
  10047. for ( let i = 0; i < textures.length; i ++ ) {
  10048. const texture = textures[ i ];
  10049. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  10050. this.updateTexture( texture, options );
  10051. }
  10052. if ( depthTexture ) {
  10053. this.updateTexture( depthTexture, options );
  10054. }
  10055. // dispose handler
  10056. if ( renderTargetData.initialized !== true ) {
  10057. renderTargetData.initialized = true;
  10058. // dispose
  10059. const onDispose = () => {
  10060. renderTarget.removeEventListener( 'dispose', onDispose );
  10061. for ( let i = 0; i < textures.length; i ++ ) {
  10062. this._destroyTexture( textures[ i ] );
  10063. }
  10064. if ( depthTexture ) {
  10065. this._destroyTexture( depthTexture );
  10066. }
  10067. this.delete( renderTarget );
  10068. };
  10069. renderTarget.addEventListener( 'dispose', onDispose );
  10070. }
  10071. }
  10072. updateTexture( texture, options = {} ) {
  10073. const textureData = this.get( texture );
  10074. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  10075. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  10076. const backend = this.backend;
  10077. if ( isRenderTarget && textureData.initialized === true ) {
  10078. // it's an update
  10079. backend.destroySampler( texture );
  10080. backend.destroyTexture( texture );
  10081. }
  10082. //
  10083. if ( texture.isFramebufferTexture ) {
  10084. const renderTarget = this.renderer.getRenderTarget();
  10085. if ( renderTarget ) {
  10086. texture.type = renderTarget.texture.type;
  10087. } else {
  10088. texture.type = UnsignedByteType;
  10089. }
  10090. }
  10091. //
  10092. const { width, height, depth } = this.getSize( texture );
  10093. options.width = width;
  10094. options.height = height;
  10095. options.depth = depth;
  10096. options.needsMipmaps = this.needsMipmaps( texture );
  10097. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  10098. //
  10099. if ( isRenderTarget || texture.isStorageTexture === true ) {
  10100. backend.createSampler( texture );
  10101. backend.createTexture( texture, options );
  10102. textureData.generation = texture.version;
  10103. } else {
  10104. const needsCreate = textureData.initialized !== true;
  10105. if ( needsCreate ) backend.createSampler( texture );
  10106. if ( texture.version > 0 ) {
  10107. const image = texture.image;
  10108. if ( image === undefined ) {
  10109. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  10110. } else if ( image.complete === false ) {
  10111. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  10112. } else {
  10113. if ( texture.images ) {
  10114. const images = [];
  10115. for ( const image of texture.images ) {
  10116. images.push( image );
  10117. }
  10118. options.images = images;
  10119. } else {
  10120. options.image = image;
  10121. }
  10122. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  10123. backend.createTexture( texture, options );
  10124. textureData.isDefaultTexture = false;
  10125. textureData.generation = texture.version;
  10126. }
  10127. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  10128. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  10129. }
  10130. } else {
  10131. // async update
  10132. backend.createDefaultTexture( texture );
  10133. textureData.isDefaultTexture = true;
  10134. textureData.generation = texture.version;
  10135. }
  10136. }
  10137. // dispose handler
  10138. if ( textureData.initialized !== true ) {
  10139. textureData.initialized = true;
  10140. textureData.generation = texture.version;
  10141. //
  10142. this.info.memory.textures ++;
  10143. // dispose
  10144. const onDispose = () => {
  10145. texture.removeEventListener( 'dispose', onDispose );
  10146. this._destroyTexture( texture );
  10147. this.info.memory.textures --;
  10148. };
  10149. texture.addEventListener( 'dispose', onDispose );
  10150. }
  10151. //
  10152. textureData.version = texture.version;
  10153. }
  10154. getSize( texture, target = _size$3 ) {
  10155. let image = texture.images ? texture.images[ 0 ] : texture.image;
  10156. if ( image ) {
  10157. if ( image.image !== undefined ) image = image.image;
  10158. target.width = image.width || 1;
  10159. target.height = image.height || 1;
  10160. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  10161. } else {
  10162. target.width = target.height = target.depth = 1;
  10163. }
  10164. return target;
  10165. }
  10166. getMipLevels( texture, width, height ) {
  10167. let mipLevelCount;
  10168. if ( texture.isCompressedTexture ) {
  10169. if ( texture.mipmaps ) {
  10170. mipLevelCount = texture.mipmaps.length;
  10171. } else {
  10172. mipLevelCount = 1;
  10173. }
  10174. } else {
  10175. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  10176. }
  10177. return mipLevelCount;
  10178. }
  10179. needsMipmaps( texture ) {
  10180. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  10181. }
  10182. isEnvironmentTexture( texture ) {
  10183. const mapping = texture.mapping;
  10184. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10185. }
  10186. _destroyTexture( texture ) {
  10187. this.backend.destroySampler( texture );
  10188. this.backend.destroyTexture( texture );
  10189. this.delete( texture );
  10190. }
  10191. }
  10192. class Color4 extends Color {
  10193. constructor( r, g, b, a = 1 ) {
  10194. super( r, g, b );
  10195. this.a = a;
  10196. }
  10197. set( r, g, b, a = 1 ) {
  10198. this.a = a;
  10199. return super.set( r, g, b );
  10200. }
  10201. copy( color ) {
  10202. if ( color.a !== undefined ) this.a = color.a;
  10203. return super.copy( color );
  10204. }
  10205. clone() {
  10206. return new this.constructor( this.r, this.g, this.b, this.a );
  10207. }
  10208. }
  10209. class ParameterNode extends PropertyNode {
  10210. static get type() {
  10211. return 'ParameterNode';
  10212. }
  10213. constructor( nodeType, name = null ) {
  10214. super( nodeType, name );
  10215. this.isParameterNode = true;
  10216. }
  10217. getHash() {
  10218. return this.uuid;
  10219. }
  10220. generate() {
  10221. return this.name;
  10222. }
  10223. }
  10224. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  10225. class StackNode extends Node {
  10226. static get type() {
  10227. return 'StackNode';
  10228. }
  10229. constructor( parent = null ) {
  10230. super();
  10231. this.nodes = [];
  10232. this.outputNode = null;
  10233. this.parent = parent;
  10234. this._currentCond = null;
  10235. this.isStackNode = true;
  10236. }
  10237. getNodeType( builder ) {
  10238. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  10239. }
  10240. add( node ) {
  10241. this.nodes.push( node );
  10242. return this;
  10243. }
  10244. If( boolNode, method ) {
  10245. const methodNode = new ShaderNode( method );
  10246. this._currentCond = select( boolNode, methodNode );
  10247. return this.add( this._currentCond );
  10248. }
  10249. ElseIf( boolNode, method ) {
  10250. const methodNode = new ShaderNode( method );
  10251. const ifNode = select( boolNode, methodNode );
  10252. this._currentCond.elseNode = ifNode;
  10253. this._currentCond = ifNode;
  10254. return this;
  10255. }
  10256. Else( method ) {
  10257. this._currentCond.elseNode = new ShaderNode( method );
  10258. return this;
  10259. }
  10260. build( builder, ...params ) {
  10261. const previousStack = getCurrentStack();
  10262. setCurrentStack( this );
  10263. for ( const node of this.nodes ) {
  10264. node.build( builder, 'void' );
  10265. }
  10266. setCurrentStack( previousStack );
  10267. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  10268. }
  10269. //
  10270. else( ...params ) { // @deprecated, r168
  10271. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  10272. return this.Else( ...params );
  10273. }
  10274. elseif( ...params ) { // @deprecated, r168
  10275. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  10276. return this.ElseIf( ...params );
  10277. }
  10278. }
  10279. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  10280. /**
  10281. * This node can be used to define multiple outputs in a shader programs.
  10282. *
  10283. * @augments Node
  10284. */
  10285. class OutputStructNode extends Node {
  10286. static get type() {
  10287. return 'OutputStructNode';
  10288. }
  10289. /**
  10290. * Constructs a new output struct node. The constructor can be invoked with an
  10291. * arbitrary number of nodes representing the members.
  10292. *
  10293. * @param {...Node} members - A parameter list of nodes.
  10294. */
  10295. constructor( ...members ) {
  10296. super();
  10297. /**
  10298. * An array of nodes which defines the output.
  10299. *
  10300. * @type {Array<Node>}
  10301. */
  10302. this.members = members;
  10303. /**
  10304. * This flag can be used for type testing.
  10305. *
  10306. * @type {Boolean}
  10307. * @readonly
  10308. * @default true
  10309. */
  10310. this.isOutputStructNode = true;
  10311. }
  10312. setup( builder ) {
  10313. super.setup( builder );
  10314. const members = this.members;
  10315. const types = [];
  10316. for ( let i = 0; i < members.length; i ++ ) {
  10317. types.push( members[ i ].getNodeType( builder ) );
  10318. }
  10319. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  10320. }
  10321. generate( builder, output ) {
  10322. const propertyName = builder.getOutputStructName();
  10323. const members = this.members;
  10324. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  10325. for ( let i = 0; i < members.length; i ++ ) {
  10326. const snippet = members[ i ].build( builder, output );
  10327. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  10328. }
  10329. return propertyName;
  10330. }
  10331. }
  10332. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  10333. /**
  10334. * Returns the MRT texture index for the given name.
  10335. *
  10336. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  10337. * @param {String} name - The name of the MRT texture which index is requested.
  10338. * @return {Number} The texture index.
  10339. */
  10340. function getTextureIndex( textures, name ) {
  10341. for ( let i = 0; i < textures.length; i ++ ) {
  10342. if ( textures[ i ].name === name ) {
  10343. return i;
  10344. }
  10345. }
  10346. return - 1;
  10347. }
  10348. /**
  10349. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  10350. * post-processing is shown below:
  10351. * ```js
  10352. * const mrtNode = mrt( {
  10353. * output: output,
  10354. * normal: normalView
  10355. * } ) );
  10356. * ```
  10357. * The MRT output is defined as a dictionary.
  10358. *
  10359. * @augments OutputStructNode
  10360. */
  10361. class MRTNode extends OutputStructNode {
  10362. static get type() {
  10363. return 'MRTNode';
  10364. }
  10365. /**
  10366. * Constructs a new output struct node.
  10367. *
  10368. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  10369. */
  10370. constructor( outputNodes ) {
  10371. super();
  10372. /**
  10373. * A dictionary representing the MRT outputs. The key
  10374. * is the name of the output, the value the node which produces
  10375. * the output result.
  10376. *
  10377. * @type {Object<String, Node>}
  10378. */
  10379. this.outputNodes = outputNodes;
  10380. /**
  10381. * This flag can be used for type testing.
  10382. *
  10383. * @type {Boolean}
  10384. * @readonly
  10385. * @default true
  10386. */
  10387. this.isMRTNode = true;
  10388. }
  10389. /**
  10390. * Returns `true` if the MRT node has an output with the given name.
  10391. *
  10392. * @param {String} name - The name of the output.
  10393. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  10394. */
  10395. has( name ) {
  10396. return this.outputNodes[ name ] !== undefined;
  10397. }
  10398. /**
  10399. * Returns the output node for the given name.
  10400. *
  10401. * @param {String} name - The name of the output.
  10402. * @return {Node} The output node.
  10403. */
  10404. get( name ) {
  10405. return this.outputNodes[ name ];
  10406. }
  10407. /**
  10408. * Merges the outputs of the given MRT node with the outputs of this node.
  10409. *
  10410. * @param {MRTNode} mrtNode - The MRT to merge.
  10411. * @return {MRTNode} A new MRT node with merged outputs..
  10412. */
  10413. merge( mrtNode ) {
  10414. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  10415. return mrt( outputs );
  10416. }
  10417. setup( builder ) {
  10418. const outputNodes = this.outputNodes;
  10419. const mrt = builder.renderer.getRenderTarget();
  10420. const members = [];
  10421. const textures = mrt.textures;
  10422. for ( const name in outputNodes ) {
  10423. const index = getTextureIndex( textures, name );
  10424. members[ index ] = vec4( outputNodes[ name ] );
  10425. }
  10426. this.members = members;
  10427. return super.setup( builder );
  10428. }
  10429. }
  10430. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  10431. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  10432. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  10433. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  10434. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  10435. const result = word.shiftRight( 22 ).bitXor( word );
  10436. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  10437. } );
  10438. // remapping functions https://iquilezles.org/articles/functions/
  10439. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  10440. const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) );
  10441. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  10442. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  10443. // https://github.com/cabbibo/glsl-tri-noise-3d
  10444. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  10445. return x.fract().sub( .5 ).abs();
  10446. } ).setLayout( {
  10447. name: 'tri',
  10448. type: 'float',
  10449. inputs: [
  10450. { name: 'x', type: 'float' }
  10451. ]
  10452. } );
  10453. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  10454. return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) );
  10455. } ).setLayout( {
  10456. name: 'tri3',
  10457. type: 'vec3',
  10458. inputs: [
  10459. { name: 'p', type: 'vec3' }
  10460. ]
  10461. } );
  10462. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  10463. const p = vec3( p_immutable ).toVar();
  10464. const z = float( 1.4 ).toVar();
  10465. const rz = float( 0.0 ).toVar();
  10466. const bp = vec3( p ).toVar();
  10467. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  10468. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  10469. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  10470. bp.mulAssign( 1.8 );
  10471. z.mulAssign( 1.5 );
  10472. p.mulAssign( 1.2 );
  10473. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  10474. rz.addAssign( t.div( z ) );
  10475. bp.addAssign( 0.14 );
  10476. } );
  10477. return rz;
  10478. } ).setLayout( {
  10479. name: 'triNoise3D',
  10480. type: 'float',
  10481. inputs: [
  10482. { name: 'p', type: 'vec3' },
  10483. { name: 'spd', type: 'float' },
  10484. { name: 'time', type: 'float' }
  10485. ]
  10486. } );
  10487. class FunctionOverloadingNode extends Node {
  10488. static get type() {
  10489. return 'FunctionOverloadingNode';
  10490. }
  10491. constructor( functionNodes = [], ...parametersNodes ) {
  10492. super();
  10493. this.functionNodes = functionNodes;
  10494. this.parametersNodes = parametersNodes;
  10495. this._candidateFnCall = null;
  10496. this.global = true;
  10497. }
  10498. getNodeType() {
  10499. return this.functionNodes[ 0 ].shaderNode.layout.type;
  10500. }
  10501. setup( builder ) {
  10502. const params = this.parametersNodes;
  10503. let candidateFnCall = this._candidateFnCall;
  10504. if ( candidateFnCall === null ) {
  10505. let candidateFn = null;
  10506. let candidateScore = - 1;
  10507. for ( const functionNode of this.functionNodes ) {
  10508. const shaderNode = functionNode.shaderNode;
  10509. const layout = shaderNode.layout;
  10510. if ( layout === null ) {
  10511. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  10512. }
  10513. const inputs = layout.inputs;
  10514. if ( params.length === inputs.length ) {
  10515. let score = 0;
  10516. for ( let i = 0; i < params.length; i ++ ) {
  10517. const param = params[ i ];
  10518. const input = inputs[ i ];
  10519. if ( param.getNodeType( builder ) === input.type ) {
  10520. score ++;
  10521. } else {
  10522. score = 0;
  10523. }
  10524. }
  10525. if ( score > candidateScore ) {
  10526. candidateFn = functionNode;
  10527. candidateScore = score;
  10528. }
  10529. }
  10530. }
  10531. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  10532. }
  10533. return candidateFnCall;
  10534. }
  10535. }
  10536. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  10537. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  10538. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  10539. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  10540. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  10541. // Deprecated
  10542. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  10543. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  10544. return time.mul( timeScale );
  10545. };
  10546. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  10547. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  10548. return time.mul( timeScale );
  10549. };
  10550. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  10551. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  10552. return deltaTime.mul( timeScale );
  10553. };
  10554. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  10555. const oscSquare = ( t = time ) => t.fract().round();
  10556. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  10557. const oscSawtooth = ( t = time ) => t.fract();
  10558. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  10559. return rotate( uv.sub( center ), rotation ).add( center );
  10560. } );
  10561. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  10562. const delta = uv.sub( center );
  10563. const delta2 = delta.dot( delta );
  10564. const delta4 = delta2.mul( delta2 );
  10565. const deltaOffset = delta4.mul( strength );
  10566. return uv.add( delta.mul( deltaOffset ) );
  10567. } );
  10568. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  10569. let worldMatrix;
  10570. if ( position !== null ) {
  10571. worldMatrix = modelWorldMatrix.toVar();
  10572. worldMatrix[ 3 ][ 0 ] = position.x;
  10573. worldMatrix[ 3 ][ 1 ] = position.y;
  10574. worldMatrix[ 3 ][ 2 ] = position.z;
  10575. } else {
  10576. worldMatrix = modelWorldMatrix;
  10577. }
  10578. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  10579. if ( defined( horizontal ) ) {
  10580. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  10581. modelViewMatrix[ 0 ][ 1 ] = 0;
  10582. modelViewMatrix[ 0 ][ 2 ] = 0;
  10583. }
  10584. if ( defined( vertical ) ) {
  10585. modelViewMatrix[ 1 ][ 0 ] = 0;
  10586. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  10587. modelViewMatrix[ 1 ][ 2 ] = 0;
  10588. }
  10589. modelViewMatrix[ 2 ][ 0 ] = 0;
  10590. modelViewMatrix[ 2 ][ 1 ] = 0;
  10591. modelViewMatrix[ 2 ][ 2 ] = 1;
  10592. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  10593. } );
  10594. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  10595. const depth = linearDepth();
  10596. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  10597. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  10598. return finalUV;
  10599. } );
  10600. class SpriteSheetUVNode extends Node {
  10601. static get type() {
  10602. return 'SpriteSheetUVNode';
  10603. }
  10604. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  10605. super( 'vec2' );
  10606. this.countNode = countNode;
  10607. this.uvNode = uvNode;
  10608. this.frameNode = frameNode;
  10609. }
  10610. setup() {
  10611. const { frameNode, uvNode, countNode } = this;
  10612. const { width, height } = countNode;
  10613. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  10614. const column = frameNum.mod( width );
  10615. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  10616. const scale = countNode.reciprocal();
  10617. const uvFrameOffset = vec2( column, row );
  10618. return uvNode.add( uvFrameOffset ).mul( scale );
  10619. }
  10620. }
  10621. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  10622. class TriplanarTexturesNode extends Node {
  10623. static get type() {
  10624. return 'TriplanarTexturesNode';
  10625. }
  10626. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  10627. super( 'vec4' );
  10628. this.textureXNode = textureXNode;
  10629. this.textureYNode = textureYNode;
  10630. this.textureZNode = textureZNode;
  10631. this.scaleNode = scaleNode;
  10632. this.positionNode = positionNode;
  10633. this.normalNode = normalNode;
  10634. }
  10635. setup() {
  10636. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  10637. // Ref: https://github.com/keijiro/StandardTriplanar
  10638. // Blending factor of triplanar mapping
  10639. let bf = normalNode.abs().normalize();
  10640. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  10641. // Triplanar mapping
  10642. const tx = positionNode.yz.mul( scaleNode );
  10643. const ty = positionNode.zx.mul( scaleNode );
  10644. const tz = positionNode.xy.mul( scaleNode );
  10645. // Base color
  10646. const textureX = textureXNode.value;
  10647. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  10648. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  10649. const cx = texture( textureX, tx ).mul( bf.x );
  10650. const cy = texture( textureY, ty ).mul( bf.y );
  10651. const cz = texture( textureZ, tz ).mul( bf.z );
  10652. return add( cx, cy, cz );
  10653. }
  10654. }
  10655. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  10656. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  10657. const _reflectorPlane = new Plane();
  10658. const _normal = new Vector3();
  10659. const _reflectorWorldPosition = new Vector3();
  10660. const _cameraWorldPosition = new Vector3();
  10661. const _rotationMatrix = new Matrix4();
  10662. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  10663. const clipPlane = new Vector4();
  10664. const _view = new Vector3();
  10665. const _target = new Vector3();
  10666. const _q = new Vector4();
  10667. const _size$2 = new Vector2();
  10668. const _defaultRT = new RenderTarget();
  10669. const _defaultUV = screenUV.flipX();
  10670. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  10671. let _inReflector = false;
  10672. class ReflectorNode extends TextureNode {
  10673. static get type() {
  10674. return 'ReflectorNode';
  10675. }
  10676. constructor( parameters = {} ) {
  10677. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  10678. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  10679. this._depthNode = null;
  10680. this.setUpdateMatrix( false );
  10681. }
  10682. get reflector() {
  10683. return this._reflectorBaseNode;
  10684. }
  10685. get target() {
  10686. return this._reflectorBaseNode.target;
  10687. }
  10688. getDepthNode() {
  10689. if ( this._depthNode === null ) {
  10690. if ( this._reflectorBaseNode.depth !== true ) {
  10691. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  10692. }
  10693. this._depthNode = nodeObject( new ReflectorNode( {
  10694. defaultTexture: _defaultRT.depthTexture,
  10695. reflector: this._reflectorBaseNode
  10696. } ) );
  10697. }
  10698. return this._depthNode;
  10699. }
  10700. setup( builder ) {
  10701. // ignore if used in post-processing
  10702. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  10703. return super.setup( builder );
  10704. }
  10705. clone() {
  10706. const texture = new this.constructor( this.reflectorNode );
  10707. texture._reflectorBaseNode = this._reflectorBaseNode;
  10708. return texture;
  10709. }
  10710. }
  10711. class ReflectorBaseNode extends Node {
  10712. static get type() {
  10713. return 'ReflectorBaseNode';
  10714. }
  10715. constructor( textureNode, parameters = {} ) {
  10716. super();
  10717. const {
  10718. target = new Object3D(),
  10719. resolution = 1,
  10720. generateMipmaps = false,
  10721. bounces = true,
  10722. depth = false
  10723. } = parameters;
  10724. //
  10725. this.textureNode = textureNode;
  10726. this.target = target;
  10727. this.resolution = resolution;
  10728. this.generateMipmaps = generateMipmaps;
  10729. this.bounces = bounces;
  10730. this.depth = depth;
  10731. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  10732. this.virtualCameras = new WeakMap();
  10733. this.renderTargets = new WeakMap();
  10734. }
  10735. _updateResolution( renderTarget, renderer ) {
  10736. const resolution = this.resolution;
  10737. renderer.getDrawingBufferSize( _size$2 );
  10738. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  10739. }
  10740. setup( builder ) {
  10741. this._updateResolution( _defaultRT, builder.renderer );
  10742. return super.setup( builder );
  10743. }
  10744. getVirtualCamera( camera ) {
  10745. let virtualCamera = this.virtualCameras.get( camera );
  10746. if ( virtualCamera === undefined ) {
  10747. virtualCamera = camera.clone();
  10748. this.virtualCameras.set( camera, virtualCamera );
  10749. }
  10750. return virtualCamera;
  10751. }
  10752. getRenderTarget( camera ) {
  10753. let renderTarget = this.renderTargets.get( camera );
  10754. if ( renderTarget === undefined ) {
  10755. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  10756. if ( this.generateMipmaps === true ) {
  10757. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  10758. renderTarget.texture.generateMipmaps = true;
  10759. }
  10760. if ( this.depth === true ) {
  10761. renderTarget.depthTexture = new DepthTexture();
  10762. }
  10763. this.renderTargets.set( camera, renderTarget );
  10764. }
  10765. return renderTarget;
  10766. }
  10767. updateBefore( frame ) {
  10768. if ( this.bounces === false && _inReflector ) return;
  10769. _inReflector = true;
  10770. const { scene, camera, renderer, material } = frame;
  10771. const { target } = this;
  10772. const virtualCamera = this.getVirtualCamera( camera );
  10773. const renderTarget = this.getRenderTarget( virtualCamera );
  10774. renderer.getDrawingBufferSize( _size$2 );
  10775. this._updateResolution( renderTarget, renderer );
  10776. //
  10777. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  10778. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  10779. _rotationMatrix.extractRotation( target.matrixWorld );
  10780. _normal.set( 0, 0, 1 );
  10781. _normal.applyMatrix4( _rotationMatrix );
  10782. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  10783. // Avoid rendering when reflector is facing away
  10784. if ( _view.dot( _normal ) > 0 ) return;
  10785. _view.reflect( _normal ).negate();
  10786. _view.add( _reflectorWorldPosition );
  10787. _rotationMatrix.extractRotation( camera.matrixWorld );
  10788. _lookAtPosition.set( 0, 0, - 1 );
  10789. _lookAtPosition.applyMatrix4( _rotationMatrix );
  10790. _lookAtPosition.add( _cameraWorldPosition );
  10791. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  10792. _target.reflect( _normal ).negate();
  10793. _target.add( _reflectorWorldPosition );
  10794. //
  10795. virtualCamera.coordinateSystem = camera.coordinateSystem;
  10796. virtualCamera.position.copy( _view );
  10797. virtualCamera.up.set( 0, 1, 0 );
  10798. virtualCamera.up.applyMatrix4( _rotationMatrix );
  10799. virtualCamera.up.reflect( _normal );
  10800. virtualCamera.lookAt( _target );
  10801. virtualCamera.near = camera.near;
  10802. virtualCamera.far = camera.far;
  10803. virtualCamera.updateMatrixWorld();
  10804. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  10805. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  10806. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  10807. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  10808. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  10809. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  10810. const projectionMatrix = virtualCamera.projectionMatrix;
  10811. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  10812. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  10813. _q.z = - 1.0;
  10814. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  10815. // Calculate the scaled plane vector
  10816. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  10817. const clipBias = 0;
  10818. // Replacing the third row of the projection matrix
  10819. projectionMatrix.elements[ 2 ] = clipPlane.x;
  10820. projectionMatrix.elements[ 6 ] = clipPlane.y;
  10821. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  10822. projectionMatrix.elements[ 14 ] = clipPlane.w;
  10823. //
  10824. this.textureNode.value = renderTarget.texture;
  10825. if ( this.depth === true ) {
  10826. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  10827. }
  10828. material.visible = false;
  10829. const currentRenderTarget = renderer.getRenderTarget();
  10830. const currentMRT = renderer.getMRT();
  10831. renderer.setMRT( null );
  10832. renderer.setRenderTarget( renderTarget );
  10833. renderer.render( scene, virtualCamera );
  10834. renderer.setMRT( currentMRT );
  10835. renderer.setRenderTarget( currentRenderTarget );
  10836. material.visible = true;
  10837. _inReflector = false;
  10838. }
  10839. }
  10840. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  10841. // Helper for passes that need to fill the viewport with a single quad.
  10842. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  10843. // https://github.com/mrdoob/three.js/pull/21358
  10844. class QuadGeometry extends BufferGeometry {
  10845. constructor( flipY = false ) {
  10846. super();
  10847. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  10848. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  10849. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  10850. }
  10851. }
  10852. const _geometry = /*@__PURE__*/ new QuadGeometry();
  10853. class QuadMesh extends Mesh {
  10854. constructor( material = null ) {
  10855. super( _geometry, material );
  10856. this.camera = _camera;
  10857. this.isQuadMesh = true;
  10858. }
  10859. renderAsync( renderer ) {
  10860. return renderer.renderAsync( this, _camera );
  10861. }
  10862. render( renderer ) {
  10863. renderer.render( this, _camera );
  10864. }
  10865. }
  10866. const _size$1 = /*@__PURE__*/ new Vector2();
  10867. class RTTNode extends TextureNode {
  10868. static get type() {
  10869. return 'RTTNode';
  10870. }
  10871. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  10872. const renderTarget = new RenderTarget( width, height, options );
  10873. super( renderTarget.texture, uv() );
  10874. this.node = node;
  10875. this.width = width;
  10876. this.height = height;
  10877. this.renderTarget = renderTarget;
  10878. this.textureNeedsUpdate = true;
  10879. this.autoUpdate = true;
  10880. this.updateMap = new WeakMap();
  10881. this._rttNode = null;
  10882. this._quadMesh = new QuadMesh( new NodeMaterial() );
  10883. this.updateBeforeType = NodeUpdateType.RENDER;
  10884. }
  10885. get autoSize() {
  10886. return this.width === null;
  10887. }
  10888. setup( builder ) {
  10889. this._rttNode = this.node.context( builder.getSharedContext() );
  10890. this._quadMesh.material.name = 'RTT';
  10891. this._quadMesh.material.needsUpdate = true;
  10892. return super.setup( builder );
  10893. }
  10894. setSize( width, height ) {
  10895. this.width = width;
  10896. this.height = height;
  10897. const effectiveWidth = width * this.pixelRatio;
  10898. const effectiveHeight = height * this.pixelRatio;
  10899. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  10900. this.textureNeedsUpdate = true;
  10901. }
  10902. setPixelRatio( pixelRatio ) {
  10903. this.pixelRatio = pixelRatio;
  10904. this.setSize( this.width, this.height );
  10905. }
  10906. updateBefore( { renderer } ) {
  10907. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  10908. this.textureNeedsUpdate = false;
  10909. //
  10910. if ( this.autoSize === true ) {
  10911. this.pixelRatio = renderer.getPixelRatio();
  10912. const size = renderer.getSize( _size$1 );
  10913. this.setSize( size.width, size.height );
  10914. }
  10915. //
  10916. this._quadMesh.material.fragmentNode = this._rttNode;
  10917. //
  10918. const currentRenderTarget = renderer.getRenderTarget();
  10919. renderer.setRenderTarget( this.renderTarget );
  10920. this._quadMesh.render( renderer );
  10921. renderer.setRenderTarget( currentRenderTarget );
  10922. }
  10923. clone() {
  10924. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  10925. newNode.sampler = this.sampler;
  10926. newNode.referenceNode = this;
  10927. return newNode;
  10928. }
  10929. }
  10930. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  10931. const convertToTexture = ( node, ...params ) => {
  10932. if ( node.isTextureNode ) return node;
  10933. if ( node.isPassNode ) return node.getTextureNode();
  10934. return rtt( node, ...params );
  10935. };
  10936. /** @module PostProcessingUtils **/
  10937. /**
  10938. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  10939. * depth value and the camera's inverse projection matrix.
  10940. *
  10941. * @method
  10942. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  10943. * @param {float} depth - The fragment's depth value.
  10944. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  10945. * @return {vec3} The fragments position in view space.
  10946. */
  10947. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  10948. let clipSpacePosition;
  10949. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10950. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  10951. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  10952. } else {
  10953. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  10954. }
  10955. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  10956. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  10957. } );
  10958. /**
  10959. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  10960. * and the camera's projection matrix
  10961. *
  10962. * @method
  10963. * @param {vec3} viewPosition - The fragments position in view space.
  10964. * @param {mat4} projectionMatrix - The camera's projection matrix.
  10965. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  10966. */
  10967. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  10968. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  10969. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  10970. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  10971. } );
  10972. /**
  10973. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  10974. * target is available or if flat surface normals are required.
  10975. *
  10976. * @method
  10977. * @param {vec2} uv - The texture coordinate.
  10978. * @param {DepthTexture} depthTexture - The depth texture.
  10979. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  10980. * @return {vec3} The computed normal vector.
  10981. */
  10982. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  10983. const size = textureSize( textureLoad( depthTexture ) );
  10984. const p = ivec2( uv.mul( size ) ).toVar();
  10985. const c0 = textureLoad( depthTexture, p ).toVar();
  10986. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  10987. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  10988. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  10989. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  10990. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  10991. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  10992. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  10993. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  10994. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  10995. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  10996. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  10997. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  10998. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  10999. const dpdx = dl.lessThan( dr ).select( ce.sub( getViewPosition( uv.sub( vec2( float( 1 ).div( size.x ), 0 ) ), l1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.add( vec2( float( 1 ).div( size.x ), 0 ) ), r1, projectionMatrixInverse ) ) );
  11000. const dpdy = db.lessThan( dt ).select( ce.sub( getViewPosition( uv.add( vec2( 0, float( 1 ).div( size.y ) ) ), b1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.sub( vec2( 0, float( 1 ).div( size.y ) ) ), t1, projectionMatrixInverse ) ) );
  11001. return normalize( cross( dpdx, dpdy ) );
  11002. } );
  11003. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  11004. constructor( array, itemSize, typeClass = Float32Array ) {
  11005. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  11006. super( array, itemSize );
  11007. this.isStorageInstancedBufferAttribute = true;
  11008. }
  11009. }
  11010. class StorageBufferAttribute extends BufferAttribute {
  11011. constructor( array, itemSize, typeClass = Float32Array ) {
  11012. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  11013. super( array, itemSize );
  11014. this.isStorageBufferAttribute = true;
  11015. }
  11016. }
  11017. class StorageArrayElementNode extends ArrayElementNode {
  11018. static get type() {
  11019. return 'StorageArrayElementNode';
  11020. }
  11021. constructor( storageBufferNode, indexNode ) {
  11022. super( storageBufferNode, indexNode );
  11023. this.isStorageArrayElementNode = true;
  11024. }
  11025. set storageBufferNode( value ) {
  11026. this.node = value;
  11027. }
  11028. get storageBufferNode() {
  11029. return this.node;
  11030. }
  11031. setup( builder ) {
  11032. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11033. if ( this.node.isPBO === true ) {
  11034. builder.setupPBO( this.node );
  11035. }
  11036. }
  11037. return super.setup( builder );
  11038. }
  11039. generate( builder, output ) {
  11040. let snippet;
  11041. const isAssignContext = builder.context.assign;
  11042. //
  11043. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11044. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11045. snippet = builder.generatePBO( this );
  11046. } else {
  11047. snippet = this.node.build( builder );
  11048. }
  11049. } else {
  11050. snippet = super.generate( builder );
  11051. }
  11052. if ( isAssignContext !== true ) {
  11053. const type = this.getNodeType( builder );
  11054. snippet = builder.format( snippet, type, output );
  11055. }
  11056. return snippet;
  11057. }
  11058. }
  11059. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  11060. class StorageBufferNode extends BufferNode {
  11061. static get type() {
  11062. return 'StorageBufferNode';
  11063. }
  11064. constructor( value, bufferType = null, bufferCount = 0 ) {
  11065. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11066. bufferType = getTypeFromLength( value.itemSize );
  11067. bufferCount = value.count;
  11068. }
  11069. super( value, bufferType, bufferCount );
  11070. this.isStorageBufferNode = true;
  11071. this.access = NodeAccess.READ_WRITE;
  11072. this.isAtomic = false;
  11073. this.isPBO = false;
  11074. this.bufferCount = bufferCount;
  11075. this._attribute = null;
  11076. this._varying = null;
  11077. this.global = true;
  11078. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11079. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11080. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11081. else value.isStorageBufferAttribute = true;
  11082. }
  11083. }
  11084. getHash( builder ) {
  11085. if ( this.bufferCount === 0 ) {
  11086. let bufferData = builder.globalCache.getData( this.value );
  11087. if ( bufferData === undefined ) {
  11088. bufferData = {
  11089. node: this
  11090. };
  11091. builder.globalCache.setData( this.value, bufferData );
  11092. }
  11093. return bufferData.node.uuid;
  11094. }
  11095. return this.uuid;
  11096. }
  11097. getInputType( /*builder*/ ) {
  11098. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11099. }
  11100. element( indexNode ) {
  11101. return storageElement( this, indexNode );
  11102. }
  11103. setPBO( value ) {
  11104. this.isPBO = value;
  11105. return this;
  11106. }
  11107. getPBO() {
  11108. return this.isPBO;
  11109. }
  11110. setAccess( value ) {
  11111. this.access = value;
  11112. return this;
  11113. }
  11114. toReadOnly() {
  11115. return this.setAccess( NodeAccess.READ_ONLY );
  11116. }
  11117. setAtomic( value ) {
  11118. this.isAtomic = value;
  11119. return this;
  11120. }
  11121. toAtomic() {
  11122. return this.setAtomic( true );
  11123. }
  11124. getAttributeData() {
  11125. if ( this._attribute === null ) {
  11126. this._attribute = bufferAttribute( this.value );
  11127. this._varying = varying( this._attribute );
  11128. }
  11129. return {
  11130. attribute: this._attribute,
  11131. varying: this._varying
  11132. };
  11133. }
  11134. getNodeType( builder ) {
  11135. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11136. return super.getNodeType( builder );
  11137. }
  11138. const { attribute } = this.getAttributeData();
  11139. return attribute.getNodeType( builder );
  11140. }
  11141. generate( builder ) {
  11142. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11143. return super.generate( builder );
  11144. }
  11145. const { attribute, varying } = this.getAttributeData();
  11146. const output = varying.build( builder );
  11147. builder.registerTransform( output, attribute );
  11148. return output;
  11149. }
  11150. }
  11151. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11152. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11153. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11154. return storage( value, type, count ).setPBO( true );
  11155. };
  11156. const attributeArray = ( count, type = 'float' ) => {
  11157. const itemSize = getLengthFromType( type );
  11158. const buffer = new StorageBufferAttribute( count, itemSize );
  11159. const node = storage( buffer, type, count );
  11160. return node;
  11161. };
  11162. const instancedArray = ( count, type = 'float' ) => {
  11163. const itemSize = getLengthFromType( type );
  11164. const buffer = new StorageInstancedBufferAttribute( count, itemSize );
  11165. const node = storage( buffer, type, count );
  11166. return node;
  11167. };
  11168. class VertexColorNode extends AttributeNode {
  11169. static get type() {
  11170. return 'VertexColorNode';
  11171. }
  11172. constructor( index = 0 ) {
  11173. super( null, 'vec4' );
  11174. this.isVertexColorNode = true;
  11175. this.index = index;
  11176. }
  11177. getAttributeName( /*builder*/ ) {
  11178. const index = this.index;
  11179. return 'color' + ( index > 0 ? index : '' );
  11180. }
  11181. generate( builder ) {
  11182. const attributeName = this.getAttributeName( builder );
  11183. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  11184. let result;
  11185. if ( geometryAttribute === true ) {
  11186. result = super.generate( builder );
  11187. } else {
  11188. // Vertex color fallback should be white
  11189. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  11190. }
  11191. return result;
  11192. }
  11193. serialize( data ) {
  11194. super.serialize( data );
  11195. data.index = this.index;
  11196. }
  11197. deserialize( data ) {
  11198. super.deserialize( data );
  11199. this.index = data.index;
  11200. }
  11201. }
  11202. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  11203. class PointUVNode extends Node {
  11204. static get type() {
  11205. return 'PointUVNode';
  11206. }
  11207. constructor() {
  11208. super( 'vec2' );
  11209. this.isPointUVNode = true;
  11210. }
  11211. generate( /*builder*/ ) {
  11212. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  11213. }
  11214. }
  11215. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  11216. const _e1 = /*@__PURE__*/ new Euler();
  11217. const _m1 = /*@__PURE__*/ new Matrix4();
  11218. class SceneNode extends Node {
  11219. static get type() {
  11220. return 'SceneNode';
  11221. }
  11222. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  11223. super();
  11224. this.scope = scope;
  11225. this.scene = scene;
  11226. }
  11227. setup( builder ) {
  11228. const scope = this.scope;
  11229. const scene = this.scene !== null ? this.scene : builder.scene;
  11230. let output;
  11231. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  11232. output = reference( 'backgroundBlurriness', 'float', scene );
  11233. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  11234. output = reference( 'backgroundIntensity', 'float', scene );
  11235. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  11236. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  11237. const background = scene.background;
  11238. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  11239. _e1.copy( scene.backgroundRotation );
  11240. // accommodate left-handed frame
  11241. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  11242. _m1.makeRotationFromEuler( _e1 );
  11243. } else {
  11244. _m1.identity();
  11245. }
  11246. return _m1;
  11247. } );
  11248. } else {
  11249. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  11250. }
  11251. return output;
  11252. }
  11253. }
  11254. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  11255. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  11256. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  11257. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  11258. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  11259. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  11260. class StorageTextureNode extends TextureNode {
  11261. static get type() {
  11262. return 'StorageTextureNode';
  11263. }
  11264. constructor( value, uvNode, storeNode = null ) {
  11265. super( value, uvNode );
  11266. this.storeNode = storeNode;
  11267. this.isStorageTextureNode = true;
  11268. this.access = NodeAccess.WRITE_ONLY;
  11269. }
  11270. getInputType( /*builder*/ ) {
  11271. return 'storageTexture';
  11272. }
  11273. setup( builder ) {
  11274. super.setup( builder );
  11275. const properties = builder.getNodeProperties( this );
  11276. properties.storeNode = this.storeNode;
  11277. }
  11278. setAccess( value ) {
  11279. this.access = value;
  11280. return this;
  11281. }
  11282. generate( builder, output ) {
  11283. let snippet;
  11284. if ( this.storeNode !== null ) {
  11285. snippet = this.generateStore( builder );
  11286. } else {
  11287. snippet = super.generate( builder, output );
  11288. }
  11289. return snippet;
  11290. }
  11291. toReadWrite() {
  11292. return this.setAccess( NodeAccess.READ_WRITE );
  11293. }
  11294. toReadOnly() {
  11295. return this.setAccess( NodeAccess.READ_ONLY );
  11296. }
  11297. toWriteOnly() {
  11298. return this.setAccess( NodeAccess.WRITE_ONLY );
  11299. }
  11300. generateStore( builder ) {
  11301. const properties = builder.getNodeProperties( this );
  11302. const { uvNode, storeNode } = properties;
  11303. const textureProperty = super.generate( builder, 'property' );
  11304. const uvSnippet = uvNode.build( builder, 'uvec2' );
  11305. const storeSnippet = storeNode.build( builder, 'vec4' );
  11306. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  11307. builder.addLineFlowCode( snippet, this );
  11308. }
  11309. }
  11310. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  11311. const textureStore = ( value, uvNode, storeNode ) => {
  11312. const node = storageTexture( value, uvNode, storeNode );
  11313. if ( storeNode !== null ) node.append();
  11314. return node;
  11315. };
  11316. class UserDataNode extends ReferenceNode {
  11317. static get type() {
  11318. return 'UserDataNode';
  11319. }
  11320. constructor( property, inputType, userData = null ) {
  11321. super( property, inputType, userData );
  11322. this.userData = userData;
  11323. }
  11324. updateReference( state ) {
  11325. this.reference = this.userData !== null ? this.userData : state.object.userData;
  11326. return this.reference;
  11327. }
  11328. }
  11329. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  11330. const _objectData = new WeakMap();
  11331. class VelocityNode extends TempNode {
  11332. static get type() {
  11333. return 'VelocityNode';
  11334. }
  11335. constructor() {
  11336. super( 'vec2' );
  11337. this.projectionMatrix = null;
  11338. this.updateType = NodeUpdateType.OBJECT;
  11339. this.updateAfterType = NodeUpdateType.OBJECT;
  11340. this.previousModelWorldMatrix = uniform( new Matrix4() );
  11341. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  11342. this.previousCameraViewMatrix = uniform( new Matrix4() );
  11343. }
  11344. setProjectionMatrix( projectionMatrix ) {
  11345. this.projectionMatrix = projectionMatrix;
  11346. }
  11347. update( { frameId, camera, object } ) {
  11348. const previousModelMatrix = getPreviousMatrix( object );
  11349. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  11350. //
  11351. const cameraData = getData( camera );
  11352. if ( cameraData.frameId !== frameId ) {
  11353. cameraData.frameId = frameId;
  11354. if ( cameraData.previousProjectionMatrix === undefined ) {
  11355. cameraData.previousProjectionMatrix = new Matrix4();
  11356. cameraData.previousCameraViewMatrix = new Matrix4();
  11357. cameraData.currentProjectionMatrix = new Matrix4();
  11358. cameraData.currentCameraViewMatrix = new Matrix4();
  11359. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  11360. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  11361. } else {
  11362. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  11363. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  11364. }
  11365. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  11366. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  11367. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  11368. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  11369. }
  11370. }
  11371. updateAfter( { object } ) {
  11372. getPreviousMatrix( object ).copy( object.matrixWorld );
  11373. }
  11374. setup( /*builder*/ ) {
  11375. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  11376. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  11377. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  11378. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  11379. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  11380. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  11381. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  11382. return velocity;
  11383. }
  11384. }
  11385. function getData( object ) {
  11386. let objectData = _objectData.get( object );
  11387. if ( objectData === undefined ) {
  11388. objectData = {};
  11389. _objectData.set( object, objectData );
  11390. }
  11391. return objectData;
  11392. }
  11393. function getPreviousMatrix( object, index = 0 ) {
  11394. const objectData = getData( object );
  11395. let matrix = objectData[ index ];
  11396. if ( matrix === undefined ) {
  11397. objectData[ index ] = matrix = new Matrix4();
  11398. }
  11399. return matrix;
  11400. }
  11401. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  11402. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11403. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  11404. } ).setLayout( {
  11405. name: 'blendBurn',
  11406. type: 'vec3',
  11407. inputs: [
  11408. { name: 'base', type: 'vec3' },
  11409. { name: 'blend', type: 'vec3' }
  11410. ]
  11411. } );
  11412. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11413. return min$1( base.div( blend.oneMinus() ), 1.0 );
  11414. } ).setLayout( {
  11415. name: 'blendDodge',
  11416. type: 'vec3',
  11417. inputs: [
  11418. { name: 'base', type: 'vec3' },
  11419. { name: 'blend', type: 'vec3' }
  11420. ]
  11421. } );
  11422. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11423. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  11424. } ).setLayout( {
  11425. name: 'blendScreen',
  11426. type: 'vec3',
  11427. inputs: [
  11428. { name: 'base', type: 'vec3' },
  11429. { name: 'blend', type: 'vec3' }
  11430. ]
  11431. } );
  11432. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11433. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  11434. } ).setLayout( {
  11435. name: 'blendOverlay',
  11436. type: 'vec3',
  11437. inputs: [
  11438. { name: 'base', type: 'vec3' },
  11439. { name: 'blend', type: 'vec3' }
  11440. ]
  11441. } );
  11442. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  11443. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  11444. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  11445. } ).setLayout( {
  11446. name: 'blendColor',
  11447. type: 'vec4',
  11448. inputs: [
  11449. { name: 'base', type: 'vec4' },
  11450. { name: 'blend', type: 'vec4' }
  11451. ]
  11452. } );
  11453. // deprecated
  11454. const burn = ( ...params ) => { // @deprecated, r171
  11455. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  11456. return blendBurn( params );
  11457. };
  11458. const dodge = ( ...params ) => { // @deprecated, r171
  11459. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  11460. return blendDodge( params );
  11461. };
  11462. const screen = ( ...params ) => { // @deprecated, r171
  11463. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  11464. return blendScreen( params );
  11465. };
  11466. const overlay = ( ...params ) => { // @deprecated, r171
  11467. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  11468. return blendOverlay( params );
  11469. };
  11470. /** @module ColorAdjustment **/
  11471. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  11472. return luminance( color.rgb );
  11473. } );
  11474. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  11475. return adjustment.mix( luminance( color.rgb ), color.rgb );
  11476. } );
  11477. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  11478. const average = add( color.r, color.g, color.b ).div( 3.0 );
  11479. const mx = color.r.max( color.g.max( color.b ) );
  11480. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  11481. return mix( color.rgb, mx, amt );
  11482. } );
  11483. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  11484. const k = vec3( 0.57735, 0.57735, 0.57735 );
  11485. const cosAngle = adjustment.cos();
  11486. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  11487. } );
  11488. const luminance = (
  11489. color,
  11490. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  11491. ) => dot( color, luminanceCoefficients );
  11492. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  11493. /**
  11494. * Color Decision List (CDL) v1.2
  11495. *
  11496. * Compact representation of color grading information, defined by slope, offset, power, and
  11497. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  11498. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  11499. *
  11500. * @method
  11501. * @param {vec4} color Input (-Infinity < input < +Infinity)
  11502. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  11503. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  11504. * @param {number | vec3} power Power (0 < power < +Infinity)
  11505. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  11506. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  11507. * @return Output, -Infinity < output < +Infinity
  11508. *
  11509. * References:
  11510. * - ASC CDL v1.2
  11511. * - {@link https://blender.stackexchange.com/a/55239/43930}
  11512. * - {@link https://docs.acescentral.com/specifications/acescc/}
  11513. */
  11514. const cdl = /*@__PURE__*/ Fn( ( [
  11515. color,
  11516. slope = vec3( 1 ),
  11517. offset = vec3( 0 ),
  11518. power = vec3( 1 ),
  11519. saturation = float( 1 ),
  11520. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  11521. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  11522. ] ) => {
  11523. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  11524. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  11525. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  11526. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  11527. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  11528. const pv = v.pow( power ).toVar();
  11529. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  11530. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  11531. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  11532. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  11533. return vec4( v.rgb, color.a );
  11534. } );
  11535. class PosterizeNode extends TempNode {
  11536. static get type() {
  11537. return 'PosterizeNode';
  11538. }
  11539. constructor( sourceNode, stepsNode ) {
  11540. super();
  11541. this.sourceNode = sourceNode;
  11542. this.stepsNode = stepsNode;
  11543. }
  11544. setup() {
  11545. const { sourceNode, stepsNode } = this;
  11546. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  11547. }
  11548. }
  11549. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  11550. const _size = /*@__PURE__*/ new Vector2();
  11551. class PassTextureNode extends TextureNode {
  11552. static get type() {
  11553. return 'PassTextureNode';
  11554. }
  11555. constructor( passNode, texture ) {
  11556. super( texture );
  11557. this.passNode = passNode;
  11558. this.setUpdateMatrix( false );
  11559. }
  11560. setup( builder ) {
  11561. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  11562. return super.setup( builder );
  11563. }
  11564. clone() {
  11565. return new this.constructor( this.passNode, this.value );
  11566. }
  11567. }
  11568. class PassMultipleTextureNode extends PassTextureNode {
  11569. static get type() {
  11570. return 'PassMultipleTextureNode';
  11571. }
  11572. constructor( passNode, textureName, previousTexture = false ) {
  11573. super( passNode, null );
  11574. this.textureName = textureName;
  11575. this.previousTexture = previousTexture;
  11576. }
  11577. updateTexture() {
  11578. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  11579. }
  11580. setup( builder ) {
  11581. this.updateTexture();
  11582. return super.setup( builder );
  11583. }
  11584. clone() {
  11585. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  11586. }
  11587. }
  11588. class PassNode extends TempNode {
  11589. static get type() {
  11590. return 'PassNode';
  11591. }
  11592. constructor( scope, scene, camera, options = {} ) {
  11593. super( 'vec4' );
  11594. this.scope = scope;
  11595. this.scene = scene;
  11596. this.camera = camera;
  11597. this.options = options;
  11598. this._pixelRatio = 1;
  11599. this._width = 1;
  11600. this._height = 1;
  11601. const depthTexture = new DepthTexture();
  11602. depthTexture.isRenderTargetTexture = true;
  11603. //depthTexture.type = FloatType;
  11604. depthTexture.name = 'depth';
  11605. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  11606. renderTarget.texture.name = 'output';
  11607. renderTarget.depthTexture = depthTexture;
  11608. this.renderTarget = renderTarget;
  11609. this.updateBeforeType = NodeUpdateType.FRAME;
  11610. this._textures = {
  11611. output: renderTarget.texture,
  11612. depth: depthTexture
  11613. };
  11614. this._textureNodes = {};
  11615. this._linearDepthNodes = {};
  11616. this._viewZNodes = {};
  11617. this._previousTextures = {};
  11618. this._previousTextureNodes = {};
  11619. this._cameraNear = uniform( 0 );
  11620. this._cameraFar = uniform( 0 );
  11621. this._mrt = null;
  11622. this.isPassNode = true;
  11623. }
  11624. setMRT( mrt ) {
  11625. this._mrt = mrt;
  11626. return this;
  11627. }
  11628. getMRT() {
  11629. return this._mrt;
  11630. }
  11631. isGlobal() {
  11632. return true;
  11633. }
  11634. getTexture( name ) {
  11635. let texture = this._textures[ name ];
  11636. if ( texture === undefined ) {
  11637. const refTexture = this.renderTarget.texture;
  11638. texture = refTexture.clone();
  11639. texture.isRenderTargetTexture = true;
  11640. texture.name = name;
  11641. this._textures[ name ] = texture;
  11642. this.renderTarget.textures.push( texture );
  11643. }
  11644. return texture;
  11645. }
  11646. getPreviousTexture( name ) {
  11647. let texture = this._previousTextures[ name ];
  11648. if ( texture === undefined ) {
  11649. texture = this.getTexture( name ).clone();
  11650. texture.isRenderTargetTexture = true;
  11651. this._previousTextures[ name ] = texture;
  11652. }
  11653. return texture;
  11654. }
  11655. toggleTexture( name ) {
  11656. const prevTexture = this._previousTextures[ name ];
  11657. if ( prevTexture !== undefined ) {
  11658. const texture = this._textures[ name ];
  11659. const index = this.renderTarget.textures.indexOf( texture );
  11660. this.renderTarget.textures[ index ] = prevTexture;
  11661. this._textures[ name ] = prevTexture;
  11662. this._previousTextures[ name ] = texture;
  11663. this._textureNodes[ name ].updateTexture();
  11664. this._previousTextureNodes[ name ].updateTexture();
  11665. }
  11666. }
  11667. getTextureNode( name = 'output' ) {
  11668. let textureNode = this._textureNodes[ name ];
  11669. if ( textureNode === undefined ) {
  11670. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  11671. textureNode.updateTexture();
  11672. this._textureNodes[ name ] = textureNode;
  11673. }
  11674. return textureNode;
  11675. }
  11676. getPreviousTextureNode( name = 'output' ) {
  11677. let textureNode = this._previousTextureNodes[ name ];
  11678. if ( textureNode === undefined ) {
  11679. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  11680. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  11681. textureNode.updateTexture();
  11682. this._previousTextureNodes[ name ] = textureNode;
  11683. }
  11684. return textureNode;
  11685. }
  11686. getViewZNode( name = 'depth' ) {
  11687. let viewZNode = this._viewZNodes[ name ];
  11688. if ( viewZNode === undefined ) {
  11689. const cameraNear = this._cameraNear;
  11690. const cameraFar = this._cameraFar;
  11691. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  11692. }
  11693. return viewZNode;
  11694. }
  11695. getLinearDepthNode( name = 'depth' ) {
  11696. let linearDepthNode = this._linearDepthNodes[ name ];
  11697. if ( linearDepthNode === undefined ) {
  11698. const cameraNear = this._cameraNear;
  11699. const cameraFar = this._cameraFar;
  11700. const viewZNode = this.getViewZNode( name );
  11701. // TODO: just if ( builder.camera.isPerspectiveCamera )
  11702. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  11703. }
  11704. return linearDepthNode;
  11705. }
  11706. setup( { renderer } ) {
  11707. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  11708. // Disable MSAA for WebGL backend for now
  11709. if ( renderer.backend.isWebGLBackend === true ) {
  11710. this.renderTarget.samples = 0;
  11711. }
  11712. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  11713. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  11714. }
  11715. updateBefore( frame ) {
  11716. const { renderer } = frame;
  11717. const { scene, camera } = this;
  11718. this._pixelRatio = renderer.getPixelRatio();
  11719. const size = renderer.getSize( _size );
  11720. this.setSize( size.width, size.height );
  11721. const currentRenderTarget = renderer.getRenderTarget();
  11722. const currentMRT = renderer.getMRT();
  11723. this._cameraNear.value = camera.near;
  11724. this._cameraFar.value = camera.far;
  11725. for ( const name in this._previousTextures ) {
  11726. this.toggleTexture( name );
  11727. }
  11728. renderer.setRenderTarget( this.renderTarget );
  11729. renderer.setMRT( this._mrt );
  11730. renderer.render( scene, camera );
  11731. renderer.setRenderTarget( currentRenderTarget );
  11732. renderer.setMRT( currentMRT );
  11733. }
  11734. setSize( width, height ) {
  11735. this._width = width;
  11736. this._height = height;
  11737. const effectiveWidth = this._width * this._pixelRatio;
  11738. const effectiveHeight = this._height * this._pixelRatio;
  11739. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  11740. }
  11741. setPixelRatio( pixelRatio ) {
  11742. this._pixelRatio = pixelRatio;
  11743. this.setSize( this._width, this._height );
  11744. }
  11745. dispose() {
  11746. this.renderTarget.dispose();
  11747. }
  11748. }
  11749. PassNode.COLOR = 'color';
  11750. PassNode.DEPTH = 'depth';
  11751. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  11752. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  11753. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  11754. class ToonOutlinePassNode extends PassNode {
  11755. static get type() {
  11756. return 'ToonOutlinePassNode';
  11757. }
  11758. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  11759. super( PassNode.COLOR, scene, camera );
  11760. this.colorNode = colorNode;
  11761. this.thicknessNode = thicknessNode;
  11762. this.alphaNode = alphaNode;
  11763. this._materialCache = new WeakMap();
  11764. }
  11765. updateBefore( frame ) {
  11766. const { renderer } = frame;
  11767. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  11768. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  11769. // only render outline for supported materials
  11770. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  11771. if ( material.wireframe === false ) {
  11772. const outlineMaterial = this._getOutlineMaterial( material );
  11773. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  11774. }
  11775. }
  11776. // default
  11777. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  11778. } );
  11779. super.updateBefore( frame );
  11780. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  11781. }
  11782. _createMaterial() {
  11783. const material = new NodeMaterial();
  11784. material.isMeshToonOutlineMaterial = true;
  11785. material.name = 'Toon_Outline';
  11786. material.side = BackSide;
  11787. // vertex node
  11788. const outlineNormal = normalLocal.negate();
  11789. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  11790. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  11791. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  11792. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  11793. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  11794. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  11795. // color node
  11796. material.colorNode = vec4( this.colorNode, this.alphaNode );
  11797. return material;
  11798. }
  11799. _getOutlineMaterial( originalMaterial ) {
  11800. let outlineMaterial = this._materialCache.get( originalMaterial );
  11801. if ( outlineMaterial === undefined ) {
  11802. outlineMaterial = this._createMaterial();
  11803. this._materialCache.set( originalMaterial, outlineMaterial );
  11804. }
  11805. return outlineMaterial;
  11806. }
  11807. }
  11808. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  11809. // exposure only
  11810. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11811. return color.mul( exposure ).clamp();
  11812. } ).setLayout( {
  11813. name: 'linearToneMapping',
  11814. type: 'vec3',
  11815. inputs: [
  11816. { name: 'color', type: 'vec3' },
  11817. { name: 'exposure', type: 'float' }
  11818. ]
  11819. } );
  11820. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  11821. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11822. color = color.mul( exposure );
  11823. return color.div( color.add( 1.0 ) ).clamp();
  11824. } ).setLayout( {
  11825. name: 'reinhardToneMapping',
  11826. type: 'vec3',
  11827. inputs: [
  11828. { name: 'color', type: 'vec3' },
  11829. { name: 'exposure', type: 'float' }
  11830. ]
  11831. } );
  11832. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  11833. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11834. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  11835. color = color.mul( exposure );
  11836. color = color.sub( 0.004 ).max( 0.0 );
  11837. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  11838. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  11839. return a.div( b ).pow( 2.2 );
  11840. } ).setLayout( {
  11841. name: 'cineonToneMapping',
  11842. type: 'vec3',
  11843. inputs: [
  11844. { name: 'color', type: 'vec3' },
  11845. { name: 'exposure', type: 'float' }
  11846. ]
  11847. } );
  11848. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  11849. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  11850. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  11851. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  11852. return a.div( b );
  11853. } );
  11854. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  11855. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11856. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  11857. const ACESInputMat = mat3(
  11858. 0.59719, 0.35458, 0.04823,
  11859. 0.07600, 0.90834, 0.01566,
  11860. 0.02840, 0.13383, 0.83777
  11861. );
  11862. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  11863. const ACESOutputMat = mat3(
  11864. 1.60475, - 0.53108, - 0.07367,
  11865. - 0.10208, 1.10813, - 0.00605,
  11866. - 0.00327, - 0.07276, 1.07602
  11867. );
  11868. color = color.mul( exposure ).div( 0.6 );
  11869. color = ACESInputMat.mul( color );
  11870. // Apply RRT and ODT
  11871. color = RRTAndODTFit( color );
  11872. color = ACESOutputMat.mul( color );
  11873. // Clamp to [0, 1]
  11874. return color.clamp();
  11875. } ).setLayout( {
  11876. name: 'acesFilmicToneMapping',
  11877. type: 'vec3',
  11878. inputs: [
  11879. { name: 'color', type: 'vec3' },
  11880. { name: 'exposure', type: 'float' }
  11881. ]
  11882. } );
  11883. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  11884. const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  11885. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  11886. const x = vec3( x_immutable ).toVar();
  11887. const x2 = vec3( x.mul( x ) ).toVar();
  11888. const x4 = vec3( x2.mul( x2 ) ).toVar();
  11889. return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) );
  11890. } );
  11891. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11892. const colortone = vec3( color ).toVar();
  11893. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  11894. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  11895. const AgxMinEv = float( - 12.47393 );
  11896. const AgxMaxEv = float( 4.026069 );
  11897. colortone.mulAssign( exposure );
  11898. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  11899. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  11900. colortone.assign( max$1( colortone, 1e-10 ) );
  11901. colortone.assign( log2( colortone ) );
  11902. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  11903. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  11904. colortone.assign( agxDefaultContrastApprox( colortone ) );
  11905. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  11906. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  11907. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  11908. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  11909. return colortone;
  11910. } ).setLayout( {
  11911. name: 'agxToneMapping',
  11912. type: 'vec3',
  11913. inputs: [
  11914. { name: 'color', type: 'vec3' },
  11915. { name: 'exposure', type: 'float' }
  11916. ]
  11917. } );
  11918. // https://modelviewer.dev/examples/tone-mapping
  11919. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11920. const StartCompression = float( 0.8 - 0.04 );
  11921. const Desaturation = float( 0.15 );
  11922. color = color.mul( exposure );
  11923. const x = min$1( color.r, min$1( color.g, color.b ) );
  11924. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  11925. color.subAssign( offset );
  11926. const peak = max$1( color.r, max$1( color.g, color.b ) );
  11927. If( peak.lessThan( StartCompression ), () => {
  11928. return color;
  11929. } );
  11930. const d = sub( 1, StartCompression );
  11931. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  11932. color.mulAssign( newPeak.div( peak ) );
  11933. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  11934. return mix( color, vec3( newPeak ), g );
  11935. } ).setLayout( {
  11936. name: 'neutralToneMapping',
  11937. type: 'vec3',
  11938. inputs: [
  11939. { name: 'color', type: 'vec3' },
  11940. { name: 'exposure', type: 'float' }
  11941. ]
  11942. } );
  11943. /**
  11944. * This class represents native code sections. It is the base
  11945. * class for modules like {@link FunctionNode} which allows to implement
  11946. * functions with native shader languages.
  11947. *
  11948. * @augments Node
  11949. */
  11950. class CodeNode extends Node {
  11951. static get type() {
  11952. return 'CodeNode';
  11953. }
  11954. /**
  11955. * Constructs a new code node.
  11956. *
  11957. * @param {String} [code=''] - The native code.
  11958. * @param {Array<Node>} [includes=[]] - An array of includes.
  11959. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  11960. */
  11961. constructor( code = '', includes = [], language = '' ) {
  11962. super( 'code' );
  11963. /**
  11964. * This flag can be used for type testing.
  11965. *
  11966. * @type {Boolean}
  11967. * @readonly
  11968. * @default true
  11969. */
  11970. this.isCodeNode = true;
  11971. /**
  11972. * The native code.
  11973. *
  11974. * @type {String}
  11975. * @default ''
  11976. */
  11977. this.code = code;
  11978. /**
  11979. * An array of includes
  11980. *
  11981. * @type {Array<Node>}
  11982. * @default []
  11983. */
  11984. this.includes = includes;
  11985. /**
  11986. * The used language.
  11987. *
  11988. * @type {('js'|'wgsl'|'glsl')}
  11989. * @default ''
  11990. */
  11991. this.language = language;
  11992. }
  11993. /**
  11994. * The method is overwritten so it always returns `true`.
  11995. *
  11996. * @return {Boolean} Whether this node is global or not.
  11997. */
  11998. isGlobal() {
  11999. return true;
  12000. }
  12001. /**
  12002. * Sets the includes of this code node.
  12003. *
  12004. * @param {Array<Node>} includes - The includes to set.
  12005. * @return {CodeNode} A reference to this node.
  12006. */
  12007. setIncludes( includes ) {
  12008. this.includes = includes;
  12009. return this;
  12010. }
  12011. /**
  12012. * Returns the includes of this code node.
  12013. *
  12014. * @param {NodeBuilder} builder - The current node builder.
  12015. * @return {Array<Node>} The includes.
  12016. */
  12017. getIncludes( /*builder*/ ) {
  12018. return this.includes;
  12019. }
  12020. generate( builder ) {
  12021. const includes = this.getIncludes( builder );
  12022. for ( const include of includes ) {
  12023. include.build( builder );
  12024. }
  12025. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  12026. nodeCode.code = this.code;
  12027. return nodeCode.code;
  12028. }
  12029. serialize( data ) {
  12030. super.serialize( data );
  12031. data.code = this.code;
  12032. data.language = this.language;
  12033. }
  12034. deserialize( data ) {
  12035. super.deserialize( data );
  12036. this.code = data.code;
  12037. this.language = data.language;
  12038. }
  12039. }
  12040. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  12041. const js = ( src, includes ) => code( src, includes, 'js' );
  12042. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  12043. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  12044. /**
  12045. * This class represents a native shader function. It can be used to implement
  12046. * certain aspects of a node material with native shader code. There are two predefined
  12047. * TSL functions for easier usage.
  12048. *
  12049. * - `wgslFn`: Creates a WGSL function node.
  12050. * - `glslFn`: Creates a GLSL function node.
  12051. *
  12052. * A basic example with one include looks like so:
  12053. *
  12054. * ```js
  12055. * const desaturateWGSLFn = wgslFn( `
  12056. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  12057. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  12058. * return vec3<f32>( dot( lum, color ) );
  12059. * }`
  12060. *);
  12061. * const someWGSLFn = wgslFn( `
  12062. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  12063. * return desaturate( color );
  12064. * }
  12065. * `, [ desaturateWGSLFn ] );
  12066. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  12067. *```
  12068. * @augments CodeNode
  12069. */
  12070. class FunctionNode extends CodeNode {
  12071. static get type() {
  12072. return 'FunctionNode';
  12073. }
  12074. /**
  12075. * Constructs a new function node.
  12076. *
  12077. * @param {String} [code=''] - The native code.
  12078. * @param {Array<Node>} [includes=[]] - An array of includes.
  12079. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  12080. */
  12081. constructor( code = '', includes = [], language = '' ) {
  12082. super( code, includes, language );
  12083. }
  12084. getNodeType( builder ) {
  12085. return this.getNodeFunction( builder ).type;
  12086. }
  12087. /**
  12088. * Returns the inputs of this function node.
  12089. *
  12090. * @param {NodeBuilder} builder - The current node builder.
  12091. * @return {Array<NodeFunctionInput>} The inputs.
  12092. */
  12093. getInputs( builder ) {
  12094. return this.getNodeFunction( builder ).inputs;
  12095. }
  12096. /**
  12097. * Returns the node function for this function node.
  12098. *
  12099. * @param {NodeBuilder} builder - The current node builder.
  12100. * @return {NodeFunction} The node function.
  12101. */
  12102. getNodeFunction( builder ) {
  12103. const nodeData = builder.getDataFromNode( this );
  12104. let nodeFunction = nodeData.nodeFunction;
  12105. if ( nodeFunction === undefined ) {
  12106. nodeFunction = builder.parser.parseFunction( this.code );
  12107. nodeData.nodeFunction = nodeFunction;
  12108. }
  12109. return nodeFunction;
  12110. }
  12111. generate( builder, output ) {
  12112. super.generate( builder );
  12113. const nodeFunction = this.getNodeFunction( builder );
  12114. const name = nodeFunction.name;
  12115. const type = nodeFunction.type;
  12116. const nodeCode = builder.getCodeFromNode( this, type );
  12117. if ( name !== '' ) {
  12118. // use a custom property name
  12119. nodeCode.name = name;
  12120. }
  12121. const propertyName = builder.getPropertyName( nodeCode );
  12122. const code = this.getNodeFunction( builder ).getCode( propertyName );
  12123. nodeCode.code = code + '\n';
  12124. if ( output === 'property' ) {
  12125. return propertyName;
  12126. } else {
  12127. return builder.format( `${ propertyName }()`, type, output );
  12128. }
  12129. }
  12130. }
  12131. const nativeFn = ( code, includes = [], language = '' ) => {
  12132. for ( let i = 0; i < includes.length; i ++ ) {
  12133. const include = includes[ i ];
  12134. // TSL Function: glslFn, wgslFn
  12135. if ( typeof include === 'function' ) {
  12136. includes[ i ] = include.functionNode;
  12137. }
  12138. }
  12139. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  12140. const fn = ( ...params ) => functionNode.call( ...params );
  12141. fn.functionNode = functionNode;
  12142. return fn;
  12143. };
  12144. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  12145. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  12146. class ScriptableValueNode extends Node {
  12147. static get type() {
  12148. return 'ScriptableValueNode';
  12149. }
  12150. constructor( value = null ) {
  12151. super();
  12152. this._value = value;
  12153. this._cache = null;
  12154. this.inputType = null;
  12155. this.outputType = null;
  12156. this.events = new EventDispatcher();
  12157. this.isScriptableValueNode = true;
  12158. }
  12159. get isScriptableOutputNode() {
  12160. return this.outputType !== null;
  12161. }
  12162. set value( val ) {
  12163. if ( this._value === val ) return;
  12164. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  12165. URL.revokeObjectURL( this._cache );
  12166. this._cache = null;
  12167. }
  12168. this._value = val;
  12169. this.events.dispatchEvent( { type: 'change' } );
  12170. this.refresh();
  12171. }
  12172. get value() {
  12173. return this._value;
  12174. }
  12175. refresh() {
  12176. this.events.dispatchEvent( { type: 'refresh' } );
  12177. }
  12178. getValue() {
  12179. const value = this.value;
  12180. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  12181. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  12182. } else if ( value && value.value !== null && value.value !== undefined && (
  12183. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  12184. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  12185. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  12186. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  12187. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  12188. ( this.inputType === 'Color' && value.value.isColor ) ||
  12189. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  12190. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  12191. ) ) {
  12192. return value.value;
  12193. }
  12194. return this._cache || value;
  12195. }
  12196. getNodeType( builder ) {
  12197. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  12198. }
  12199. setup() {
  12200. return this.value && this.value.isNode ? this.value : float();
  12201. }
  12202. serialize( data ) {
  12203. super.serialize( data );
  12204. if ( this.value !== null ) {
  12205. if ( this.inputType === 'ArrayBuffer' ) {
  12206. data.value = arrayBufferToBase64( this.value );
  12207. } else {
  12208. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  12209. }
  12210. } else {
  12211. data.value = null;
  12212. }
  12213. data.inputType = this.inputType;
  12214. data.outputType = this.outputType;
  12215. }
  12216. deserialize( data ) {
  12217. super.deserialize( data );
  12218. let value = null;
  12219. if ( data.value !== null ) {
  12220. if ( data.inputType === 'ArrayBuffer' ) {
  12221. value = base64ToArrayBuffer( data.value );
  12222. } else if ( data.inputType === 'Texture' ) {
  12223. value = data.meta.textures[ data.value ];
  12224. } else {
  12225. value = data.meta.nodes[ data.value ] || null;
  12226. }
  12227. }
  12228. this.value = value;
  12229. this.inputType = data.inputType;
  12230. this.outputType = data.outputType;
  12231. }
  12232. }
  12233. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  12234. class Resources extends Map {
  12235. get( key, callback = null, ...params ) {
  12236. if ( this.has( key ) ) return super.get( key );
  12237. if ( callback !== null ) {
  12238. const value = callback( ...params );
  12239. this.set( key, value );
  12240. return value;
  12241. }
  12242. }
  12243. }
  12244. class Parameters {
  12245. constructor( scriptableNode ) {
  12246. this.scriptableNode = scriptableNode;
  12247. }
  12248. get parameters() {
  12249. return this.scriptableNode.parameters;
  12250. }
  12251. get layout() {
  12252. return this.scriptableNode.getLayout();
  12253. }
  12254. getInputLayout( id ) {
  12255. return this.scriptableNode.getInputLayout( id );
  12256. }
  12257. get( name ) {
  12258. const param = this.parameters[ name ];
  12259. const value = param ? param.getValue() : null;
  12260. return value;
  12261. }
  12262. }
  12263. const ScriptableNodeResources = new Resources();
  12264. class ScriptableNode extends Node {
  12265. static get type() {
  12266. return 'ScriptableNode';
  12267. }
  12268. constructor( codeNode = null, parameters = {} ) {
  12269. super();
  12270. this.codeNode = codeNode;
  12271. this.parameters = parameters;
  12272. this._local = new Resources();
  12273. this._output = scriptableValue();
  12274. this._outputs = {};
  12275. this._source = this.source;
  12276. this._method = null;
  12277. this._object = null;
  12278. this._value = null;
  12279. this._needsOutputUpdate = true;
  12280. this.onRefresh = this.onRefresh.bind( this );
  12281. this.isScriptableNode = true;
  12282. }
  12283. get source() {
  12284. return this.codeNode ? this.codeNode.code : '';
  12285. }
  12286. setLocal( name, value ) {
  12287. return this._local.set( name, value );
  12288. }
  12289. getLocal( name ) {
  12290. return this._local.get( name );
  12291. }
  12292. onRefresh() {
  12293. this._refresh();
  12294. }
  12295. getInputLayout( id ) {
  12296. for ( const element of this.getLayout() ) {
  12297. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  12298. return element;
  12299. }
  12300. }
  12301. }
  12302. getOutputLayout( id ) {
  12303. for ( const element of this.getLayout() ) {
  12304. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  12305. return element;
  12306. }
  12307. }
  12308. }
  12309. setOutput( name, value ) {
  12310. const outputs = this._outputs;
  12311. if ( outputs[ name ] === undefined ) {
  12312. outputs[ name ] = scriptableValue( value );
  12313. } else {
  12314. outputs[ name ].value = value;
  12315. }
  12316. return this;
  12317. }
  12318. getOutput( name ) {
  12319. return this._outputs[ name ];
  12320. }
  12321. getParameter( name ) {
  12322. return this.parameters[ name ];
  12323. }
  12324. setParameter( name, value ) {
  12325. const parameters = this.parameters;
  12326. if ( value && value.isScriptableNode ) {
  12327. this.deleteParameter( name );
  12328. parameters[ name ] = value;
  12329. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  12330. } else if ( value && value.isScriptableValueNode ) {
  12331. this.deleteParameter( name );
  12332. parameters[ name ] = value;
  12333. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  12334. } else if ( parameters[ name ] === undefined ) {
  12335. parameters[ name ] = scriptableValue( value );
  12336. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  12337. } else {
  12338. parameters[ name ].value = value;
  12339. }
  12340. return this;
  12341. }
  12342. getValue() {
  12343. return this.getDefaultOutput().getValue();
  12344. }
  12345. deleteParameter( name ) {
  12346. let valueNode = this.parameters[ name ];
  12347. if ( valueNode ) {
  12348. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  12349. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  12350. }
  12351. return this;
  12352. }
  12353. clearParameters() {
  12354. for ( const name of Object.keys( this.parameters ) ) {
  12355. this.deleteParameter( name );
  12356. }
  12357. this.needsUpdate = true;
  12358. return this;
  12359. }
  12360. call( name, ...params ) {
  12361. const object = this.getObject();
  12362. const method = object[ name ];
  12363. if ( typeof method === 'function' ) {
  12364. return method( ...params );
  12365. }
  12366. }
  12367. async callAsync( name, ...params ) {
  12368. const object = this.getObject();
  12369. const method = object[ name ];
  12370. if ( typeof method === 'function' ) {
  12371. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  12372. }
  12373. }
  12374. getNodeType( builder ) {
  12375. return this.getDefaultOutputNode().getNodeType( builder );
  12376. }
  12377. refresh( output = null ) {
  12378. if ( output !== null ) {
  12379. this.getOutput( output ).refresh();
  12380. } else {
  12381. this._refresh();
  12382. }
  12383. }
  12384. getObject() {
  12385. if ( this.needsUpdate ) this.dispose();
  12386. if ( this._object !== null ) return this._object;
  12387. //
  12388. const refresh = () => this.refresh();
  12389. const setOutput = ( id, value ) => this.setOutput( id, value );
  12390. const parameters = new Parameters( this );
  12391. const THREE = ScriptableNodeResources.get( 'THREE' );
  12392. const TSL = ScriptableNodeResources.get( 'TSL' );
  12393. const method = this.getMethod( this.codeNode );
  12394. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  12395. this._object = method( ...params );
  12396. const layout = this._object.layout;
  12397. if ( layout ) {
  12398. if ( layout.cache === false ) {
  12399. this._local.clear();
  12400. }
  12401. // default output
  12402. this._output.outputType = layout.outputType || null;
  12403. if ( Array.isArray( layout.elements ) ) {
  12404. for ( const element of layout.elements ) {
  12405. const id = element.id || element.name;
  12406. if ( element.inputType ) {
  12407. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  12408. this.getParameter( id ).inputType = element.inputType;
  12409. }
  12410. if ( element.outputType ) {
  12411. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  12412. this.getOutput( id ).outputType = element.outputType;
  12413. }
  12414. }
  12415. }
  12416. }
  12417. return this._object;
  12418. }
  12419. deserialize( data ) {
  12420. super.deserialize( data );
  12421. for ( const name in this.parameters ) {
  12422. let valueNode = this.parameters[ name ];
  12423. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  12424. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  12425. }
  12426. }
  12427. getLayout() {
  12428. return this.getObject().layout;
  12429. }
  12430. getDefaultOutputNode() {
  12431. const output = this.getDefaultOutput().value;
  12432. if ( output && output.isNode ) {
  12433. return output;
  12434. }
  12435. return float();
  12436. }
  12437. getDefaultOutput() {
  12438. return this._exec()._output;
  12439. }
  12440. getMethod() {
  12441. if ( this.needsUpdate ) this.dispose();
  12442. if ( this._method !== null ) return this._method;
  12443. //
  12444. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  12445. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  12446. const properties = interfaceProps.join( ', ' );
  12447. const declarations = 'var ' + properties + '; var output = {};\n';
  12448. const returns = '\nreturn { ...output, ' + properties + ' };';
  12449. const code = declarations + this.codeNode.code + returns;
  12450. //
  12451. this._method = new Function( ...parametersProps, code );
  12452. return this._method;
  12453. }
  12454. dispose() {
  12455. if ( this._method === null ) return;
  12456. if ( this._object && typeof this._object.dispose === 'function' ) {
  12457. this._object.dispose();
  12458. }
  12459. this._method = null;
  12460. this._object = null;
  12461. this._source = null;
  12462. this._value = null;
  12463. this._needsOutputUpdate = true;
  12464. this._output.value = null;
  12465. this._outputs = {};
  12466. }
  12467. setup() {
  12468. return this.getDefaultOutputNode();
  12469. }
  12470. getCacheKey( force ) {
  12471. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  12472. for ( const param in this.parameters ) {
  12473. values.push( this.parameters[ param ].getCacheKey( force ) );
  12474. }
  12475. return hashArray( values );
  12476. }
  12477. set needsUpdate( value ) {
  12478. if ( value === true ) this.dispose();
  12479. }
  12480. get needsUpdate() {
  12481. return this.source !== this._source;
  12482. }
  12483. _exec() {
  12484. if ( this.codeNode === null ) return this;
  12485. if ( this._needsOutputUpdate === true ) {
  12486. this._value = this.call( 'main' );
  12487. this._needsOutputUpdate = false;
  12488. }
  12489. this._output.value = this._value;
  12490. return this;
  12491. }
  12492. _refresh() {
  12493. this.needsUpdate = true;
  12494. this._exec();
  12495. this._output.refresh();
  12496. }
  12497. }
  12498. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  12499. class FogNode extends Node {
  12500. static get type() {
  12501. return 'FogNode';
  12502. }
  12503. constructor( colorNode, factorNode ) {
  12504. super( 'float' );
  12505. this.isFogNode = true;
  12506. this.colorNode = colorNode;
  12507. this.factorNode = factorNode;
  12508. }
  12509. getViewZNode( builder ) {
  12510. let viewZ;
  12511. const getViewZ = builder.context.getViewZ;
  12512. if ( getViewZ !== undefined ) {
  12513. viewZ = getViewZ( this );
  12514. }
  12515. return ( viewZ || positionView.z ).negate();
  12516. }
  12517. setup() {
  12518. return this.factorNode;
  12519. }
  12520. }
  12521. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  12522. class FogRangeNode extends FogNode {
  12523. static get type() {
  12524. return 'FogRangeNode';
  12525. }
  12526. constructor( colorNode, nearNode, farNode ) {
  12527. super( colorNode );
  12528. this.isFogRangeNode = true;
  12529. this.nearNode = nearNode;
  12530. this.farNode = farNode;
  12531. }
  12532. setup( builder ) {
  12533. const viewZ = this.getViewZNode( builder );
  12534. return smoothstep( this.nearNode, this.farNode, viewZ );
  12535. }
  12536. }
  12537. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  12538. class FogExp2Node extends FogNode {
  12539. static get type() {
  12540. return 'FogExp2Node';
  12541. }
  12542. constructor( colorNode, densityNode ) {
  12543. super( colorNode );
  12544. this.isFogExp2Node = true;
  12545. this.densityNode = densityNode;
  12546. }
  12547. setup( builder ) {
  12548. const viewZ = this.getViewZNode( builder );
  12549. const density = this.densityNode;
  12550. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  12551. }
  12552. }
  12553. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  12554. let min = null;
  12555. let max = null;
  12556. class RangeNode extends Node {
  12557. static get type() {
  12558. return 'RangeNode';
  12559. }
  12560. constructor( minNode = float(), maxNode = float() ) {
  12561. super();
  12562. this.minNode = minNode;
  12563. this.maxNode = maxNode;
  12564. }
  12565. getVectorLength( builder ) {
  12566. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  12567. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  12568. return minLength > maxLength ? minLength : maxLength;
  12569. }
  12570. getNodeType( builder ) {
  12571. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  12572. }
  12573. setup( builder ) {
  12574. const object = builder.object;
  12575. let output = null;
  12576. if ( object.count > 1 ) {
  12577. const minValue = this.minNode.value;
  12578. const maxValue = this.maxNode.value;
  12579. const minLength = builder.getTypeLength( getValueType( minValue ) );
  12580. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  12581. min = min || new Vector4();
  12582. max = max || new Vector4();
  12583. min.setScalar( 0 );
  12584. max.setScalar( 0 );
  12585. if ( minLength === 1 ) min.setScalar( minValue );
  12586. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  12587. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  12588. if ( maxLength === 1 ) max.setScalar( maxValue );
  12589. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  12590. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  12591. const stride = 4;
  12592. const length = stride * object.count;
  12593. const array = new Float32Array( length );
  12594. for ( let i = 0; i < length; i ++ ) {
  12595. const index = i % stride;
  12596. const minElementValue = min.getComponent( index );
  12597. const maxElementValue = max.getComponent( index );
  12598. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  12599. }
  12600. const nodeType = this.getNodeType( builder );
  12601. if ( object.count <= 4096 ) {
  12602. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  12603. } else {
  12604. // TODO: Improve anonymous buffer attribute creation removing this part
  12605. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  12606. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  12607. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  12608. }
  12609. } else {
  12610. output = float( 0 );
  12611. }
  12612. return output;
  12613. }
  12614. }
  12615. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  12616. class ComputeBuiltinNode extends Node {
  12617. static get type() {
  12618. return 'ComputeBuiltinNode';
  12619. }
  12620. constructor( builtinName, nodeType ) {
  12621. super( nodeType );
  12622. this._builtinName = builtinName;
  12623. }
  12624. getHash( builder ) {
  12625. return this.getBuiltinName( builder );
  12626. }
  12627. getNodeType( /*builder*/ ) {
  12628. return this.nodeType;
  12629. }
  12630. setBuiltinName( builtinName ) {
  12631. this._builtinName = builtinName;
  12632. return this;
  12633. }
  12634. getBuiltinName( /*builder*/ ) {
  12635. return this._builtinName;
  12636. }
  12637. hasBuiltin( builder ) {
  12638. builder.hasBuiltin( this._builtinName );
  12639. }
  12640. generate( builder, output ) {
  12641. const builtinName = this.getBuiltinName( builder );
  12642. const nodeType = this.getNodeType( builder );
  12643. if ( builder.shaderStage === 'compute' ) {
  12644. return builder.format( builtinName, nodeType, output );
  12645. } else {
  12646. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  12647. return builder.generateConst( nodeType );
  12648. }
  12649. }
  12650. serialize( data ) {
  12651. super.serialize( data );
  12652. data.global = this.global;
  12653. data._builtinName = this._builtinName;
  12654. }
  12655. deserialize( data ) {
  12656. super.deserialize( data );
  12657. this.global = data.global;
  12658. this._builtinName = data._builtinName;
  12659. }
  12660. }
  12661. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  12662. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  12663. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  12664. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  12665. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  12666. class BarrierNode extends Node {
  12667. constructor( scope ) {
  12668. super();
  12669. this.scope = scope;
  12670. }
  12671. generate( builder ) {
  12672. const { scope } = this;
  12673. const { renderer } = builder;
  12674. if ( renderer.backend.isWebGLBackend === true ) {
  12675. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  12676. } else {
  12677. builder.addLineFlowCode( `${scope}Barrier()`, this );
  12678. }
  12679. }
  12680. }
  12681. const barrier = nodeProxy( BarrierNode );
  12682. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  12683. const storageBarrier = () => barrier( 'storage' ).append();
  12684. const textureBarrier = () => barrier( 'texture' ).append();
  12685. class WorkgroupInfoElementNode extends ArrayElementNode {
  12686. constructor( workgroupInfoNode, indexNode ) {
  12687. super( workgroupInfoNode, indexNode );
  12688. this.isWorkgroupInfoElementNode = true;
  12689. }
  12690. generate( builder, output ) {
  12691. let snippet;
  12692. const isAssignContext = builder.context.assign;
  12693. snippet = super.generate( builder );
  12694. if ( isAssignContext !== true ) {
  12695. const type = this.getNodeType( builder );
  12696. snippet = builder.format( snippet, type, output );
  12697. }
  12698. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  12699. return snippet;
  12700. }
  12701. }
  12702. class WorkgroupInfoNode extends Node {
  12703. constructor( scope, bufferType, bufferCount = 0 ) {
  12704. super( bufferType );
  12705. this.bufferType = bufferType;
  12706. this.bufferCount = bufferCount;
  12707. this.isWorkgroupInfoNode = true;
  12708. this.scope = scope;
  12709. }
  12710. label( name ) {
  12711. this.name = name;
  12712. return this;
  12713. }
  12714. getHash() {
  12715. return this.uuid;
  12716. }
  12717. setScope( scope ) {
  12718. this.scope = scope;
  12719. return this;
  12720. }
  12721. getInputType( /*builder*/ ) {
  12722. return `${this.scope}Array`;
  12723. }
  12724. element( indexNode ) {
  12725. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  12726. }
  12727. generate( builder ) {
  12728. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  12729. }
  12730. }
  12731. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  12732. class AtomicFunctionNode extends TempNode {
  12733. static get type() {
  12734. return 'AtomicFunctionNode';
  12735. }
  12736. constructor( method, pointerNode, valueNode, storeNode = null ) {
  12737. super( 'uint' );
  12738. this.method = method;
  12739. this.pointerNode = pointerNode;
  12740. this.valueNode = valueNode;
  12741. this.storeNode = storeNode;
  12742. }
  12743. getInputType( builder ) {
  12744. return this.pointerNode.getNodeType( builder );
  12745. }
  12746. getNodeType( builder ) {
  12747. return this.getInputType( builder );
  12748. }
  12749. generate( builder ) {
  12750. const method = this.method;
  12751. const type = this.getNodeType( builder );
  12752. const inputType = this.getInputType( builder );
  12753. const a = this.pointerNode;
  12754. const b = this.valueNode;
  12755. const params = [];
  12756. params.push( `&${ a.build( builder, inputType ) }` );
  12757. params.push( b.build( builder, inputType ) );
  12758. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  12759. if ( this.storeNode !== null ) {
  12760. const varSnippet = this.storeNode.build( builder, inputType );
  12761. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  12762. } else {
  12763. builder.addLineFlowCode( methodSnippet, this );
  12764. }
  12765. }
  12766. }
  12767. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  12768. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  12769. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  12770. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  12771. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  12772. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  12773. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  12774. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  12775. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  12776. const atomicNode = nodeProxy( AtomicFunctionNode );
  12777. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  12778. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  12779. node.append();
  12780. return node;
  12781. };
  12782. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  12783. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  12784. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  12785. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  12786. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  12787. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  12788. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  12789. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  12790. let uniformsLib;
  12791. function getLightData( light ) {
  12792. uniformsLib = uniformsLib || new WeakMap();
  12793. let uniforms = uniformsLib.get( light );
  12794. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  12795. return uniforms;
  12796. }
  12797. function lightShadowMatrix( light ) {
  12798. const data = getLightData( light );
  12799. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  12800. light.shadow.updateMatrices( light );
  12801. return light.shadow.matrix;
  12802. } ) );
  12803. }
  12804. function lightProjectionUV( light ) {
  12805. const data = getLightData( light );
  12806. if ( data.projectionUV === undefined ) {
  12807. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  12808. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  12809. }
  12810. return data.projectionUV;
  12811. }
  12812. function lightPosition( light ) {
  12813. const data = getLightData( light );
  12814. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  12815. }
  12816. function lightTargetPosition( light ) {
  12817. const data = getLightData( light );
  12818. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  12819. }
  12820. function lightViewPosition( light ) {
  12821. const data = getLightData( light );
  12822. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  12823. self.value = self.value || new Vector3();
  12824. self.value.setFromMatrixPosition( light.matrixWorld );
  12825. self.value.applyMatrix4( camera.matrixWorldInverse );
  12826. } ) );
  12827. }
  12828. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  12829. const sortLights = ( lights ) => {
  12830. return lights.sort( ( a, b ) => a.id - b.id );
  12831. };
  12832. const getLightNodeById = ( id, lightNodes ) => {
  12833. for ( const lightNode of lightNodes ) {
  12834. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  12835. return lightNode;
  12836. }
  12837. }
  12838. return null;
  12839. };
  12840. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  12841. class LightsNode extends Node {
  12842. static get type() {
  12843. return 'LightsNode';
  12844. }
  12845. constructor() {
  12846. super( 'vec3' );
  12847. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  12848. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  12849. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  12850. this._lights = [];
  12851. this._lightNodes = null;
  12852. this._lightNodesHash = null;
  12853. this.global = true;
  12854. }
  12855. getHash( builder ) {
  12856. if ( this._lightNodesHash === null ) {
  12857. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  12858. const hash = [];
  12859. for ( const lightNode of this._lightNodes ) {
  12860. hash.push( lightNode.getSelf().getHash() );
  12861. }
  12862. this._lightNodesHash = 'lights-' + hash.join( ',' );
  12863. }
  12864. return this._lightNodesHash;
  12865. }
  12866. analyze( builder ) {
  12867. const properties = builder.getDataFromNode( this );
  12868. for ( const node of properties.nodes ) {
  12869. node.build( builder );
  12870. }
  12871. }
  12872. setupLightsNode( builder ) {
  12873. const lightNodes = [];
  12874. const previousLightNodes = this._lightNodes;
  12875. const lights = sortLights( this._lights );
  12876. const nodeLibrary = builder.renderer.library;
  12877. for ( const light of lights ) {
  12878. if ( light.isNode ) {
  12879. lightNodes.push( nodeObject( light ) );
  12880. } else {
  12881. let lightNode = null;
  12882. if ( previousLightNodes !== null ) {
  12883. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  12884. }
  12885. if ( lightNode === null ) {
  12886. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  12887. if ( lightNodeClass === null ) {
  12888. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  12889. continue;
  12890. }
  12891. let lightNode = null;
  12892. if ( ! _lightsNodeRef.has( light ) ) {
  12893. lightNode = nodeObject( new lightNodeClass( light ) );
  12894. _lightsNodeRef.set( light, lightNode );
  12895. } else {
  12896. lightNode = _lightsNodeRef.get( light );
  12897. }
  12898. lightNodes.push( lightNode );
  12899. }
  12900. }
  12901. }
  12902. this._lightNodes = lightNodes;
  12903. }
  12904. setupLights( builder, lightNodes ) {
  12905. for ( const lightNode of lightNodes ) {
  12906. lightNode.build( builder );
  12907. }
  12908. }
  12909. setup( builder ) {
  12910. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  12911. const context = builder.context;
  12912. const lightingModel = context.lightingModel;
  12913. let outgoingLightNode = this.outgoingLightNode;
  12914. if ( lightingModel ) {
  12915. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  12916. context.outgoingLight = outgoingLightNode;
  12917. const stack = builder.addStack();
  12918. //
  12919. const properties = builder.getDataFromNode( this );
  12920. properties.nodes = stack.nodes;
  12921. //
  12922. lightingModel.start( context, stack, builder );
  12923. // lights
  12924. this.setupLights( builder, _lightNodes );
  12925. //
  12926. lightingModel.indirect( context, stack, builder );
  12927. //
  12928. const { backdrop, backdropAlpha } = context;
  12929. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  12930. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  12931. if ( backdrop !== null ) {
  12932. if ( backdropAlpha !== null ) {
  12933. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  12934. } else {
  12935. totalDiffuse = vec3( backdrop );
  12936. }
  12937. context.material.transparent = true;
  12938. }
  12939. totalDiffuseNode.assign( totalDiffuse );
  12940. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  12941. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  12942. //
  12943. lightingModel.finish( context, stack, builder );
  12944. //
  12945. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  12946. }
  12947. return outgoingLightNode;
  12948. }
  12949. setLights( lights ) {
  12950. this._lights = lights;
  12951. this._lightNodes = null;
  12952. this._lightNodesHash = null;
  12953. return this;
  12954. }
  12955. getLights() {
  12956. return this._lights;
  12957. }
  12958. get hasLights() {
  12959. return this._lights.length > 0;
  12960. }
  12961. }
  12962. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  12963. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  12964. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  12965. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  12966. let dist = positionWorld.sub( position ).length();
  12967. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  12968. dist = dist.saturate(); // clamp to [ 0, 1 ]
  12969. return dist;
  12970. } );
  12971. const linearShadowDistance = ( light ) => {
  12972. const camera = light.shadow.camera;
  12973. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  12974. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  12975. const referencePosition = objectPosition( light );
  12976. return linearDistance( referencePosition, nearDistance, farDistance );
  12977. };
  12978. const getShadowMaterial = ( light ) => {
  12979. let material = shadowMaterialLib.get( light );
  12980. if ( material === undefined ) {
  12981. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  12982. material = new NodeMaterial();
  12983. material.colorNode = vec4( 0, 0, 0, 1 );
  12984. material.depthNode = depthNode;
  12985. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  12986. material.blending = NoBlending;
  12987. material.name = 'ShadowMaterial';
  12988. shadowMaterialLib.set( light, material );
  12989. }
  12990. return material;
  12991. };
  12992. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  12993. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  12994. } );
  12995. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  12996. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  12997. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12998. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12999. const texelSize = vec2( 1 ).div( mapSize );
  13000. const dx0 = texelSize.x.negate().mul( radius );
  13001. const dy0 = texelSize.y.negate().mul( radius );
  13002. const dx1 = texelSize.x.mul( radius );
  13003. const dy1 = texelSize.y.mul( radius );
  13004. const dx2 = dx0.div( 2 );
  13005. const dy2 = dy0.div( 2 );
  13006. const dx3 = dx1.div( 2 );
  13007. const dy3 = dy1.div( 2 );
  13008. return add(
  13009. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  13010. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  13011. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  13012. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  13013. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  13014. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  13015. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  13016. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  13017. depthCompare( shadowCoord.xy, shadowCoord.z ),
  13018. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  13019. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  13020. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  13021. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  13022. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  13023. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  13024. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  13025. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  13026. ).mul( 1 / 17 );
  13027. } );
  13028. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  13029. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  13030. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  13031. const texelSize = vec2( 1 ).div( mapSize );
  13032. const dx = texelSize.x;
  13033. const dy = texelSize.y;
  13034. const uv = shadowCoord.xy;
  13035. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  13036. uv.subAssign( f.mul( texelSize ) );
  13037. return add(
  13038. depthCompare( uv, shadowCoord.z ),
  13039. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  13040. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  13041. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  13042. mix(
  13043. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  13044. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  13045. f.x
  13046. ),
  13047. mix(
  13048. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  13049. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  13050. f.x
  13051. ),
  13052. mix(
  13053. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  13054. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  13055. f.y
  13056. ),
  13057. mix(
  13058. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  13059. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  13060. f.y
  13061. ),
  13062. mix(
  13063. mix(
  13064. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  13065. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  13066. f.x
  13067. ),
  13068. mix(
  13069. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  13070. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  13071. f.x
  13072. ),
  13073. f.y
  13074. )
  13075. ).mul( 1 / 9 );
  13076. } );
  13077. // VSM
  13078. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  13079. const occlusion = float( 1 ).toVar();
  13080. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  13081. const hardShadow = step( shadowCoord.z, distribution.x );
  13082. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  13083. const distance = shadowCoord.z.sub( distribution.x );
  13084. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  13085. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  13086. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  13087. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  13088. } );
  13089. return occlusion;
  13090. } );
  13091. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  13092. const mean = float( 0 ).toVar();
  13093. const squaredMean = float( 0 ).toVar();
  13094. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  13095. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  13096. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  13097. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  13098. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  13099. mean.addAssign( depth );
  13100. squaredMean.addAssign( depth.mul( depth ) );
  13101. } );
  13102. mean.divAssign( samples );
  13103. squaredMean.divAssign( samples );
  13104. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  13105. return vec2( mean, std_dev );
  13106. } );
  13107. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  13108. const mean = float( 0 ).toVar();
  13109. const squaredMean = float( 0 ).toVar();
  13110. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  13111. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  13112. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  13113. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  13114. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  13115. mean.addAssign( distribution.x );
  13116. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  13117. } );
  13118. mean.divAssign( samples );
  13119. squaredMean.divAssign( samples );
  13120. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  13121. return vec2( mean, std_dev );
  13122. } );
  13123. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  13124. //
  13125. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  13126. class ShadowNode extends Node {
  13127. static get type() {
  13128. return 'ShadowNode';
  13129. }
  13130. constructor( light, shadow = null ) {
  13131. super();
  13132. this.light = light;
  13133. this.shadow = shadow || light.shadow;
  13134. this.shadowMap = null;
  13135. this.vsmShadowMapVertical = null;
  13136. this.vsmShadowMapHorizontal = null;
  13137. this.vsmMaterialVertical = null;
  13138. this.vsmMaterialHorizontal = null;
  13139. this.updateBeforeType = NodeUpdateType.RENDER;
  13140. this._node = null;
  13141. this.isShadowNode = true;
  13142. }
  13143. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  13144. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  13145. .and( shadowCoord.x.lessThanEqual( 1 ) )
  13146. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  13147. .and( shadowCoord.y.lessThanEqual( 1 ) )
  13148. .and( shadowCoord.z.lessThanEqual( 1 ) );
  13149. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  13150. return frustumTest.select( shadowNode, float( 1 ) );
  13151. }
  13152. setupShadowCoord( builder, shadowPosition ) {
  13153. const { shadow } = this;
  13154. const { renderer } = builder;
  13155. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  13156. let shadowCoord = shadowPosition;
  13157. let coordZ;
  13158. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  13159. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  13160. coordZ = shadowCoord.z;
  13161. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  13162. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  13163. }
  13164. } else {
  13165. const w = shadowCoord.w;
  13166. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  13167. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  13168. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  13169. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  13170. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  13171. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  13172. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  13173. }
  13174. shadowCoord = vec3(
  13175. shadowCoord.x,
  13176. shadowCoord.y.oneMinus(), // follow webgpu standards
  13177. coordZ.add( bias )
  13178. );
  13179. return shadowCoord;
  13180. }
  13181. getShadowFilterFn( type ) {
  13182. return _shadowFilterLib[ type ];
  13183. }
  13184. setupShadow( builder ) {
  13185. const { renderer } = builder;
  13186. const { light, shadow } = this;
  13187. const shadowMapType = renderer.shadowMap.type;
  13188. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  13189. depthTexture.compareFunction = LessCompare;
  13190. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  13191. shadowMap.depthTexture = depthTexture;
  13192. shadow.camera.updateProjectionMatrix();
  13193. // VSM
  13194. if ( shadowMapType === VSMShadowMap ) {
  13195. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  13196. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  13197. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  13198. const shadowPassVertical = texture( depthTexture );
  13199. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  13200. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  13201. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  13202. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  13203. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  13204. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  13205. material.name = 'VSMVertical';
  13206. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  13207. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  13208. material.name = 'VSMHorizontal';
  13209. }
  13210. //
  13211. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  13212. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  13213. const shadowPosition = lightShadowMatrix( light ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  13214. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  13215. //
  13216. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  13217. if ( filterFn === null ) {
  13218. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  13219. }
  13220. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  13221. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  13222. const shadowColor = texture( shadowMap.texture, shadowCoord );
  13223. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  13224. this.shadowMap = shadowMap;
  13225. this.shadow.map = shadowMap;
  13226. return shadowOutput;
  13227. }
  13228. setup( builder ) {
  13229. if ( builder.renderer.shadowMap.enabled === false ) return;
  13230. return Fn( ( { material } ) => {
  13231. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  13232. let node = this._node;
  13233. if ( node === null ) {
  13234. this._node = node = this.setupShadow( builder );
  13235. }
  13236. if ( builder.material.shadowNode ) { // @deprecated, r171
  13237. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  13238. }
  13239. if ( builder.material.receivedShadowNode ) {
  13240. node = builder.material.receivedShadowNode( node );
  13241. }
  13242. return node;
  13243. } )();
  13244. }
  13245. renderShadow( frame ) {
  13246. const { shadow, shadowMap } = this;
  13247. const { renderer, scene } = frame;
  13248. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  13249. renderer.render( scene, shadow.camera );
  13250. }
  13251. updateShadow( frame ) {
  13252. const { shadowMap, light, shadow } = this;
  13253. const { renderer, scene, camera } = frame;
  13254. const shadowType = renderer.shadowMap.type;
  13255. const depthVersion = shadowMap.depthTexture.version;
  13256. this._depthVersionCached = depthVersion;
  13257. const currentOverrideMaterial = scene.overrideMaterial;
  13258. scene.overrideMaterial = getShadowMaterial( light );
  13259. shadow.camera.layers.mask = camera.layers.mask;
  13260. const currentRenderTarget = renderer.getRenderTarget();
  13261. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  13262. const currentMRT = renderer.getMRT();
  13263. renderer.setMRT( null );
  13264. renderer.setRenderObjectFunction( ( object, ...params ) => {
  13265. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  13266. renderer.renderObject( object, ...params );
  13267. }
  13268. } );
  13269. renderer.setRenderTarget( shadowMap );
  13270. this.renderShadow( frame );
  13271. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  13272. // vsm blur pass
  13273. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  13274. this.vsmPass( renderer );
  13275. }
  13276. renderer.setRenderTarget( currentRenderTarget );
  13277. renderer.setMRT( currentMRT );
  13278. scene.overrideMaterial = currentOverrideMaterial;
  13279. }
  13280. vsmPass( renderer ) {
  13281. const { shadow } = this;
  13282. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  13283. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  13284. renderer.setRenderTarget( this.vsmShadowMapVertical );
  13285. _quadMesh$1.material = this.vsmMaterialVertical;
  13286. _quadMesh$1.render( renderer );
  13287. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  13288. _quadMesh$1.material = this.vsmMaterialHorizontal;
  13289. _quadMesh$1.render( renderer );
  13290. }
  13291. dispose() {
  13292. this.shadowMap.dispose();
  13293. this.shadowMap = null;
  13294. if ( this.vsmShadowMapVertical !== null ) {
  13295. this.vsmShadowMapVertical.dispose();
  13296. this.vsmShadowMapVertical = null;
  13297. this.vsmMaterialVertical.dispose();
  13298. this.vsmMaterialVertical = null;
  13299. }
  13300. if ( this.vsmShadowMapHorizontal !== null ) {
  13301. this.vsmShadowMapHorizontal.dispose();
  13302. this.vsmShadowMapHorizontal = null;
  13303. this.vsmMaterialHorizontal.dispose();
  13304. this.vsmMaterialHorizontal = null;
  13305. }
  13306. this.updateBeforeType = NodeUpdateType.NONE;
  13307. }
  13308. updateBefore( frame ) {
  13309. const { shadow } = this;
  13310. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  13311. if ( needsUpdate ) {
  13312. this.updateShadow( frame );
  13313. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  13314. shadow.needsUpdate = false;
  13315. }
  13316. }
  13317. }
  13318. }
  13319. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  13320. class AnalyticLightNode extends LightingNode {
  13321. static get type() {
  13322. return 'AnalyticLightNode';
  13323. }
  13324. constructor( light = null ) {
  13325. super();
  13326. this.light = light;
  13327. this.color = new Color();
  13328. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  13329. this.baseColorNode = null;
  13330. this.shadowNode = null;
  13331. this.shadowColorNode = null;
  13332. this.isAnalyticLightNode = true;
  13333. this.updateType = NodeUpdateType.FRAME;
  13334. }
  13335. getCacheKey() {
  13336. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  13337. }
  13338. getHash() {
  13339. return this.light.uuid;
  13340. }
  13341. setupShadowNode() {
  13342. return shadow( this.light );
  13343. }
  13344. setupShadow( builder ) {
  13345. const { renderer } = builder;
  13346. if ( renderer.shadowMap.enabled === false ) return;
  13347. let shadowColorNode = this.shadowColorNode;
  13348. if ( shadowColorNode === null ) {
  13349. const customShadowNode = this.light.shadow.shadowNode;
  13350. let shadowNode;
  13351. if ( customShadowNode !== undefined ) {
  13352. shadowNode = nodeObject( customShadowNode );
  13353. } else {
  13354. shadowNode = this.setupShadowNode( builder );
  13355. }
  13356. this.shadowNode = shadowNode;
  13357. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  13358. this.baseColorNode = this.colorNode;
  13359. }
  13360. //
  13361. this.colorNode = shadowColorNode;
  13362. }
  13363. setup( builder ) {
  13364. this.colorNode = this.baseColorNode || this.colorNode;
  13365. if ( this.light.castShadow ) {
  13366. if ( builder.object.receiveShadow ) {
  13367. this.setupShadow( builder );
  13368. }
  13369. } else if ( this.shadowNode !== null ) {
  13370. this.shadowNode.dispose();
  13371. this.shadowNode = null;
  13372. this.shadowColorNode = null;
  13373. }
  13374. }
  13375. update( /*frame*/ ) {
  13376. const { light } = this;
  13377. this.color.copy( light.color ).multiplyScalar( light.intensity );
  13378. }
  13379. }
  13380. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  13381. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  13382. // based upon Frostbite 3 Moving to Physically-based Rendering
  13383. // page 32, equation 26: E[window1]
  13384. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13385. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  13386. return cutoffDistance.greaterThan( 0 ).select(
  13387. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  13388. distanceFalloff
  13389. );
  13390. } ); // validated
  13391. const _clearColor$2 = /*@__PURE__*/ new Color();
  13392. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  13393. // vector suitable for 2D texture mapping. This code uses the following layout for the
  13394. // 2D texture:
  13395. //
  13396. // xzXZ
  13397. // y Y
  13398. //
  13399. // Y - Positive y direction
  13400. // y - Negative y direction
  13401. // X - Positive x direction
  13402. // x - Negative x direction
  13403. // Z - Positive z direction
  13404. // z - Negative z direction
  13405. //
  13406. // Source and test bed:
  13407. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  13408. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  13409. const v = pos.toVar();
  13410. // Number of texels to avoid at the edge of each square
  13411. const absV = abs( v );
  13412. // Intersect unit cube
  13413. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  13414. absV.mulAssign( scaleToCube );
  13415. // Apply scale to avoid seams
  13416. // two texels less per square (one texel will do for NEAREST)
  13417. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  13418. // Unwrap
  13419. // space: -1 ... 1 range for each square
  13420. //
  13421. // #X## dim := ( 4 , 2 )
  13422. // # # center := ( 1 , 1 )
  13423. const planar = vec2( v.xy ).toVar();
  13424. const almostATexel = texelSizeY.mul( 1.5 );
  13425. const almostOne = almostATexel.oneMinus();
  13426. If( absV.z.greaterThanEqual( almostOne ), () => {
  13427. If( v.z.greaterThan( 0.0 ), () => {
  13428. planar.x.assign( sub( 4.0, v.x ) );
  13429. } );
  13430. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  13431. const signX = sign( v.x );
  13432. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  13433. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  13434. const signY = sign( v.y );
  13435. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  13436. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  13437. } );
  13438. // Transform to UV space
  13439. // scale := 0.5 / dim
  13440. // translate := ( center + 0.5 ) / dim
  13441. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  13442. } ).setLayout( {
  13443. name: 'cubeToUV',
  13444. type: 'vec2',
  13445. inputs: [
  13446. { name: 'pos', type: 'vec3' },
  13447. { name: 'texelSizeY', type: 'float' }
  13448. ]
  13449. } );
  13450. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  13451. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  13452. } );
  13453. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  13454. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  13455. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  13456. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  13457. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  13458. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  13459. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  13460. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  13461. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  13462. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  13463. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  13464. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  13465. .mul( 1.0 / 9.0 );
  13466. } );
  13467. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  13468. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  13469. // the vector from the light to the world-space position of the fragment.
  13470. const lightToPosition = shadowCoord.xyz.toVar();
  13471. const lightToPositionLength = lightToPosition.length();
  13472. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  13473. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  13474. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  13475. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  13476. const result = float( 1.0 ).toVar();
  13477. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  13478. // dp = normalized distance from light to fragment position
  13479. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  13480. dp.addAssign( bias );
  13481. // bd3D = base direction 3D
  13482. const bd3D = lightToPosition.normalize();
  13483. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  13484. // percentage-closer filtering
  13485. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  13486. } );
  13487. return result;
  13488. } );
  13489. const _viewport = /*@__PURE__*/ new Vector4();
  13490. const _viewportSize = /*@__PURE__*/ new Vector2();
  13491. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  13492. //
  13493. class PointShadowNode extends ShadowNode {
  13494. static get type() {
  13495. return 'PointShadowNode';
  13496. }
  13497. constructor( light, shadow = null ) {
  13498. super( light, shadow );
  13499. }
  13500. getShadowFilterFn( type ) {
  13501. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  13502. }
  13503. setupShadowCoord( builder, shadowPosition ) {
  13504. return shadowPosition;
  13505. }
  13506. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  13507. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  13508. }
  13509. renderShadow( frame ) {
  13510. const { shadow, shadowMap, light } = this;
  13511. const { renderer, scene } = frame;
  13512. const shadowFrameExtents = shadow.getFrameExtents();
  13513. _shadowMapSize.copy( shadow.mapSize );
  13514. _shadowMapSize.multiply( shadowFrameExtents );
  13515. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  13516. _viewportSize.copy( shadow.mapSize );
  13517. //
  13518. const previousAutoClear = renderer.autoClear;
  13519. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  13520. const previousClearAlpha = renderer.getClearAlpha();
  13521. renderer.autoClear = false;
  13522. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  13523. renderer.clear();
  13524. const viewportCount = shadow.getViewportCount();
  13525. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13526. const viewport = shadow.getViewport( vp );
  13527. const x = _viewportSize.x * viewport.x;
  13528. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  13529. _viewport.set(
  13530. x,
  13531. y,
  13532. _viewportSize.x * viewport.z,
  13533. _viewportSize.y * viewport.w
  13534. );
  13535. shadowMap.viewport.copy( _viewport );
  13536. shadow.updateMatrices( light, vp );
  13537. renderer.render( scene, shadow.camera );
  13538. }
  13539. //
  13540. renderer.autoClear = previousAutoClear;
  13541. renderer.setClearColor( previousClearColor, previousClearAlpha );
  13542. }
  13543. }
  13544. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  13545. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  13546. const lightingModel = builder.context.lightingModel;
  13547. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  13548. const lightDirection = lVector.normalize();
  13549. const lightDistance = lVector.length();
  13550. const lightAttenuation = getDistanceAttenuation( {
  13551. lightDistance,
  13552. cutoffDistance,
  13553. decayExponent
  13554. } );
  13555. const lightColor = color.mul( lightAttenuation );
  13556. const reflectedLight = builder.context.reflectedLight;
  13557. lightingModel.direct( {
  13558. lightDirection,
  13559. lightColor,
  13560. reflectedLight
  13561. }, builder.stack, builder );
  13562. } );
  13563. class PointLightNode extends AnalyticLightNode {
  13564. static get type() {
  13565. return 'PointLightNode';
  13566. }
  13567. constructor( light = null ) {
  13568. super( light );
  13569. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  13570. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  13571. }
  13572. update( frame ) {
  13573. const { light } = this;
  13574. super.update( frame );
  13575. this.cutoffDistanceNode.value = light.distance;
  13576. this.decayExponentNode.value = light.decay;
  13577. }
  13578. setupShadowNode() {
  13579. return pointShadow( this.light );
  13580. }
  13581. setup( builder ) {
  13582. super.setup( builder );
  13583. directPointLight( {
  13584. color: this.colorNode,
  13585. lightViewPosition: lightViewPosition( this.light ),
  13586. cutoffDistance: this.cutoffDistanceNode,
  13587. decayExponent: this.decayExponentNode
  13588. } ).append();
  13589. }
  13590. }
  13591. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  13592. const uv = coord.mul( 2.0 );
  13593. const cx = uv.x.floor();
  13594. const cy = uv.y.floor();
  13595. const result = cx.add( cy ).mod( 2.0 );
  13596. return result.sign();
  13597. } );
  13598. // Three.js Transpiler
  13599. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  13600. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  13601. const f = float( f_immutable ).toVar();
  13602. const t = float( t_immutable ).toVar();
  13603. const b = bool( b_immutable ).toVar();
  13604. return select( b, t, f );
  13605. } ).setLayout( {
  13606. name: 'mx_select',
  13607. type: 'float',
  13608. inputs: [
  13609. { name: 'b', type: 'bool' },
  13610. { name: 't', type: 'float' },
  13611. { name: 'f', type: 'float' }
  13612. ]
  13613. } );
  13614. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  13615. const b = bool( b_immutable ).toVar();
  13616. const val = float( val_immutable ).toVar();
  13617. return select( b, val.negate(), val );
  13618. } ).setLayout( {
  13619. name: 'mx_negate_if',
  13620. type: 'float',
  13621. inputs: [
  13622. { name: 'val', type: 'float' },
  13623. { name: 'b', type: 'bool' }
  13624. ]
  13625. } );
  13626. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  13627. const x = float( x_immutable ).toVar();
  13628. return int( floor( x ) );
  13629. } ).setLayout( {
  13630. name: 'mx_floor',
  13631. type: 'int',
  13632. inputs: [
  13633. { name: 'x', type: 'float' }
  13634. ]
  13635. } );
  13636. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  13637. const x = float( x_immutable ).toVar();
  13638. i.assign( mx_floor( x ) );
  13639. return x.sub( float( i ) );
  13640. } );
  13641. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  13642. const t = float( t_immutable ).toVar();
  13643. const s = float( s_immutable ).toVar();
  13644. const v3 = float( v3_immutable ).toVar();
  13645. const v2 = float( v2_immutable ).toVar();
  13646. const v1 = float( v1_immutable ).toVar();
  13647. const v0 = float( v0_immutable ).toVar();
  13648. const s1 = float( sub( 1.0, s ) ).toVar();
  13649. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  13650. } ).setLayout( {
  13651. name: 'mx_bilerp_0',
  13652. type: 'float',
  13653. inputs: [
  13654. { name: 'v0', type: 'float' },
  13655. { name: 'v1', type: 'float' },
  13656. { name: 'v2', type: 'float' },
  13657. { name: 'v3', type: 'float' },
  13658. { name: 's', type: 'float' },
  13659. { name: 't', type: 'float' }
  13660. ]
  13661. } );
  13662. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  13663. const t = float( t_immutable ).toVar();
  13664. const s = float( s_immutable ).toVar();
  13665. const v3 = vec3( v3_immutable ).toVar();
  13666. const v2 = vec3( v2_immutable ).toVar();
  13667. const v1 = vec3( v1_immutable ).toVar();
  13668. const v0 = vec3( v0_immutable ).toVar();
  13669. const s1 = float( sub( 1.0, s ) ).toVar();
  13670. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  13671. } ).setLayout( {
  13672. name: 'mx_bilerp_1',
  13673. type: 'vec3',
  13674. inputs: [
  13675. { name: 'v0', type: 'vec3' },
  13676. { name: 'v1', type: 'vec3' },
  13677. { name: 'v2', type: 'vec3' },
  13678. { name: 'v3', type: 'vec3' },
  13679. { name: 's', type: 'float' },
  13680. { name: 't', type: 'float' }
  13681. ]
  13682. } );
  13683. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  13684. const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  13685. const r = float( r_immutable ).toVar();
  13686. const t = float( t_immutable ).toVar();
  13687. const s = float( s_immutable ).toVar();
  13688. const v7 = float( v7_immutable ).toVar();
  13689. const v6 = float( v6_immutable ).toVar();
  13690. const v5 = float( v5_immutable ).toVar();
  13691. const v4 = float( v4_immutable ).toVar();
  13692. const v3 = float( v3_immutable ).toVar();
  13693. const v2 = float( v2_immutable ).toVar();
  13694. const v1 = float( v1_immutable ).toVar();
  13695. const v0 = float( v0_immutable ).toVar();
  13696. const s1 = float( sub( 1.0, s ) ).toVar();
  13697. const t1 = float( sub( 1.0, t ) ).toVar();
  13698. const r1 = float( sub( 1.0, r ) ).toVar();
  13699. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  13700. } ).setLayout( {
  13701. name: 'mx_trilerp_0',
  13702. type: 'float',
  13703. inputs: [
  13704. { name: 'v0', type: 'float' },
  13705. { name: 'v1', type: 'float' },
  13706. { name: 'v2', type: 'float' },
  13707. { name: 'v3', type: 'float' },
  13708. { name: 'v4', type: 'float' },
  13709. { name: 'v5', type: 'float' },
  13710. { name: 'v6', type: 'float' },
  13711. { name: 'v7', type: 'float' },
  13712. { name: 's', type: 'float' },
  13713. { name: 't', type: 'float' },
  13714. { name: 'r', type: 'float' }
  13715. ]
  13716. } );
  13717. const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  13718. const r = float( r_immutable ).toVar();
  13719. const t = float( t_immutable ).toVar();
  13720. const s = float( s_immutable ).toVar();
  13721. const v7 = vec3( v7_immutable ).toVar();
  13722. const v6 = vec3( v6_immutable ).toVar();
  13723. const v5 = vec3( v5_immutable ).toVar();
  13724. const v4 = vec3( v4_immutable ).toVar();
  13725. const v3 = vec3( v3_immutable ).toVar();
  13726. const v2 = vec3( v2_immutable ).toVar();
  13727. const v1 = vec3( v1_immutable ).toVar();
  13728. const v0 = vec3( v0_immutable ).toVar();
  13729. const s1 = float( sub( 1.0, s ) ).toVar();
  13730. const t1 = float( sub( 1.0, t ) ).toVar();
  13731. const r1 = float( sub( 1.0, r ) ).toVar();
  13732. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  13733. } ).setLayout( {
  13734. name: 'mx_trilerp_1',
  13735. type: 'vec3',
  13736. inputs: [
  13737. { name: 'v0', type: 'vec3' },
  13738. { name: 'v1', type: 'vec3' },
  13739. { name: 'v2', type: 'vec3' },
  13740. { name: 'v3', type: 'vec3' },
  13741. { name: 'v4', type: 'vec3' },
  13742. { name: 'v5', type: 'vec3' },
  13743. { name: 'v6', type: 'vec3' },
  13744. { name: 'v7', type: 'vec3' },
  13745. { name: 's', type: 'float' },
  13746. { name: 't', type: 'float' },
  13747. { name: 'r', type: 'float' }
  13748. ]
  13749. } );
  13750. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  13751. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  13752. const y = float( y_immutable ).toVar();
  13753. const x = float( x_immutable ).toVar();
  13754. const hash = uint( hash_immutable ).toVar();
  13755. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  13756. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  13757. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  13758. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  13759. } ).setLayout( {
  13760. name: 'mx_gradient_float_0',
  13761. type: 'float',
  13762. inputs: [
  13763. { name: 'hash', type: 'uint' },
  13764. { name: 'x', type: 'float' },
  13765. { name: 'y', type: 'float' }
  13766. ]
  13767. } );
  13768. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  13769. const z = float( z_immutable ).toVar();
  13770. const y = float( y_immutable ).toVar();
  13771. const x = float( x_immutable ).toVar();
  13772. const hash = uint( hash_immutable ).toVar();
  13773. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  13774. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  13775. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  13776. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  13777. } ).setLayout( {
  13778. name: 'mx_gradient_float_1',
  13779. type: 'float',
  13780. inputs: [
  13781. { name: 'hash', type: 'uint' },
  13782. { name: 'x', type: 'float' },
  13783. { name: 'y', type: 'float' },
  13784. { name: 'z', type: 'float' }
  13785. ]
  13786. } );
  13787. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  13788. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  13789. const y = float( y_immutable ).toVar();
  13790. const x = float( x_immutable ).toVar();
  13791. const hash = uvec3( hash_immutable ).toVar();
  13792. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  13793. } ).setLayout( {
  13794. name: 'mx_gradient_vec3_0',
  13795. type: 'vec3',
  13796. inputs: [
  13797. { name: 'hash', type: 'uvec3' },
  13798. { name: 'x', type: 'float' },
  13799. { name: 'y', type: 'float' }
  13800. ]
  13801. } );
  13802. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  13803. const z = float( z_immutable ).toVar();
  13804. const y = float( y_immutable ).toVar();
  13805. const x = float( x_immutable ).toVar();
  13806. const hash = uvec3( hash_immutable ).toVar();
  13807. return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) );
  13808. } ).setLayout( {
  13809. name: 'mx_gradient_vec3_1',
  13810. type: 'vec3',
  13811. inputs: [
  13812. { name: 'hash', type: 'uvec3' },
  13813. { name: 'x', type: 'float' },
  13814. { name: 'y', type: 'float' },
  13815. { name: 'z', type: 'float' }
  13816. ]
  13817. } );
  13818. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  13819. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  13820. const v = float( v_immutable ).toVar();
  13821. return mul( 0.6616, v );
  13822. } ).setLayout( {
  13823. name: 'mx_gradient_scale2d_0',
  13824. type: 'float',
  13825. inputs: [
  13826. { name: 'v', type: 'float' }
  13827. ]
  13828. } );
  13829. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  13830. const v = float( v_immutable ).toVar();
  13831. return mul( 0.9820, v );
  13832. } ).setLayout( {
  13833. name: 'mx_gradient_scale3d_0',
  13834. type: 'float',
  13835. inputs: [
  13836. { name: 'v', type: 'float' }
  13837. ]
  13838. } );
  13839. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  13840. const v = vec3( v_immutable ).toVar();
  13841. return mul( 0.6616, v );
  13842. } ).setLayout( {
  13843. name: 'mx_gradient_scale2d_1',
  13844. type: 'vec3',
  13845. inputs: [
  13846. { name: 'v', type: 'vec3' }
  13847. ]
  13848. } );
  13849. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  13850. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  13851. const v = vec3( v_immutable ).toVar();
  13852. return mul( 0.9820, v );
  13853. } ).setLayout( {
  13854. name: 'mx_gradient_scale3d_1',
  13855. type: 'vec3',
  13856. inputs: [
  13857. { name: 'v', type: 'vec3' }
  13858. ]
  13859. } );
  13860. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  13861. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  13862. const k = int( k_immutable ).toVar();
  13863. const x = uint( x_immutable ).toVar();
  13864. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  13865. } ).setLayout( {
  13866. name: 'mx_rotl32',
  13867. type: 'uint',
  13868. inputs: [
  13869. { name: 'x', type: 'uint' },
  13870. { name: 'k', type: 'int' }
  13871. ]
  13872. } );
  13873. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  13874. a.subAssign( c );
  13875. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  13876. c.addAssign( b );
  13877. b.subAssign( a );
  13878. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  13879. a.addAssign( c );
  13880. c.subAssign( b );
  13881. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  13882. b.addAssign( a );
  13883. a.subAssign( c );
  13884. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  13885. c.addAssign( b );
  13886. b.subAssign( a );
  13887. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  13888. a.addAssign( c );
  13889. c.subAssign( b );
  13890. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  13891. b.addAssign( a );
  13892. } );
  13893. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  13894. const c = uint( c_immutable ).toVar();
  13895. const b = uint( b_immutable ).toVar();
  13896. const a = uint( a_immutable ).toVar();
  13897. c.bitXorAssign( b );
  13898. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  13899. a.bitXorAssign( c );
  13900. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  13901. b.bitXorAssign( a );
  13902. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  13903. c.bitXorAssign( b );
  13904. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  13905. a.bitXorAssign( c );
  13906. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  13907. b.bitXorAssign( a );
  13908. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  13909. c.bitXorAssign( b );
  13910. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  13911. return c;
  13912. } ).setLayout( {
  13913. name: 'mx_bjfinal',
  13914. type: 'uint',
  13915. inputs: [
  13916. { name: 'a', type: 'uint' },
  13917. { name: 'b', type: 'uint' },
  13918. { name: 'c', type: 'uint' }
  13919. ]
  13920. } );
  13921. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  13922. const bits = uint( bits_immutable ).toVar();
  13923. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  13924. } ).setLayout( {
  13925. name: 'mx_bits_to_01',
  13926. type: 'float',
  13927. inputs: [
  13928. { name: 'bits', type: 'uint' }
  13929. ]
  13930. } );
  13931. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  13932. const t = float( t_immutable ).toVar();
  13933. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  13934. } ).setLayout( {
  13935. name: 'mx_fade',
  13936. type: 'float',
  13937. inputs: [
  13938. { name: 't', type: 'float' }
  13939. ]
  13940. } );
  13941. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  13942. const x = int( x_immutable ).toVar();
  13943. const len = uint( uint( 1 ) ).toVar();
  13944. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  13945. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  13946. } ).setLayout( {
  13947. name: 'mx_hash_int_0',
  13948. type: 'uint',
  13949. inputs: [
  13950. { name: 'x', type: 'int' }
  13951. ]
  13952. } );
  13953. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  13954. const y = int( y_immutable ).toVar();
  13955. const x = int( x_immutable ).toVar();
  13956. const len = uint( uint( 2 ) ).toVar();
  13957. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  13958. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  13959. a.addAssign( uint( x ) );
  13960. b.addAssign( uint( y ) );
  13961. return mx_bjfinal( a, b, c );
  13962. } ).setLayout( {
  13963. name: 'mx_hash_int_1',
  13964. type: 'uint',
  13965. inputs: [
  13966. { name: 'x', type: 'int' },
  13967. { name: 'y', type: 'int' }
  13968. ]
  13969. } );
  13970. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  13971. const z = int( z_immutable ).toVar();
  13972. const y = int( y_immutable ).toVar();
  13973. const x = int( x_immutable ).toVar();
  13974. const len = uint( uint( 3 ) ).toVar();
  13975. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  13976. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  13977. a.addAssign( uint( x ) );
  13978. b.addAssign( uint( y ) );
  13979. c.addAssign( uint( z ) );
  13980. return mx_bjfinal( a, b, c );
  13981. } ).setLayout( {
  13982. name: 'mx_hash_int_2',
  13983. type: 'uint',
  13984. inputs: [
  13985. { name: 'x', type: 'int' },
  13986. { name: 'y', type: 'int' },
  13987. { name: 'z', type: 'int' }
  13988. ]
  13989. } );
  13990. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  13991. const xx = int( xx_immutable ).toVar();
  13992. const z = int( z_immutable ).toVar();
  13993. const y = int( y_immutable ).toVar();
  13994. const x = int( x_immutable ).toVar();
  13995. const len = uint( uint( 4 ) ).toVar();
  13996. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  13997. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  13998. a.addAssign( uint( x ) );
  13999. b.addAssign( uint( y ) );
  14000. c.addAssign( uint( z ) );
  14001. mx_bjmix( a, b, c );
  14002. a.addAssign( uint( xx ) );
  14003. return mx_bjfinal( a, b, c );
  14004. } ).setLayout( {
  14005. name: 'mx_hash_int_3',
  14006. type: 'uint',
  14007. inputs: [
  14008. { name: 'x', type: 'int' },
  14009. { name: 'y', type: 'int' },
  14010. { name: 'z', type: 'int' },
  14011. { name: 'xx', type: 'int' }
  14012. ]
  14013. } );
  14014. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  14015. const yy = int( yy_immutable ).toVar();
  14016. const xx = int( xx_immutable ).toVar();
  14017. const z = int( z_immutable ).toVar();
  14018. const y = int( y_immutable ).toVar();
  14019. const x = int( x_immutable ).toVar();
  14020. const len = uint( uint( 5 ) ).toVar();
  14021. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  14022. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  14023. a.addAssign( uint( x ) );
  14024. b.addAssign( uint( y ) );
  14025. c.addAssign( uint( z ) );
  14026. mx_bjmix( a, b, c );
  14027. a.addAssign( uint( xx ) );
  14028. b.addAssign( uint( yy ) );
  14029. return mx_bjfinal( a, b, c );
  14030. } ).setLayout( {
  14031. name: 'mx_hash_int_4',
  14032. type: 'uint',
  14033. inputs: [
  14034. { name: 'x', type: 'int' },
  14035. { name: 'y', type: 'int' },
  14036. { name: 'z', type: 'int' },
  14037. { name: 'xx', type: 'int' },
  14038. { name: 'yy', type: 'int' }
  14039. ]
  14040. } );
  14041. const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] );
  14042. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  14043. const y = int( y_immutable ).toVar();
  14044. const x = int( x_immutable ).toVar();
  14045. const h = uint( mx_hash_int( x, y ) ).toVar();
  14046. const result = uvec3().toVar();
  14047. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  14048. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  14049. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  14050. return result;
  14051. } ).setLayout( {
  14052. name: 'mx_hash_vec3_0',
  14053. type: 'uvec3',
  14054. inputs: [
  14055. { name: 'x', type: 'int' },
  14056. { name: 'y', type: 'int' }
  14057. ]
  14058. } );
  14059. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  14060. const z = int( z_immutable ).toVar();
  14061. const y = int( y_immutable ).toVar();
  14062. const x = int( x_immutable ).toVar();
  14063. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  14064. const result = uvec3().toVar();
  14065. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  14066. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  14067. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  14068. return result;
  14069. } ).setLayout( {
  14070. name: 'mx_hash_vec3_1',
  14071. type: 'uvec3',
  14072. inputs: [
  14073. { name: 'x', type: 'int' },
  14074. { name: 'y', type: 'int' },
  14075. { name: 'z', type: 'int' }
  14076. ]
  14077. } );
  14078. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  14079. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14080. const p = vec2( p_immutable ).toVar();
  14081. const X = int().toVar(), Y = int().toVar();
  14082. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  14083. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  14084. const u = float( mx_fade( fx ) ).toVar();
  14085. const v = float( mx_fade( fy ) ).toVar();
  14086. const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  14087. return mx_gradient_scale2d( result );
  14088. } ).setLayout( {
  14089. name: 'mx_perlin_noise_float_0',
  14090. type: 'float',
  14091. inputs: [
  14092. { name: 'p', type: 'vec2' }
  14093. ]
  14094. } );
  14095. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14096. const p = vec3( p_immutable ).toVar();
  14097. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14098. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  14099. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  14100. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  14101. const u = float( mx_fade( fx ) ).toVar();
  14102. const v = float( mx_fade( fy ) ).toVar();
  14103. const w = float( mx_fade( fz ) ).toVar();
  14104. const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  14105. return mx_gradient_scale3d( result );
  14106. } ).setLayout( {
  14107. name: 'mx_perlin_noise_float_1',
  14108. type: 'float',
  14109. inputs: [
  14110. { name: 'p', type: 'vec3' }
  14111. ]
  14112. } );
  14113. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  14114. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14115. const p = vec2( p_immutable ).toVar();
  14116. const X = int().toVar(), Y = int().toVar();
  14117. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  14118. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  14119. const u = float( mx_fade( fx ) ).toVar();
  14120. const v = float( mx_fade( fy ) ).toVar();
  14121. const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  14122. return mx_gradient_scale2d( result );
  14123. } ).setLayout( {
  14124. name: 'mx_perlin_noise_vec3_0',
  14125. type: 'vec3',
  14126. inputs: [
  14127. { name: 'p', type: 'vec2' }
  14128. ]
  14129. } );
  14130. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14131. const p = vec3( p_immutable ).toVar();
  14132. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14133. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  14134. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  14135. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  14136. const u = float( mx_fade( fx ) ).toVar();
  14137. const v = float( mx_fade( fy ) ).toVar();
  14138. const w = float( mx_fade( fz ) ).toVar();
  14139. const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  14140. return mx_gradient_scale3d( result );
  14141. } ).setLayout( {
  14142. name: 'mx_perlin_noise_vec3_1',
  14143. type: 'vec3',
  14144. inputs: [
  14145. { name: 'p', type: 'vec3' }
  14146. ]
  14147. } );
  14148. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  14149. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14150. const p = float( p_immutable ).toVar();
  14151. const ix = int( mx_floor( p ) ).toVar();
  14152. return mx_bits_to_01( mx_hash_int( ix ) );
  14153. } ).setLayout( {
  14154. name: 'mx_cell_noise_float_0',
  14155. type: 'float',
  14156. inputs: [
  14157. { name: 'p', type: 'float' }
  14158. ]
  14159. } );
  14160. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14161. const p = vec2( p_immutable ).toVar();
  14162. const ix = int( mx_floor( p.x ) ).toVar();
  14163. const iy = int( mx_floor( p.y ) ).toVar();
  14164. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  14165. } ).setLayout( {
  14166. name: 'mx_cell_noise_float_1',
  14167. type: 'float',
  14168. inputs: [
  14169. { name: 'p', type: 'vec2' }
  14170. ]
  14171. } );
  14172. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14173. const p = vec3( p_immutable ).toVar();
  14174. const ix = int( mx_floor( p.x ) ).toVar();
  14175. const iy = int( mx_floor( p.y ) ).toVar();
  14176. const iz = int( mx_floor( p.z ) ).toVar();
  14177. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  14178. } ).setLayout( {
  14179. name: 'mx_cell_noise_float_2',
  14180. type: 'float',
  14181. inputs: [
  14182. { name: 'p', type: 'vec3' }
  14183. ]
  14184. } );
  14185. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14186. const p = vec4( p_immutable ).toVar();
  14187. const ix = int( mx_floor( p.x ) ).toVar();
  14188. const iy = int( mx_floor( p.y ) ).toVar();
  14189. const iz = int( mx_floor( p.z ) ).toVar();
  14190. const iw = int( mx_floor( p.w ) ).toVar();
  14191. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  14192. } ).setLayout( {
  14193. name: 'mx_cell_noise_float_3',
  14194. type: 'float',
  14195. inputs: [
  14196. { name: 'p', type: 'vec4' }
  14197. ]
  14198. } );
  14199. const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] );
  14200. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14201. const p = float( p_immutable ).toVar();
  14202. const ix = int( mx_floor( p ) ).toVar();
  14203. return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) );
  14204. } ).setLayout( {
  14205. name: 'mx_cell_noise_vec3_0',
  14206. type: 'vec3',
  14207. inputs: [
  14208. { name: 'p', type: 'float' }
  14209. ]
  14210. } );
  14211. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14212. const p = vec2( p_immutable ).toVar();
  14213. const ix = int( mx_floor( p.x ) ).toVar();
  14214. const iy = int( mx_floor( p.y ) ).toVar();
  14215. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) );
  14216. } ).setLayout( {
  14217. name: 'mx_cell_noise_vec3_1',
  14218. type: 'vec3',
  14219. inputs: [
  14220. { name: 'p', type: 'vec2' }
  14221. ]
  14222. } );
  14223. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14224. const p = vec3( p_immutable ).toVar();
  14225. const ix = int( mx_floor( p.x ) ).toVar();
  14226. const iy = int( mx_floor( p.y ) ).toVar();
  14227. const iz = int( mx_floor( p.z ) ).toVar();
  14228. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) );
  14229. } ).setLayout( {
  14230. name: 'mx_cell_noise_vec3_2',
  14231. type: 'vec3',
  14232. inputs: [
  14233. { name: 'p', type: 'vec3' }
  14234. ]
  14235. } );
  14236. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  14237. const p = vec4( p_immutable ).toVar();
  14238. const ix = int( mx_floor( p.x ) ).toVar();
  14239. const iy = int( mx_floor( p.y ) ).toVar();
  14240. const iz = int( mx_floor( p.z ) ).toVar();
  14241. const iw = int( mx_floor( p.w ) ).toVar();
  14242. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) );
  14243. } ).setLayout( {
  14244. name: 'mx_cell_noise_vec3_3',
  14245. type: 'vec3',
  14246. inputs: [
  14247. { name: 'p', type: 'vec4' }
  14248. ]
  14249. } );
  14250. const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] );
  14251. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  14252. const diminish = float( diminish_immutable ).toVar();
  14253. const lacunarity = float( lacunarity_immutable ).toVar();
  14254. const octaves = int( octaves_immutable ).toVar();
  14255. const p = vec3( p_immutable ).toVar();
  14256. const result = float( 0.0 ).toVar();
  14257. const amplitude = float( 1.0 ).toVar();
  14258. Loop( octaves, () => {
  14259. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  14260. amplitude.mulAssign( diminish );
  14261. p.mulAssign( lacunarity );
  14262. } );
  14263. return result;
  14264. } ).setLayout( {
  14265. name: 'mx_fractal_noise_float',
  14266. type: 'float',
  14267. inputs: [
  14268. { name: 'p', type: 'vec3' },
  14269. { name: 'octaves', type: 'int' },
  14270. { name: 'lacunarity', type: 'float' },
  14271. { name: 'diminish', type: 'float' }
  14272. ]
  14273. } );
  14274. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  14275. const diminish = float( diminish_immutable ).toVar();
  14276. const lacunarity = float( lacunarity_immutable ).toVar();
  14277. const octaves = int( octaves_immutable ).toVar();
  14278. const p = vec3( p_immutable ).toVar();
  14279. const result = vec3( 0.0 ).toVar();
  14280. const amplitude = float( 1.0 ).toVar();
  14281. Loop( octaves, () => {
  14282. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  14283. amplitude.mulAssign( diminish );
  14284. p.mulAssign( lacunarity );
  14285. } );
  14286. return result;
  14287. } ).setLayout( {
  14288. name: 'mx_fractal_noise_vec3',
  14289. type: 'vec3',
  14290. inputs: [
  14291. { name: 'p', type: 'vec3' },
  14292. { name: 'octaves', type: 'int' },
  14293. { name: 'lacunarity', type: 'float' },
  14294. { name: 'diminish', type: 'float' }
  14295. ]
  14296. } );
  14297. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  14298. const diminish = float( diminish_immutable ).toVar();
  14299. const lacunarity = float( lacunarity_immutable ).toVar();
  14300. const octaves = int( octaves_immutable ).toVar();
  14301. const p = vec3( p_immutable ).toVar();
  14302. return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) );
  14303. } ).setLayout( {
  14304. name: 'mx_fractal_noise_vec2',
  14305. type: 'vec2',
  14306. inputs: [
  14307. { name: 'p', type: 'vec3' },
  14308. { name: 'octaves', type: 'int' },
  14309. { name: 'lacunarity', type: 'float' },
  14310. { name: 'diminish', type: 'float' }
  14311. ]
  14312. } );
  14313. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  14314. const diminish = float( diminish_immutable ).toVar();
  14315. const lacunarity = float( lacunarity_immutable ).toVar();
  14316. const octaves = int( octaves_immutable ).toVar();
  14317. const p = vec3( p_immutable ).toVar();
  14318. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  14319. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  14320. return vec4( c, f );
  14321. } ).setLayout( {
  14322. name: 'mx_fractal_noise_vec4',
  14323. type: 'vec4',
  14324. inputs: [
  14325. { name: 'p', type: 'vec3' },
  14326. { name: 'octaves', type: 'int' },
  14327. { name: 'lacunarity', type: 'float' },
  14328. { name: 'diminish', type: 'float' }
  14329. ]
  14330. } );
  14331. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  14332. const metric = int( metric_immutable ).toVar();
  14333. const jitter = float( jitter_immutable ).toVar();
  14334. const yoff = int( yoff_immutable ).toVar();
  14335. const xoff = int( xoff_immutable ).toVar();
  14336. const y = int( y_immutable ).toVar();
  14337. const x = int( x_immutable ).toVar();
  14338. const p = vec2( p_immutable ).toVar();
  14339. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  14340. const off = vec2( tmp.x, tmp.y ).toVar();
  14341. off.subAssign( 0.5 );
  14342. off.mulAssign( jitter );
  14343. off.addAssign( 0.5 );
  14344. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  14345. const diff = vec2( cellpos.sub( p ) ).toVar();
  14346. If( metric.equal( int( 2 ) ), () => {
  14347. return abs( diff.x ).add( abs( diff.y ) );
  14348. } );
  14349. If( metric.equal( int( 3 ) ), () => {
  14350. return max$1( abs( diff.x ), abs( diff.y ) );
  14351. } );
  14352. return dot( diff, diff );
  14353. } ).setLayout( {
  14354. name: 'mx_worley_distance_0',
  14355. type: 'float',
  14356. inputs: [
  14357. { name: 'p', type: 'vec2' },
  14358. { name: 'x', type: 'int' },
  14359. { name: 'y', type: 'int' },
  14360. { name: 'xoff', type: 'int' },
  14361. { name: 'yoff', type: 'int' },
  14362. { name: 'jitter', type: 'float' },
  14363. { name: 'metric', type: 'int' }
  14364. ]
  14365. } );
  14366. const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  14367. const metric = int( metric_immutable ).toVar();
  14368. const jitter = float( jitter_immutable ).toVar();
  14369. const zoff = int( zoff_immutable ).toVar();
  14370. const yoff = int( yoff_immutable ).toVar();
  14371. const xoff = int( xoff_immutable ).toVar();
  14372. const z = int( z_immutable ).toVar();
  14373. const y = int( y_immutable ).toVar();
  14374. const x = int( x_immutable ).toVar();
  14375. const p = vec3( p_immutable ).toVar();
  14376. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  14377. off.subAssign( 0.5 );
  14378. off.mulAssign( jitter );
  14379. off.addAssign( 0.5 );
  14380. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  14381. const diff = vec3( cellpos.sub( p ) ).toVar();
  14382. If( metric.equal( int( 2 ) ), () => {
  14383. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  14384. } );
  14385. If( metric.equal( int( 3 ) ), () => {
  14386. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  14387. } );
  14388. return dot( diff, diff );
  14389. } ).setLayout( {
  14390. name: 'mx_worley_distance_1',
  14391. type: 'float',
  14392. inputs: [
  14393. { name: 'p', type: 'vec3' },
  14394. { name: 'x', type: 'int' },
  14395. { name: 'y', type: 'int' },
  14396. { name: 'z', type: 'int' },
  14397. { name: 'xoff', type: 'int' },
  14398. { name: 'yoff', type: 'int' },
  14399. { name: 'zoff', type: 'int' },
  14400. { name: 'jitter', type: 'float' },
  14401. { name: 'metric', type: 'int' }
  14402. ]
  14403. } );
  14404. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  14405. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14406. const metric = int( metric_immutable ).toVar();
  14407. const jitter = float( jitter_immutable ).toVar();
  14408. const p = vec2( p_immutable ).toVar();
  14409. const X = int().toVar(), Y = int().toVar();
  14410. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  14411. const sqdist = float( 1e6 ).toVar();
  14412. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14413. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14414. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  14415. sqdist.assign( min$1( sqdist, dist ) );
  14416. } );
  14417. } );
  14418. If( metric.equal( int( 0 ) ), () => {
  14419. sqdist.assign( sqrt( sqdist ) );
  14420. } );
  14421. return sqdist;
  14422. } ).setLayout( {
  14423. name: 'mx_worley_noise_float_0',
  14424. type: 'float',
  14425. inputs: [
  14426. { name: 'p', type: 'vec2' },
  14427. { name: 'jitter', type: 'float' },
  14428. { name: 'metric', type: 'int' }
  14429. ]
  14430. } );
  14431. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14432. const metric = int( metric_immutable ).toVar();
  14433. const jitter = float( jitter_immutable ).toVar();
  14434. const p = vec2( p_immutable ).toVar();
  14435. const X = int().toVar(), Y = int().toVar();
  14436. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  14437. const sqdist = vec2( 1e6, 1e6 ).toVar();
  14438. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14439. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14440. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  14441. If( dist.lessThan( sqdist.x ), () => {
  14442. sqdist.y.assign( sqdist.x );
  14443. sqdist.x.assign( dist );
  14444. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  14445. sqdist.y.assign( dist );
  14446. } );
  14447. } );
  14448. } );
  14449. If( metric.equal( int( 0 ) ), () => {
  14450. sqdist.assign( sqrt( sqdist ) );
  14451. } );
  14452. return sqdist;
  14453. } ).setLayout( {
  14454. name: 'mx_worley_noise_vec2_0',
  14455. type: 'vec2',
  14456. inputs: [
  14457. { name: 'p', type: 'vec2' },
  14458. { name: 'jitter', type: 'float' },
  14459. { name: 'metric', type: 'int' }
  14460. ]
  14461. } );
  14462. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14463. const metric = int( metric_immutable ).toVar();
  14464. const jitter = float( jitter_immutable ).toVar();
  14465. const p = vec2( p_immutable ).toVar();
  14466. const X = int().toVar(), Y = int().toVar();
  14467. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  14468. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  14469. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14470. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14471. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  14472. If( dist.lessThan( sqdist.x ), () => {
  14473. sqdist.z.assign( sqdist.y );
  14474. sqdist.y.assign( sqdist.x );
  14475. sqdist.x.assign( dist );
  14476. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  14477. sqdist.z.assign( sqdist.y );
  14478. sqdist.y.assign( dist );
  14479. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  14480. sqdist.z.assign( dist );
  14481. } );
  14482. } );
  14483. } );
  14484. If( metric.equal( int( 0 ) ), () => {
  14485. sqdist.assign( sqrt( sqdist ) );
  14486. } );
  14487. return sqdist;
  14488. } ).setLayout( {
  14489. name: 'mx_worley_noise_vec3_0',
  14490. type: 'vec3',
  14491. inputs: [
  14492. { name: 'p', type: 'vec2' },
  14493. { name: 'jitter', type: 'float' },
  14494. { name: 'metric', type: 'int' }
  14495. ]
  14496. } );
  14497. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14498. const metric = int( metric_immutable ).toVar();
  14499. const jitter = float( jitter_immutable ).toVar();
  14500. const p = vec3( p_immutable ).toVar();
  14501. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14502. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  14503. const sqdist = float( 1e6 ).toVar();
  14504. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14505. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14506. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  14507. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  14508. sqdist.assign( min$1( sqdist, dist ) );
  14509. } );
  14510. } );
  14511. } );
  14512. If( metric.equal( int( 0 ) ), () => {
  14513. sqdist.assign( sqrt( sqdist ) );
  14514. } );
  14515. return sqdist;
  14516. } ).setLayout( {
  14517. name: 'mx_worley_noise_float_1',
  14518. type: 'float',
  14519. inputs: [
  14520. { name: 'p', type: 'vec3' },
  14521. { name: 'jitter', type: 'float' },
  14522. { name: 'metric', type: 'int' }
  14523. ]
  14524. } );
  14525. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  14526. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14527. const metric = int( metric_immutable ).toVar();
  14528. const jitter = float( jitter_immutable ).toVar();
  14529. const p = vec3( p_immutable ).toVar();
  14530. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14531. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  14532. const sqdist = vec2( 1e6, 1e6 ).toVar();
  14533. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14534. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14535. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  14536. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  14537. If( dist.lessThan( sqdist.x ), () => {
  14538. sqdist.y.assign( sqdist.x );
  14539. sqdist.x.assign( dist );
  14540. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  14541. sqdist.y.assign( dist );
  14542. } );
  14543. } );
  14544. } );
  14545. } );
  14546. If( metric.equal( int( 0 ) ), () => {
  14547. sqdist.assign( sqrt( sqdist ) );
  14548. } );
  14549. return sqdist;
  14550. } ).setLayout( {
  14551. name: 'mx_worley_noise_vec2_1',
  14552. type: 'vec2',
  14553. inputs: [
  14554. { name: 'p', type: 'vec3' },
  14555. { name: 'jitter', type: 'float' },
  14556. { name: 'metric', type: 'int' }
  14557. ]
  14558. } );
  14559. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  14560. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  14561. const metric = int( metric_immutable ).toVar();
  14562. const jitter = float( jitter_immutable ).toVar();
  14563. const p = vec3( p_immutable ).toVar();
  14564. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  14565. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  14566. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  14567. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  14568. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  14569. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  14570. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  14571. If( dist.lessThan( sqdist.x ), () => {
  14572. sqdist.z.assign( sqdist.y );
  14573. sqdist.y.assign( sqdist.x );
  14574. sqdist.x.assign( dist );
  14575. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  14576. sqdist.z.assign( sqdist.y );
  14577. sqdist.y.assign( dist );
  14578. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  14579. sqdist.z.assign( dist );
  14580. } );
  14581. } );
  14582. } );
  14583. } );
  14584. If( metric.equal( int( 0 ) ), () => {
  14585. sqdist.assign( sqrt( sqdist ) );
  14586. } );
  14587. return sqdist;
  14588. } ).setLayout( {
  14589. name: 'mx_worley_noise_vec3_1',
  14590. type: 'vec3',
  14591. inputs: [
  14592. { name: 'p', type: 'vec3' },
  14593. { name: 'jitter', type: 'float' },
  14594. { name: 'metric', type: 'int' }
  14595. ]
  14596. } );
  14597. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  14598. // Three.js Transpiler
  14599. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  14600. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  14601. const s = hsv.y;
  14602. const v = hsv.z;
  14603. const result = vec3().toVar();
  14604. If( s.lessThan( 0.0001 ), () => {
  14605. result.assign( vec3( v, v, v ) );
  14606. } ).Else( () => {
  14607. let h = hsv.x;
  14608. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  14609. const hi = int( trunc( h ) );
  14610. const f = h.sub( float( hi ) );
  14611. const p = v.mul( s.oneMinus() );
  14612. const q = v.mul( s.mul( f ).oneMinus() );
  14613. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  14614. If( hi.equal( int( 0 ) ), () => {
  14615. result.assign( vec3( v, t, p ) );
  14616. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  14617. result.assign( vec3( q, v, p ) );
  14618. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  14619. result.assign( vec3( p, v, t ) );
  14620. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  14621. result.assign( vec3( p, q, v ) );
  14622. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  14623. result.assign( vec3( t, p, v ) );
  14624. } ).Else( () => {
  14625. result.assign( vec3( v, p, q ) );
  14626. } );
  14627. } );
  14628. return result;
  14629. } ).setLayout( {
  14630. name: 'mx_hsvtorgb',
  14631. type: 'vec3',
  14632. inputs: [
  14633. { name: 'hsv', type: 'vec3' }
  14634. ]
  14635. } );
  14636. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  14637. const c = vec3( c_immutable ).toVar();
  14638. const r = float( c.x ).toVar();
  14639. const g = float( c.y ).toVar();
  14640. const b = float( c.z ).toVar();
  14641. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  14642. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  14643. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  14644. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  14645. v.assign( maxcomp );
  14646. If( maxcomp.greaterThan( 0.0 ), () => {
  14647. s.assign( delta.div( maxcomp ) );
  14648. } ).Else( () => {
  14649. s.assign( 0.0 );
  14650. } );
  14651. If( s.lessThanEqual( 0.0 ), () => {
  14652. h.assign( 0.0 );
  14653. } ).Else( () => {
  14654. If( r.greaterThanEqual( maxcomp ), () => {
  14655. h.assign( g.sub( b ).div( delta ) );
  14656. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  14657. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  14658. } ).Else( () => {
  14659. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  14660. } );
  14661. h.mulAssign( 1.0 / 6.0 );
  14662. If( h.lessThan( 0.0 ), () => {
  14663. h.addAssign( 1.0 );
  14664. } );
  14665. } );
  14666. return vec3( h, s, v );
  14667. } ).setLayout( {
  14668. name: 'mx_rgbtohsv',
  14669. type: 'vec3',
  14670. inputs: [
  14671. { name: 'c', type: 'vec3' }
  14672. ]
  14673. } );
  14674. // Three.js Transpiler
  14675. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  14676. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  14677. const color = vec3( color_immutable ).toVar();
  14678. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  14679. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  14680. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  14681. return mix( linSeg, powSeg, isAbove );
  14682. } ).setLayout( {
  14683. name: 'mx_srgb_texture_to_lin_rec709',
  14684. type: 'vec3',
  14685. inputs: [
  14686. { name: 'color', type: 'vec3' }
  14687. ]
  14688. } );
  14689. const mx_aastep = ( threshold, value ) => {
  14690. threshold = float( threshold );
  14691. value = float( value );
  14692. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  14693. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  14694. };
  14695. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  14696. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  14697. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  14698. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  14699. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  14700. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  14701. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  14702. const mx_safepower = ( in1, in2 = 1 ) => {
  14703. in1 = float( in1 );
  14704. return in1.abs().pow( in2 ).mul( in1.sign() );
  14705. };
  14706. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  14707. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  14708. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  14709. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  14710. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  14711. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  14712. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  14713. return noise_vec4.mul( amplitude ).add( pivot );
  14714. };
  14715. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  14716. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  14717. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  14718. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  14719. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  14720. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  14721. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  14722. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  14723. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  14724. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  14725. const nDir = normalize( normal ).toVar( 'nDir' );
  14726. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  14727. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  14728. const rbminmax = vec3().toVar( 'rbminmax' );
  14729. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  14730. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  14731. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  14732. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  14733. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  14734. return boxIntersection.sub( cubePos );
  14735. } );
  14736. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  14737. // normal is assumed to have unit length
  14738. const x = normal.x, y = normal.y, z = normal.z;
  14739. // band 0
  14740. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  14741. // band 1
  14742. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  14743. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  14744. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  14745. // band 2
  14746. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  14747. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  14748. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  14749. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  14750. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  14751. return result;
  14752. } );
  14753. // constants
  14754. var TSL = /*#__PURE__*/Object.freeze({
  14755. __proto__: null,
  14756. BRDF_GGX: BRDF_GGX,
  14757. BRDF_Lambert: BRDF_Lambert,
  14758. BasicShadowFilter: BasicShadowFilter,
  14759. Break: Break,
  14760. Continue: Continue,
  14761. DFGApprox: DFGApprox,
  14762. D_GGX: D_GGX,
  14763. Discard: Discard,
  14764. EPSILON: EPSILON,
  14765. F_Schlick: F_Schlick,
  14766. Fn: Fn,
  14767. INFINITY: INFINITY,
  14768. If: If,
  14769. Loop: Loop,
  14770. NodeAccess: NodeAccess,
  14771. NodeShaderStage: NodeShaderStage,
  14772. NodeType: NodeType,
  14773. NodeUpdateType: NodeUpdateType,
  14774. PCFShadowFilter: PCFShadowFilter,
  14775. PCFSoftShadowFilter: PCFSoftShadowFilter,
  14776. PI: PI,
  14777. PI2: PI2,
  14778. Return: Return,
  14779. Schlick_to_F0: Schlick_to_F0,
  14780. ScriptableNodeResources: ScriptableNodeResources,
  14781. ShaderNode: ShaderNode,
  14782. TBNViewMatrix: TBNViewMatrix,
  14783. VSMShadowFilter: VSMShadowFilter,
  14784. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  14785. abs: abs,
  14786. acesFilmicToneMapping: acesFilmicToneMapping,
  14787. acos: acos,
  14788. add: add,
  14789. addMethodChaining: addMethodChaining,
  14790. addNodeElement: addNodeElement,
  14791. agxToneMapping: agxToneMapping,
  14792. all: all,
  14793. alphaT: alphaT,
  14794. and: and,
  14795. anisotropy: anisotropy,
  14796. anisotropyB: anisotropyB,
  14797. anisotropyT: anisotropyT,
  14798. any: any,
  14799. append: append,
  14800. arrayBuffer: arrayBuffer,
  14801. asin: asin,
  14802. assign: assign,
  14803. atan: atan,
  14804. atan2: atan2,
  14805. atomicAdd: atomicAdd,
  14806. atomicAnd: atomicAnd,
  14807. atomicFunc: atomicFunc,
  14808. atomicMax: atomicMax,
  14809. atomicMin: atomicMin,
  14810. atomicOr: atomicOr,
  14811. atomicStore: atomicStore,
  14812. atomicSub: atomicSub,
  14813. atomicXor: atomicXor,
  14814. attenuationColor: attenuationColor,
  14815. attenuationDistance: attenuationDistance,
  14816. attribute: attribute,
  14817. attributeArray: attributeArray,
  14818. backgroundBlurriness: backgroundBlurriness,
  14819. backgroundIntensity: backgroundIntensity,
  14820. backgroundRotation: backgroundRotation,
  14821. batch: batch,
  14822. billboarding: billboarding,
  14823. bitAnd: bitAnd,
  14824. bitNot: bitNot,
  14825. bitOr: bitOr,
  14826. bitXor: bitXor,
  14827. bitangentGeometry: bitangentGeometry,
  14828. bitangentLocal: bitangentLocal,
  14829. bitangentView: bitangentView,
  14830. bitangentWorld: bitangentWorld,
  14831. bitcast: bitcast,
  14832. blendBurn: blendBurn,
  14833. blendColor: blendColor,
  14834. blendDodge: blendDodge,
  14835. blendOverlay: blendOverlay,
  14836. blendScreen: blendScreen,
  14837. blur: blur,
  14838. bool: bool,
  14839. buffer: buffer,
  14840. bufferAttribute: bufferAttribute,
  14841. bumpMap: bumpMap,
  14842. burn: burn,
  14843. bvec2: bvec2,
  14844. bvec3: bvec3,
  14845. bvec4: bvec4,
  14846. bypass: bypass,
  14847. cache: cache,
  14848. call: call,
  14849. cameraFar: cameraFar,
  14850. cameraNear: cameraNear,
  14851. cameraNormalMatrix: cameraNormalMatrix,
  14852. cameraPosition: cameraPosition,
  14853. cameraProjectionMatrix: cameraProjectionMatrix,
  14854. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  14855. cameraViewMatrix: cameraViewMatrix,
  14856. cameraWorldMatrix: cameraWorldMatrix,
  14857. cbrt: cbrt,
  14858. cdl: cdl,
  14859. ceil: ceil,
  14860. checker: checker,
  14861. cineonToneMapping: cineonToneMapping,
  14862. clamp: clamp,
  14863. clearcoat: clearcoat,
  14864. clearcoatRoughness: clearcoatRoughness,
  14865. code: code,
  14866. color: color,
  14867. colorSpaceToWorking: colorSpaceToWorking,
  14868. colorToDirection: colorToDirection,
  14869. compute: compute,
  14870. cond: cond,
  14871. context: context,
  14872. convert: convert,
  14873. convertColorSpace: convertColorSpace,
  14874. convertToTexture: convertToTexture,
  14875. cos: cos,
  14876. cross: cross,
  14877. cubeTexture: cubeTexture,
  14878. dFdx: dFdx,
  14879. dFdy: dFdy,
  14880. dashSize: dashSize,
  14881. defaultBuildStages: defaultBuildStages,
  14882. defaultShaderStages: defaultShaderStages,
  14883. defined: defined,
  14884. degrees: degrees,
  14885. deltaTime: deltaTime,
  14886. densityFog: densityFog,
  14887. depth: depth,
  14888. depthPass: depthPass,
  14889. difference: difference,
  14890. diffuseColor: diffuseColor,
  14891. directPointLight: directPointLight,
  14892. directionToColor: directionToColor,
  14893. dispersion: dispersion,
  14894. distance: distance,
  14895. div: div,
  14896. dodge: dodge,
  14897. dot: dot,
  14898. drawIndex: drawIndex,
  14899. dynamicBufferAttribute: dynamicBufferAttribute,
  14900. element: element,
  14901. emissive: emissive,
  14902. equal: equal,
  14903. equals: equals,
  14904. equirectUV: equirectUV,
  14905. exp: exp,
  14906. exp2: exp2,
  14907. expression: expression,
  14908. faceDirection: faceDirection,
  14909. faceForward: faceForward,
  14910. float: float,
  14911. floor: floor,
  14912. fog: fog,
  14913. fract: fract,
  14914. frameGroup: frameGroup,
  14915. frameId: frameId,
  14916. frontFacing: frontFacing,
  14917. fwidth: fwidth,
  14918. gain: gain,
  14919. gapSize: gapSize,
  14920. getConstNodeType: getConstNodeType,
  14921. getCurrentStack: getCurrentStack,
  14922. getDirection: getDirection,
  14923. getDistanceAttenuation: getDistanceAttenuation,
  14924. getGeometryRoughness: getGeometryRoughness,
  14925. getNormalFromDepth: getNormalFromDepth,
  14926. getParallaxCorrectNormal: getParallaxCorrectNormal,
  14927. getRoughness: getRoughness,
  14928. getScreenPosition: getScreenPosition,
  14929. getShIrradianceAt: getShIrradianceAt,
  14930. getTextureIndex: getTextureIndex,
  14931. getViewPosition: getViewPosition,
  14932. glsl: glsl,
  14933. glslFn: glslFn,
  14934. grayscale: grayscale,
  14935. greaterThan: greaterThan,
  14936. greaterThanEqual: greaterThanEqual,
  14937. hash: hash,
  14938. highPrecisionModelNormalViewMatrix: highPrecisionModelNormalViewMatrix,
  14939. highPrecisionModelViewMatrix: highPrecisionModelViewMatrix,
  14940. hue: hue,
  14941. instance: instance,
  14942. instanceIndex: instanceIndex,
  14943. instancedArray: instancedArray,
  14944. instancedBufferAttribute: instancedBufferAttribute,
  14945. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  14946. instancedMesh: instancedMesh,
  14947. int: int,
  14948. inverseSqrt: inverseSqrt,
  14949. invocationLocalIndex: invocationLocalIndex,
  14950. invocationSubgroupIndex: invocationSubgroupIndex,
  14951. ior: ior,
  14952. iridescence: iridescence,
  14953. iridescenceIOR: iridescenceIOR,
  14954. iridescenceThickness: iridescenceThickness,
  14955. ivec2: ivec2,
  14956. ivec3: ivec3,
  14957. ivec4: ivec4,
  14958. js: js,
  14959. label: label,
  14960. length: length,
  14961. lengthSq: lengthSq,
  14962. lessThan: lessThan,
  14963. lessThanEqual: lessThanEqual,
  14964. lightPosition: lightPosition,
  14965. lightProjectionUV: lightProjectionUV,
  14966. lightShadowMatrix: lightShadowMatrix,
  14967. lightTargetDirection: lightTargetDirection,
  14968. lightTargetPosition: lightTargetPosition,
  14969. lightViewPosition: lightViewPosition,
  14970. lightingContext: lightingContext,
  14971. lights: lights,
  14972. linearDepth: linearDepth,
  14973. linearToneMapping: linearToneMapping,
  14974. localId: localId,
  14975. log: log,
  14976. log2: log2,
  14977. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  14978. loop: loop,
  14979. luminance: luminance,
  14980. mat2: mat2,
  14981. mat3: mat3,
  14982. mat4: mat4,
  14983. matcapUV: matcapUV,
  14984. materialAOMap: materialAOMap,
  14985. materialAlphaTest: materialAlphaTest,
  14986. materialAnisotropy: materialAnisotropy,
  14987. materialAnisotropyVector: materialAnisotropyVector,
  14988. materialAttenuationColor: materialAttenuationColor,
  14989. materialAttenuationDistance: materialAttenuationDistance,
  14990. materialClearcoat: materialClearcoat,
  14991. materialClearcoatNormal: materialClearcoatNormal,
  14992. materialClearcoatRoughness: materialClearcoatRoughness,
  14993. materialColor: materialColor,
  14994. materialDispersion: materialDispersion,
  14995. materialEmissive: materialEmissive,
  14996. materialIOR: materialIOR,
  14997. materialIridescence: materialIridescence,
  14998. materialIridescenceIOR: materialIridescenceIOR,
  14999. materialIridescenceThickness: materialIridescenceThickness,
  15000. materialLightMap: materialLightMap,
  15001. materialLineDashOffset: materialLineDashOffset,
  15002. materialLineDashSize: materialLineDashSize,
  15003. materialLineGapSize: materialLineGapSize,
  15004. materialLineScale: materialLineScale,
  15005. materialLineWidth: materialLineWidth,
  15006. materialMetalness: materialMetalness,
  15007. materialNormal: materialNormal,
  15008. materialOpacity: materialOpacity,
  15009. materialPointWidth: materialPointWidth,
  15010. materialReference: materialReference,
  15011. materialReflectivity: materialReflectivity,
  15012. materialRefractionRatio: materialRefractionRatio,
  15013. materialRotation: materialRotation,
  15014. materialRoughness: materialRoughness,
  15015. materialSheen: materialSheen,
  15016. materialSheenRoughness: materialSheenRoughness,
  15017. materialShininess: materialShininess,
  15018. materialSpecular: materialSpecular,
  15019. materialSpecularColor: materialSpecularColor,
  15020. materialSpecularIntensity: materialSpecularIntensity,
  15021. materialSpecularStrength: materialSpecularStrength,
  15022. materialThickness: materialThickness,
  15023. materialTransmission: materialTransmission,
  15024. max: max$1,
  15025. maxMipLevel: maxMipLevel,
  15026. metalness: metalness,
  15027. min: min$1,
  15028. mix: mix,
  15029. mixElement: mixElement,
  15030. mod: mod,
  15031. modInt: modInt,
  15032. modelDirection: modelDirection,
  15033. modelNormalMatrix: modelNormalMatrix,
  15034. modelPosition: modelPosition,
  15035. modelScale: modelScale,
  15036. modelViewMatrix: modelViewMatrix,
  15037. modelViewPosition: modelViewPosition,
  15038. modelViewProjection: modelViewProjection,
  15039. modelWorldMatrix: modelWorldMatrix,
  15040. modelWorldMatrixInverse: modelWorldMatrixInverse,
  15041. morphReference: morphReference,
  15042. mrt: mrt,
  15043. mul: mul,
  15044. mx_aastep: mx_aastep,
  15045. mx_cell_noise_float: mx_cell_noise_float,
  15046. mx_contrast: mx_contrast,
  15047. mx_fractal_noise_float: mx_fractal_noise_float,
  15048. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  15049. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  15050. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  15051. mx_hsvtorgb: mx_hsvtorgb,
  15052. mx_noise_float: mx_noise_float,
  15053. mx_noise_vec3: mx_noise_vec3,
  15054. mx_noise_vec4: mx_noise_vec4,
  15055. mx_ramplr: mx_ramplr,
  15056. mx_ramptb: mx_ramptb,
  15057. mx_rgbtohsv: mx_rgbtohsv,
  15058. mx_safepower: mx_safepower,
  15059. mx_splitlr: mx_splitlr,
  15060. mx_splittb: mx_splittb,
  15061. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  15062. mx_transform_uv: mx_transform_uv,
  15063. mx_worley_noise_float: mx_worley_noise_float,
  15064. mx_worley_noise_vec2: mx_worley_noise_vec2,
  15065. mx_worley_noise_vec3: mx_worley_noise_vec3,
  15066. negate: negate,
  15067. neutralToneMapping: neutralToneMapping,
  15068. nodeArray: nodeArray,
  15069. nodeImmutable: nodeImmutable,
  15070. nodeObject: nodeObject,
  15071. nodeObjects: nodeObjects,
  15072. nodeProxy: nodeProxy,
  15073. normalFlat: normalFlat,
  15074. normalGeometry: normalGeometry,
  15075. normalLocal: normalLocal,
  15076. normalMap: normalMap,
  15077. normalView: normalView,
  15078. normalWorld: normalWorld,
  15079. normalize: normalize,
  15080. not: not,
  15081. notEqual: notEqual,
  15082. numWorkgroups: numWorkgroups,
  15083. objectDirection: objectDirection,
  15084. objectGroup: objectGroup,
  15085. objectPosition: objectPosition,
  15086. objectScale: objectScale,
  15087. objectViewPosition: objectViewPosition,
  15088. objectWorldMatrix: objectWorldMatrix,
  15089. oneMinus: oneMinus,
  15090. or: or,
  15091. orthographicDepthToViewZ: orthographicDepthToViewZ,
  15092. oscSawtooth: oscSawtooth,
  15093. oscSine: oscSine,
  15094. oscSquare: oscSquare,
  15095. oscTriangle: oscTriangle,
  15096. output: output,
  15097. outputStruct: outputStruct,
  15098. overlay: overlay,
  15099. overloadingFn: overloadingFn,
  15100. parabola: parabola,
  15101. parallaxDirection: parallaxDirection,
  15102. parallaxUV: parallaxUV,
  15103. parameter: parameter,
  15104. pass: pass,
  15105. passTexture: passTexture,
  15106. pcurve: pcurve,
  15107. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  15108. pmremTexture: pmremTexture,
  15109. pointUV: pointUV,
  15110. pointWidth: pointWidth,
  15111. positionGeometry: positionGeometry,
  15112. positionLocal: positionLocal,
  15113. positionPrevious: positionPrevious,
  15114. positionView: positionView,
  15115. positionViewDirection: positionViewDirection,
  15116. positionWorld: positionWorld,
  15117. positionWorldDirection: positionWorldDirection,
  15118. posterize: posterize,
  15119. pow: pow,
  15120. pow2: pow2,
  15121. pow3: pow3,
  15122. pow4: pow4,
  15123. property: property,
  15124. radians: radians,
  15125. rand: rand,
  15126. range: range,
  15127. rangeFog: rangeFog,
  15128. reciprocal: reciprocal,
  15129. reference: reference,
  15130. referenceBuffer: referenceBuffer,
  15131. reflect: reflect,
  15132. reflectVector: reflectVector,
  15133. reflectView: reflectView,
  15134. reflector: reflector,
  15135. refract: refract,
  15136. refractVector: refractVector,
  15137. refractView: refractView,
  15138. reinhardToneMapping: reinhardToneMapping,
  15139. remainder: remainder,
  15140. remap: remap,
  15141. remapClamp: remapClamp,
  15142. renderGroup: renderGroup,
  15143. renderOutput: renderOutput,
  15144. rendererReference: rendererReference,
  15145. rotate: rotate,
  15146. rotateUV: rotateUV,
  15147. roughness: roughness,
  15148. round: round,
  15149. rtt: rtt,
  15150. sRGBTransferEOTF: sRGBTransferEOTF,
  15151. sRGBTransferOETF: sRGBTransferOETF,
  15152. sampler: sampler,
  15153. saturate: saturate,
  15154. saturation: saturation,
  15155. screen: screen,
  15156. screenCoordinate: screenCoordinate,
  15157. screenSize: screenSize,
  15158. screenUV: screenUV,
  15159. scriptable: scriptable,
  15160. scriptableValue: scriptableValue,
  15161. select: select,
  15162. setCurrentStack: setCurrentStack,
  15163. shaderStages: shaderStages,
  15164. shadow: shadow,
  15165. sharedUniformGroup: sharedUniformGroup,
  15166. sheen: sheen,
  15167. sheenRoughness: sheenRoughness,
  15168. shiftLeft: shiftLeft,
  15169. shiftRight: shiftRight,
  15170. shininess: shininess,
  15171. sign: sign,
  15172. sin: sin,
  15173. sinc: sinc,
  15174. skinning: skinning,
  15175. skinningReference: skinningReference,
  15176. smoothstep: smoothstep,
  15177. smoothstepElement: smoothstepElement,
  15178. specularColor: specularColor,
  15179. specularF90: specularF90,
  15180. spherizeUV: spherizeUV,
  15181. split: split,
  15182. spritesheetUV: spritesheetUV,
  15183. sqrt: sqrt,
  15184. stack: stack,
  15185. step: step,
  15186. storage: storage,
  15187. storageBarrier: storageBarrier,
  15188. storageObject: storageObject,
  15189. storageTexture: storageTexture,
  15190. string: string,
  15191. sub: sub,
  15192. subgroupIndex: subgroupIndex,
  15193. subgroupSize: subgroupSize,
  15194. tan: tan,
  15195. tangentGeometry: tangentGeometry,
  15196. tangentLocal: tangentLocal,
  15197. tangentView: tangentView,
  15198. tangentWorld: tangentWorld,
  15199. temp: temp,
  15200. texture: texture,
  15201. texture3D: texture3D,
  15202. textureBarrier: textureBarrier,
  15203. textureBicubic: textureBicubic,
  15204. textureCubeUV: textureCubeUV,
  15205. textureLoad: textureLoad,
  15206. textureSize: textureSize,
  15207. textureStore: textureStore,
  15208. thickness: thickness,
  15209. threshold: threshold,
  15210. time: time,
  15211. timerDelta: timerDelta,
  15212. timerGlobal: timerGlobal,
  15213. timerLocal: timerLocal,
  15214. toOutputColorSpace: toOutputColorSpace,
  15215. toWorkingColorSpace: toWorkingColorSpace,
  15216. toneMapping: toneMapping,
  15217. toneMappingExposure: toneMappingExposure,
  15218. toonOutlinePass: toonOutlinePass,
  15219. transformDirection: transformDirection,
  15220. transformNormal: transformNormal,
  15221. transformNormalToView: transformNormalToView,
  15222. transformedBentNormalView: transformedBentNormalView,
  15223. transformedBitangentView: transformedBitangentView,
  15224. transformedBitangentWorld: transformedBitangentWorld,
  15225. transformedClearcoatNormalView: transformedClearcoatNormalView,
  15226. transformedNormalView: transformedNormalView,
  15227. transformedNormalWorld: transformedNormalWorld,
  15228. transformedTangentView: transformedTangentView,
  15229. transformedTangentWorld: transformedTangentWorld,
  15230. transmission: transmission,
  15231. transpose: transpose,
  15232. tri: tri,
  15233. tri3: tri3,
  15234. triNoise3D: triNoise3D,
  15235. triplanarTexture: triplanarTexture,
  15236. triplanarTextures: triplanarTextures,
  15237. trunc: trunc,
  15238. tslFn: tslFn,
  15239. uint: uint,
  15240. uniform: uniform,
  15241. uniformArray: uniformArray,
  15242. uniformGroup: uniformGroup,
  15243. uniforms: uniforms,
  15244. userData: userData,
  15245. uv: uv,
  15246. uvec2: uvec2,
  15247. uvec3: uvec3,
  15248. uvec4: uvec4,
  15249. varying: varying,
  15250. varyingProperty: varyingProperty,
  15251. vec2: vec2,
  15252. vec3: vec3,
  15253. vec4: vec4,
  15254. vectorComponents: vectorComponents,
  15255. velocity: velocity,
  15256. vertexColor: vertexColor,
  15257. vertexIndex: vertexIndex,
  15258. vibrance: vibrance,
  15259. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  15260. viewZToOrthographicDepth: viewZToOrthographicDepth,
  15261. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  15262. viewport: viewport,
  15263. viewportBottomLeft: viewportBottomLeft,
  15264. viewportCoordinate: viewportCoordinate,
  15265. viewportDepthTexture: viewportDepthTexture,
  15266. viewportLinearDepth: viewportLinearDepth,
  15267. viewportMipTexture: viewportMipTexture,
  15268. viewportResolution: viewportResolution,
  15269. viewportSafeUV: viewportSafeUV,
  15270. viewportSharedTexture: viewportSharedTexture,
  15271. viewportSize: viewportSize,
  15272. viewportTexture: viewportTexture,
  15273. viewportTopLeft: viewportTopLeft,
  15274. viewportUV: viewportUV,
  15275. wgsl: wgsl,
  15276. wgslFn: wgslFn,
  15277. workgroupArray: workgroupArray,
  15278. workgroupBarrier: workgroupBarrier,
  15279. workgroupId: workgroupId,
  15280. workingToColorSpace: workingToColorSpace,
  15281. xor: xor
  15282. });
  15283. const _clearColor$1 = /*@__PURE__*/ new Color4();
  15284. class Background extends DataMap {
  15285. constructor( renderer, nodes ) {
  15286. super();
  15287. this.renderer = renderer;
  15288. this.nodes = nodes;
  15289. }
  15290. update( scene, renderList, renderContext ) {
  15291. const renderer = this.renderer;
  15292. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  15293. let forceClear = false;
  15294. if ( background === null ) {
  15295. // no background settings, use clear color configuration from the renderer
  15296. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  15297. _clearColor$1.a = renderer._clearColor.a;
  15298. } else if ( background.isColor === true ) {
  15299. // background is an opaque color
  15300. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  15301. _clearColor$1.a = 1;
  15302. forceClear = true;
  15303. } else if ( background.isNode === true ) {
  15304. const sceneData = this.get( scene );
  15305. const backgroundNode = background;
  15306. _clearColor$1.copy( renderer._clearColor );
  15307. let backgroundMesh = sceneData.backgroundMesh;
  15308. if ( backgroundMesh === undefined ) {
  15309. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  15310. // @TODO: Add Texture2D support using node context
  15311. getUV: () => backgroundRotation.mul( normalWorld ),
  15312. getTextureLevel: () => backgroundBlurriness
  15313. } );
  15314. let viewProj = modelViewProjection();
  15315. viewProj = viewProj.setZ( viewProj.w );
  15316. const nodeMaterial = new NodeMaterial();
  15317. nodeMaterial.name = 'Background.material';
  15318. nodeMaterial.side = BackSide;
  15319. nodeMaterial.depthTest = false;
  15320. nodeMaterial.depthWrite = false;
  15321. nodeMaterial.fog = false;
  15322. nodeMaterial.lights = false;
  15323. nodeMaterial.vertexNode = viewProj;
  15324. nodeMaterial.colorNode = backgroundMeshNode;
  15325. sceneData.backgroundMeshNode = backgroundMeshNode;
  15326. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  15327. backgroundMesh.frustumCulled = false;
  15328. backgroundMesh.name = 'Background.mesh';
  15329. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  15330. this.matrixWorld.copyPosition( camera.matrixWorld );
  15331. };
  15332. }
  15333. const backgroundCacheKey = backgroundNode.getCacheKey();
  15334. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  15335. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  15336. sceneData.backgroundMeshNode.needsUpdate = true;
  15337. backgroundMesh.material.needsUpdate = true;
  15338. sceneData.backgroundCacheKey = backgroundCacheKey;
  15339. }
  15340. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  15341. } else {
  15342. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  15343. }
  15344. //
  15345. if ( renderer.autoClear === true || forceClear === true ) {
  15346. const clearColorValue = renderContext.clearColorValue;
  15347. clearColorValue.r = _clearColor$1.r;
  15348. clearColorValue.g = _clearColor$1.g;
  15349. clearColorValue.b = _clearColor$1.b;
  15350. clearColorValue.a = _clearColor$1.a;
  15351. // premultiply alpha
  15352. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  15353. clearColorValue.r *= clearColorValue.a;
  15354. clearColorValue.g *= clearColorValue.a;
  15355. clearColorValue.b *= clearColorValue.a;
  15356. }
  15357. //
  15358. renderContext.depthClearValue = renderer._clearDepth;
  15359. renderContext.stencilClearValue = renderer._clearStencil;
  15360. renderContext.clearColor = renderer.autoClearColor === true;
  15361. renderContext.clearDepth = renderer.autoClearDepth === true;
  15362. renderContext.clearStencil = renderer.autoClearStencil === true;
  15363. } else {
  15364. renderContext.clearColor = false;
  15365. renderContext.clearDepth = false;
  15366. renderContext.clearStencil = false;
  15367. }
  15368. }
  15369. }
  15370. let _id$6 = 0;
  15371. class BindGroup {
  15372. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  15373. this.name = name;
  15374. this.bindings = bindings;
  15375. this.index = index;
  15376. this.bindingsReference = bindingsReference;
  15377. this.id = _id$6 ++;
  15378. }
  15379. }
  15380. class NodeBuilderState {
  15381. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  15382. this.vertexShader = vertexShader;
  15383. this.fragmentShader = fragmentShader;
  15384. this.computeShader = computeShader;
  15385. this.transforms = transforms;
  15386. this.nodeAttributes = nodeAttributes;
  15387. this.bindings = bindings;
  15388. this.updateNodes = updateNodes;
  15389. this.updateBeforeNodes = updateBeforeNodes;
  15390. this.updateAfterNodes = updateAfterNodes;
  15391. this.monitor = monitor;
  15392. this.usedTimes = 0;
  15393. }
  15394. createBindings() {
  15395. const bindings = [];
  15396. for ( const instanceGroup of this.bindings ) {
  15397. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  15398. if ( shared !== true ) {
  15399. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  15400. bindings.push( bindingsGroup );
  15401. for ( const instanceBinding of instanceGroup.bindings ) {
  15402. bindingsGroup.bindings.push( instanceBinding.clone() );
  15403. }
  15404. } else {
  15405. bindings.push( instanceGroup );
  15406. }
  15407. }
  15408. return bindings;
  15409. }
  15410. }
  15411. /**
  15412. * {@link NodeBuilder} is going to create instances of this class during the build process
  15413. * of nodes. They represent the final shader attributes that are going to be generated
  15414. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  15415. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  15416. */
  15417. class NodeAttribute {
  15418. /**
  15419. * Constructs a new node attribute.
  15420. *
  15421. * @param {String} name - The name of the attribute.
  15422. * @param {String} type - The type of the attribute.
  15423. * @param {Node?} node - An optional reference to the node.
  15424. */
  15425. constructor( name, type, node = null ) {
  15426. /**
  15427. * This flag can be used for type testing.
  15428. *
  15429. * @type {Boolean}
  15430. * @readonly
  15431. * @default true
  15432. */
  15433. this.isNodeAttribute = true;
  15434. /**
  15435. * The name of the attribute.
  15436. *
  15437. * @type {String}
  15438. */
  15439. this.name = name;
  15440. /**
  15441. * The type of the attribute.
  15442. *
  15443. * @type {String}
  15444. */
  15445. this.type = type;
  15446. /**
  15447. * An optional reference to the node.
  15448. *
  15449. * @type {Node?}
  15450. * @default null
  15451. */
  15452. this.node = node;
  15453. }
  15454. }
  15455. /**
  15456. * {@link NodeBuilder} is going to create instances of this class during the build process
  15457. * of nodes. They represent the final shader uniforms that are going to be generated
  15458. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  15459. * for this purpose.
  15460. */
  15461. class NodeUniform {
  15462. /**
  15463. * Constructs a new node uniform.
  15464. *
  15465. * @param {String} name - The name of the uniform.
  15466. * @param {String} type - The type of the uniform.
  15467. * @param {UniformNode} node - An reference to the node.
  15468. */
  15469. constructor( name, type, node ) {
  15470. /**
  15471. * This flag can be used for type testing.
  15472. *
  15473. * @type {Boolean}
  15474. * @readonly
  15475. * @default true
  15476. */
  15477. this.isNodeUniform = true;
  15478. /**
  15479. * The name of the uniform.
  15480. *
  15481. * @type {String}
  15482. */
  15483. this.name = name;
  15484. /**
  15485. * The type of the uniform.
  15486. *
  15487. * @type {String}
  15488. */
  15489. this.type = type;
  15490. /**
  15491. * An reference to the node.
  15492. *
  15493. * @type {UniformNode}
  15494. */
  15495. this.node = node.getSelf();
  15496. }
  15497. /**
  15498. * The value of the uniform node.
  15499. *
  15500. * @type {Any}
  15501. */
  15502. get value() {
  15503. return this.node.value;
  15504. }
  15505. set value( val ) {
  15506. this.node.value = val;
  15507. }
  15508. /**
  15509. * The id of the uniform node.
  15510. *
  15511. * @type {Number}
  15512. */
  15513. get id() {
  15514. return this.node.id;
  15515. }
  15516. /**
  15517. * The uniform node's group.
  15518. *
  15519. * @type {UniformGroupNode}
  15520. */
  15521. get groupNode() {
  15522. return this.node.groupNode;
  15523. }
  15524. }
  15525. /**
  15526. * {@link NodeBuilder} is going to create instances of this class during the build process
  15527. * of nodes. They represent the final shader variables that are going to be generated
  15528. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  15529. * this purpose.
  15530. */
  15531. class NodeVar {
  15532. /**
  15533. * Constructs a new node variable.
  15534. *
  15535. * @param {String} name - The name of the variable.
  15536. * @param {String} type - The type of the variable.
  15537. */
  15538. constructor( name, type ) {
  15539. /**
  15540. * This flag can be used for type testing.
  15541. *
  15542. * @type {Boolean}
  15543. * @readonly
  15544. * @default true
  15545. */
  15546. this.isNodeVar = true;
  15547. /**
  15548. * The name of the variable.
  15549. *
  15550. * @type {String}
  15551. */
  15552. this.name = name;
  15553. /**
  15554. * The type of the variable.
  15555. *
  15556. * @type {String}
  15557. */
  15558. this.type = type;
  15559. }
  15560. }
  15561. /**
  15562. * {@link NodeBuilder} is going to create instances of this class during the build process
  15563. * of nodes. They represent the final shader varyings that are going to be generated
  15564. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  15565. * this purpose.
  15566. *
  15567. * @augments NodeVar
  15568. */
  15569. class NodeVarying extends NodeVar {
  15570. /**
  15571. * Constructs a new node varying.
  15572. *
  15573. * @param {String} name - The name of the varying.
  15574. * @param {String} type - The type of the varying.
  15575. */
  15576. constructor( name, type ) {
  15577. super( name, type );
  15578. /**
  15579. * Whether this varying requires interpolation or not. This property can be used
  15580. * to check if the varying can be optimized for a variable.
  15581. *
  15582. * @type {Boolean}
  15583. * @default false
  15584. */
  15585. this.needsInterpolation = false;
  15586. /**
  15587. * This flag can be used for type testing.
  15588. *
  15589. * @type {Boolean}
  15590. * @readonly
  15591. * @default true
  15592. */
  15593. this.isNodeVarying = true;
  15594. }
  15595. }
  15596. /**
  15597. * {@link NodeBuilder} is going to create instances of this class during the build process
  15598. * of nodes. They represent user-defined, native shader code portions that are going to be
  15599. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  15600. * for this purpose.
  15601. */
  15602. class NodeCode {
  15603. /**
  15604. * Constructs a new code node.
  15605. *
  15606. * @param {String} name - The name of the code.
  15607. * @param {String} type - The node type.
  15608. * @param {String} [code=''] - The native shader code.
  15609. */
  15610. constructor( name, type, code = '' ) {
  15611. /**
  15612. * The name of the code.
  15613. *
  15614. * @type {String}
  15615. */
  15616. this.name = name;
  15617. /**
  15618. * The node type.
  15619. *
  15620. * @type {String}
  15621. */
  15622. this.type = type;
  15623. /**
  15624. * The native shader code.
  15625. *
  15626. * @type {String}
  15627. * @default ''
  15628. */
  15629. this.code = code;
  15630. Object.defineProperty( this, 'isNodeCode', { value: true } );
  15631. }
  15632. }
  15633. let _id$5 = 0;
  15634. /**
  15635. * This utility class is used in {@link NodeBuilder} as an internal
  15636. * cache data structure for node data.
  15637. */
  15638. class NodeCache {
  15639. /**
  15640. * Constructs a new node cache.
  15641. *
  15642. * @param {NodeCache?} parent - A reference to a parent cache.
  15643. */
  15644. constructor( parent = null ) {
  15645. /**
  15646. * The id of the cache.
  15647. *
  15648. * @type {Number}
  15649. * @readonly
  15650. */
  15651. this.id = _id$5 ++;
  15652. /**
  15653. * A weak map for managing node data.
  15654. *
  15655. * @type {WeakMap}
  15656. */
  15657. this.nodesData = new WeakMap();
  15658. /**
  15659. * Reference to a parent node cache.
  15660. *
  15661. * @type {NodeCache?}
  15662. * @default null
  15663. */
  15664. this.parent = parent;
  15665. }
  15666. /**
  15667. * Returns the data for the given node.
  15668. *
  15669. * @param {Node} node - The node.
  15670. * @return {Object?} The data for the node.
  15671. */
  15672. getData( node ) {
  15673. let data = this.nodesData.get( node );
  15674. if ( data === undefined && this.parent !== null ) {
  15675. data = this.parent.getData( node );
  15676. }
  15677. return data;
  15678. }
  15679. /**
  15680. * Sets the data for a given node.
  15681. *
  15682. * @param {Node} node - The node.
  15683. * @param {Object} data - The data that should be cached.
  15684. */
  15685. setData( node, data ) {
  15686. this.nodesData.set( node, data );
  15687. }
  15688. }
  15689. /**
  15690. * {@link NodeBuilder} is going to create instances of this class during the build process
  15691. * of nodes. They represent the final shader struct data that are going to be generated
  15692. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  15693. * for this purpose.
  15694. */
  15695. class StructTypeNode extends Node {
  15696. static get type() {
  15697. return 'StructTypeNode';
  15698. }
  15699. /**
  15700. * Constructs a new struct type node.
  15701. *
  15702. * @param {String} name - The name of the struct.
  15703. * @param {Array<String>} types - An array of types.
  15704. */
  15705. constructor( name, types ) {
  15706. super();
  15707. /**
  15708. * The name of the struct.
  15709. *
  15710. * @type {String}
  15711. */
  15712. this.name = name;
  15713. /**
  15714. * An array of types.
  15715. *
  15716. * @type {Array<String>}
  15717. */
  15718. this.types = types;
  15719. /**
  15720. * This flag can be used for type testing.
  15721. *
  15722. * @type {Boolean}
  15723. * @readonly
  15724. * @default true
  15725. */
  15726. this.isStructTypeNode = true;
  15727. }
  15728. /**
  15729. * Returns the member types.
  15730. *
  15731. * @return {Array<String>} The types.
  15732. */
  15733. getMemberTypes() {
  15734. return this.types;
  15735. }
  15736. }
  15737. class Uniform {
  15738. constructor( name, value ) {
  15739. this.name = name;
  15740. this.value = value;
  15741. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  15742. this.itemSize = 0;
  15743. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  15744. }
  15745. setValue( value ) {
  15746. this.value = value;
  15747. }
  15748. getValue() {
  15749. return this.value;
  15750. }
  15751. }
  15752. class NumberUniform extends Uniform {
  15753. constructor( name, value = 0 ) {
  15754. super( name, value );
  15755. this.isNumberUniform = true;
  15756. this.boundary = 4;
  15757. this.itemSize = 1;
  15758. }
  15759. }
  15760. class Vector2Uniform extends Uniform {
  15761. constructor( name, value = new Vector2() ) {
  15762. super( name, value );
  15763. this.isVector2Uniform = true;
  15764. this.boundary = 8;
  15765. this.itemSize = 2;
  15766. }
  15767. }
  15768. class Vector3Uniform extends Uniform {
  15769. constructor( name, value = new Vector3() ) {
  15770. super( name, value );
  15771. this.isVector3Uniform = true;
  15772. this.boundary = 16;
  15773. this.itemSize = 3;
  15774. }
  15775. }
  15776. class Vector4Uniform extends Uniform {
  15777. constructor( name, value = new Vector4() ) {
  15778. super( name, value );
  15779. this.isVector4Uniform = true;
  15780. this.boundary = 16;
  15781. this.itemSize = 4;
  15782. }
  15783. }
  15784. class ColorUniform extends Uniform {
  15785. constructor( name, value = new Color() ) {
  15786. super( name, value );
  15787. this.isColorUniform = true;
  15788. this.boundary = 16;
  15789. this.itemSize = 3;
  15790. }
  15791. }
  15792. class Matrix3Uniform extends Uniform {
  15793. constructor( name, value = new Matrix3() ) {
  15794. super( name, value );
  15795. this.isMatrix3Uniform = true;
  15796. this.boundary = 48;
  15797. this.itemSize = 12;
  15798. }
  15799. }
  15800. class Matrix4Uniform extends Uniform {
  15801. constructor( name, value = new Matrix4() ) {
  15802. super( name, value );
  15803. this.isMatrix4Uniform = true;
  15804. this.boundary = 64;
  15805. this.itemSize = 16;
  15806. }
  15807. }
  15808. class NumberNodeUniform extends NumberUniform {
  15809. constructor( nodeUniform ) {
  15810. super( nodeUniform.name, nodeUniform.value );
  15811. this.nodeUniform = nodeUniform;
  15812. }
  15813. getValue() {
  15814. return this.nodeUniform.value;
  15815. }
  15816. getType() {
  15817. return this.nodeUniform.type;
  15818. }
  15819. }
  15820. class Vector2NodeUniform extends Vector2Uniform {
  15821. constructor( nodeUniform ) {
  15822. super( nodeUniform.name, nodeUniform.value );
  15823. this.nodeUniform = nodeUniform;
  15824. }
  15825. getValue() {
  15826. return this.nodeUniform.value;
  15827. }
  15828. getType() {
  15829. return this.nodeUniform.type;
  15830. }
  15831. }
  15832. class Vector3NodeUniform extends Vector3Uniform {
  15833. constructor( nodeUniform ) {
  15834. super( nodeUniform.name, nodeUniform.value );
  15835. this.nodeUniform = nodeUniform;
  15836. }
  15837. getValue() {
  15838. return this.nodeUniform.value;
  15839. }
  15840. getType() {
  15841. return this.nodeUniform.type;
  15842. }
  15843. }
  15844. class Vector4NodeUniform extends Vector4Uniform {
  15845. constructor( nodeUniform ) {
  15846. super( nodeUniform.name, nodeUniform.value );
  15847. this.nodeUniform = nodeUniform;
  15848. }
  15849. getValue() {
  15850. return this.nodeUniform.value;
  15851. }
  15852. getType() {
  15853. return this.nodeUniform.type;
  15854. }
  15855. }
  15856. class ColorNodeUniform extends ColorUniform {
  15857. constructor( nodeUniform ) {
  15858. super( nodeUniform.name, nodeUniform.value );
  15859. this.nodeUniform = nodeUniform;
  15860. }
  15861. getValue() {
  15862. return this.nodeUniform.value;
  15863. }
  15864. getType() {
  15865. return this.nodeUniform.type;
  15866. }
  15867. }
  15868. class Matrix3NodeUniform extends Matrix3Uniform {
  15869. constructor( nodeUniform ) {
  15870. super( nodeUniform.name, nodeUniform.value );
  15871. this.nodeUniform = nodeUniform;
  15872. }
  15873. getValue() {
  15874. return this.nodeUniform.value;
  15875. }
  15876. getType() {
  15877. return this.nodeUniform.type;
  15878. }
  15879. }
  15880. class Matrix4NodeUniform extends Matrix4Uniform {
  15881. constructor( nodeUniform ) {
  15882. super( nodeUniform.name, nodeUniform.value );
  15883. this.nodeUniform = nodeUniform;
  15884. }
  15885. getValue() {
  15886. return this.nodeUniform.value;
  15887. }
  15888. getType() {
  15889. return this.nodeUniform.type;
  15890. }
  15891. }
  15892. const LOD_MIN = 4;
  15893. // The standard deviations (radians) associated with the extra mips. These are
  15894. // chosen to approximate a Trowbridge-Reitz distribution function times the
  15895. // geometric shadowing function. These sigma values squared must match the
  15896. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  15897. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  15898. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  15899. // samples and exit early, but not recompile the shader.
  15900. const MAX_SAMPLES = 20;
  15901. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  15902. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  15903. const _clearColor = /*@__PURE__*/ new Color();
  15904. let _oldTarget = null;
  15905. let _oldActiveCubeFace = 0;
  15906. let _oldActiveMipmapLevel = 0;
  15907. // Golden Ratio
  15908. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  15909. const INV_PHI = 1 / PHI;
  15910. // Vertices of a dodecahedron (except the opposites, which represent the
  15911. // same axis), used as axis directions evenly spread on a sphere.
  15912. const _axisDirections = [
  15913. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  15914. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  15915. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  15916. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  15917. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  15918. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  15919. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  15920. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  15921. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  15922. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  15923. ];
  15924. //
  15925. // WebGPU Face indices
  15926. const _faceLib = [
  15927. 3, 1, 5,
  15928. 0, 4, 2
  15929. ];
  15930. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  15931. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  15932. /**
  15933. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  15934. * (PMREM) from a cubeMap environment texture. This allows different levels of
  15935. * blur to be quickly accessed based on material roughness. It is packed into a
  15936. * special CubeUV format that allows us to perform custom interpolation so that
  15937. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  15938. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  15939. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  15940. * higher roughness levels. In this way we maintain resolution to smoothly
  15941. * interpolate diffuse lighting while limiting sampling computation.
  15942. *
  15943. * Paper: Fast, Accurate Image-Based Lighting
  15944. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  15945. */
  15946. class PMREMGenerator {
  15947. constructor( renderer ) {
  15948. this._renderer = renderer;
  15949. this._pingPongRenderTarget = null;
  15950. this._lodMax = 0;
  15951. this._cubeSize = 0;
  15952. this._lodPlanes = [];
  15953. this._sizeLods = [];
  15954. this._sigmas = [];
  15955. this._lodMeshes = [];
  15956. this._blurMaterial = null;
  15957. this._cubemapMaterial = null;
  15958. this._equirectMaterial = null;
  15959. this._backgroundBox = null;
  15960. }
  15961. get _hasInitialized() {
  15962. return this._renderer.hasInitialized();
  15963. }
  15964. /**
  15965. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15966. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15967. * in radians to be applied to the scene before PMREM generation. Optional near
  15968. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  15969. * is placed at the origin).
  15970. */
  15971. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  15972. this._setSize( 256 );
  15973. if ( this._hasInitialized === false ) {
  15974. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  15975. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15976. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  15977. return cubeUVRenderTarget;
  15978. }
  15979. _oldTarget = this._renderer.getRenderTarget();
  15980. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15981. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15982. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15983. cubeUVRenderTarget.depthBuffer = true;
  15984. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  15985. if ( sigma > 0 ) {
  15986. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  15987. }
  15988. this._applyPMREM( cubeUVRenderTarget );
  15989. this._cleanup( cubeUVRenderTarget );
  15990. return cubeUVRenderTarget;
  15991. }
  15992. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  15993. if ( this._hasInitialized === false ) await this._renderer.init();
  15994. return this.fromScene( scene, sigma, near, far, renderTarget );
  15995. }
  15996. /**
  15997. * Generates a PMREM from an equirectangular texture, which can be either LDR
  15998. * or HDR. The ideal input image size is 1k (1024 x 512),
  15999. * as this matches best with the 256 x 256 cubemap output.
  16000. */
  16001. fromEquirectangular( equirectangular, renderTarget = null ) {
  16002. if ( this._hasInitialized === false ) {
  16003. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16004. this._setSizeFromTexture( equirectangular );
  16005. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  16006. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16007. return cubeUVRenderTarget;
  16008. }
  16009. return this._fromTexture( equirectangular, renderTarget );
  16010. }
  16011. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16012. if ( this._hasInitialized === false ) await this._renderer.init();
  16013. return this._fromTexture( equirectangular, renderTarget );
  16014. }
  16015. /**
  16016. * Generates a PMREM from an cubemap texture, which can be either LDR
  16017. * or HDR. The ideal input cube size is 256 x 256,
  16018. * as this matches best with the 256 x 256 cubemap output.
  16019. */
  16020. fromCubemap( cubemap, renderTarget = null ) {
  16021. if ( this._hasInitialized === false ) {
  16022. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16023. this._setSizeFromTexture( cubemap );
  16024. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  16025. this.fromCubemapAsync( cubemap, renderTarget );
  16026. return cubeUVRenderTarget;
  16027. }
  16028. return this._fromTexture( cubemap, renderTarget );
  16029. }
  16030. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16031. if ( this._hasInitialized === false ) await this._renderer.init();
  16032. return this._fromTexture( cubemap, renderTarget );
  16033. }
  16034. /**
  16035. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16036. * your texture's network fetch for increased concurrency.
  16037. */
  16038. async compileCubemapShader() {
  16039. if ( this._cubemapMaterial === null ) {
  16040. this._cubemapMaterial = _getCubemapMaterial();
  16041. await this._compileMaterial( this._cubemapMaterial );
  16042. }
  16043. }
  16044. /**
  16045. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16046. * your texture's network fetch for increased concurrency.
  16047. */
  16048. async compileEquirectangularShader() {
  16049. if ( this._equirectMaterial === null ) {
  16050. this._equirectMaterial = _getEquirectMaterial();
  16051. await this._compileMaterial( this._equirectMaterial );
  16052. }
  16053. }
  16054. /**
  16055. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16056. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16057. * one of them will cause any others to also become unusable.
  16058. */
  16059. dispose() {
  16060. this._dispose();
  16061. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16062. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16063. if ( this._backgroundBox !== null ) {
  16064. this._backgroundBox.geometry.dispose();
  16065. this._backgroundBox.material.dispose();
  16066. }
  16067. }
  16068. // private interface
  16069. _setSizeFromTexture( texture ) {
  16070. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16071. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16072. } else { // Equirectangular
  16073. this._setSize( texture.image.width / 4 );
  16074. }
  16075. }
  16076. _setSize( cubeSize ) {
  16077. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16078. this._cubeSize = Math.pow( 2, this._lodMax );
  16079. }
  16080. _dispose() {
  16081. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16082. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16083. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16084. this._lodPlanes[ i ].dispose();
  16085. }
  16086. }
  16087. _cleanup( outputTarget ) {
  16088. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16089. outputTarget.scissorTest = false;
  16090. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16091. }
  16092. _fromTexture( texture, renderTarget ) {
  16093. this._setSizeFromTexture( texture );
  16094. _oldTarget = this._renderer.getRenderTarget();
  16095. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16096. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16097. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  16098. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16099. this._applyPMREM( cubeUVRenderTarget );
  16100. this._cleanup( cubeUVRenderTarget );
  16101. return cubeUVRenderTarget;
  16102. }
  16103. _allocateTargets() {
  16104. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16105. const height = 4 * this._cubeSize;
  16106. const params = {
  16107. magFilter: LinearFilter,
  16108. minFilter: LinearFilter,
  16109. generateMipmaps: false,
  16110. type: HalfFloatType,
  16111. format: RGBAFormat,
  16112. colorSpace: LinearSRGBColorSpace,
  16113. //depthBuffer: false
  16114. };
  16115. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  16116. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  16117. if ( this._pingPongRenderTarget !== null ) {
  16118. this._dispose();
  16119. }
  16120. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  16121. const { _lodMax } = this;
  16122. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16123. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  16124. }
  16125. return cubeUVRenderTarget;
  16126. }
  16127. async _compileMaterial( material ) {
  16128. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16129. await this._renderer.compile( tmpMesh, _flatCamera );
  16130. }
  16131. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  16132. const cubeCamera = _cubeCamera;
  16133. cubeCamera.near = near;
  16134. cubeCamera.far = far;
  16135. // px, py, pz, nx, ny, nz
  16136. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  16137. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  16138. const renderer = this._renderer;
  16139. const originalAutoClear = renderer.autoClear;
  16140. renderer.getClearColor( _clearColor );
  16141. renderer.autoClear = false;
  16142. let backgroundBox = this._backgroundBox;
  16143. if ( backgroundBox === null ) {
  16144. const backgroundMaterial = new MeshBasicMaterial( {
  16145. name: 'PMREM.Background',
  16146. side: BackSide,
  16147. depthWrite: false,
  16148. depthTest: false
  16149. } );
  16150. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16151. }
  16152. let useSolidColor = false;
  16153. const background = scene.background;
  16154. if ( background ) {
  16155. if ( background.isColor ) {
  16156. backgroundBox.material.color.copy( background );
  16157. scene.background = null;
  16158. useSolidColor = true;
  16159. }
  16160. } else {
  16161. backgroundBox.material.color.copy( _clearColor );
  16162. useSolidColor = true;
  16163. }
  16164. renderer.setRenderTarget( cubeUVRenderTarget );
  16165. renderer.clear();
  16166. if ( useSolidColor ) {
  16167. renderer.render( backgroundBox, cubeCamera );
  16168. }
  16169. for ( let i = 0; i < 6; i ++ ) {
  16170. const col = i % 3;
  16171. if ( col === 0 ) {
  16172. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16173. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  16174. } else if ( col === 1 ) {
  16175. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16176. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  16177. } else {
  16178. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16179. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  16180. }
  16181. const size = this._cubeSize;
  16182. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16183. renderer.render( scene, cubeCamera );
  16184. }
  16185. renderer.autoClear = originalAutoClear;
  16186. scene.background = background;
  16187. }
  16188. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16189. const renderer = this._renderer;
  16190. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16191. if ( isCubeTexture ) {
  16192. if ( this._cubemapMaterial === null ) {
  16193. this._cubemapMaterial = _getCubemapMaterial( texture );
  16194. }
  16195. } else {
  16196. if ( this._equirectMaterial === null ) {
  16197. this._equirectMaterial = _getEquirectMaterial( texture );
  16198. }
  16199. }
  16200. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16201. material.fragmentNode.value = texture;
  16202. const mesh = this._lodMeshes[ 0 ];
  16203. mesh.material = material;
  16204. const size = this._cubeSize;
  16205. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16206. renderer.setRenderTarget( cubeUVRenderTarget );
  16207. renderer.render( mesh, _flatCamera );
  16208. }
  16209. _applyPMREM( cubeUVRenderTarget ) {
  16210. const renderer = this._renderer;
  16211. const autoClear = renderer.autoClear;
  16212. renderer.autoClear = false;
  16213. const n = this._lodPlanes.length;
  16214. for ( let i = 1; i < n; i ++ ) {
  16215. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16216. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16217. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16218. }
  16219. renderer.autoClear = autoClear;
  16220. }
  16221. /**
  16222. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16223. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16224. * the blur latitudinally (around the poles), and then longitudinally (towards
  16225. * the poles) to approximate the orthogonally-separable blur. It is least
  16226. * accurate at the poles, but still does a decent job.
  16227. */
  16228. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16229. const pingPongRenderTarget = this._pingPongRenderTarget;
  16230. this._halfBlur(
  16231. cubeUVRenderTarget,
  16232. pingPongRenderTarget,
  16233. lodIn,
  16234. lodOut,
  16235. sigma,
  16236. 'latitudinal',
  16237. poleAxis );
  16238. this._halfBlur(
  16239. pingPongRenderTarget,
  16240. cubeUVRenderTarget,
  16241. lodOut,
  16242. lodOut,
  16243. sigma,
  16244. 'longitudinal',
  16245. poleAxis );
  16246. }
  16247. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16248. const renderer = this._renderer;
  16249. const blurMaterial = this._blurMaterial;
  16250. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16251. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16252. }
  16253. // Number of standard deviations at which to cut off the discrete approximation.
  16254. const STANDARD_DEVIATIONS = 3;
  16255. const blurMesh = this._lodMeshes[ lodOut ];
  16256. blurMesh.material = blurMaterial;
  16257. const blurUniforms = blurMaterial.uniforms;
  16258. const pixels = this._sizeLods[ lodIn ] - 1;
  16259. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16260. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16261. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16262. if ( samples > MAX_SAMPLES ) {
  16263. console.warn( `sigmaRadians, ${
  16264. sigmaRadians}, is too large and will clip, as it requested ${
  16265. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16266. }
  16267. const weights = [];
  16268. let sum = 0;
  16269. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16270. const x = i / sigmaPixels;
  16271. const weight = Math.exp( - x * x / 2 );
  16272. weights.push( weight );
  16273. if ( i === 0 ) {
  16274. sum += weight;
  16275. } else if ( i < samples ) {
  16276. sum += 2 * weight;
  16277. }
  16278. }
  16279. for ( let i = 0; i < weights.length; i ++ ) {
  16280. weights[ i ] = weights[ i ] / sum;
  16281. }
  16282. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16283. blurUniforms.envMap.value = targetIn.texture;
  16284. blurUniforms.samples.value = samples;
  16285. blurUniforms.weights.array = weights;
  16286. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16287. if ( poleAxis ) {
  16288. blurUniforms.poleAxis.value = poleAxis;
  16289. }
  16290. const { _lodMax } = this;
  16291. blurUniforms.dTheta.value = radiansPerPixel;
  16292. blurUniforms.mipInt.value = _lodMax - lodIn;
  16293. const outputSize = this._sizeLods[ lodOut ];
  16294. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16295. const y = 4 * ( this._cubeSize - outputSize );
  16296. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16297. renderer.setRenderTarget( targetOut );
  16298. renderer.render( blurMesh, _flatCamera );
  16299. }
  16300. }
  16301. function _createPlanes( lodMax ) {
  16302. const lodPlanes = [];
  16303. const sizeLods = [];
  16304. const sigmas = [];
  16305. const lodMeshes = [];
  16306. let lod = lodMax;
  16307. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16308. for ( let i = 0; i < totalLods; i ++ ) {
  16309. const sizeLod = Math.pow( 2, lod );
  16310. sizeLods.push( sizeLod );
  16311. let sigma = 1.0 / sizeLod;
  16312. if ( i > lodMax - LOD_MIN ) {
  16313. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16314. } else if ( i === 0 ) {
  16315. sigma = 0;
  16316. }
  16317. sigmas.push( sigma );
  16318. const texelSize = 1.0 / ( sizeLod - 2 );
  16319. const min = - texelSize;
  16320. const max = 1 + texelSize;
  16321. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16322. const cubeFaces = 6;
  16323. const vertices = 6;
  16324. const positionSize = 3;
  16325. const uvSize = 2;
  16326. const faceIndexSize = 1;
  16327. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16328. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16329. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16330. for ( let face = 0; face < cubeFaces; face ++ ) {
  16331. const x = ( face % 3 ) * 2 / 3 - 1;
  16332. const y = face > 2 ? 0 : - 1;
  16333. const coordinates = [
  16334. x, y, 0,
  16335. x + 2 / 3, y, 0,
  16336. x + 2 / 3, y + 1, 0,
  16337. x, y, 0,
  16338. x + 2 / 3, y + 1, 0,
  16339. x, y + 1, 0
  16340. ];
  16341. const faceIdx = _faceLib[ face ];
  16342. position.set( coordinates, positionSize * vertices * faceIdx );
  16343. uv.set( uv1, uvSize * vertices * faceIdx );
  16344. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16345. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16346. }
  16347. const planes = new BufferGeometry();
  16348. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16349. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16350. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  16351. lodPlanes.push( planes );
  16352. lodMeshes.push( new Mesh( planes, null ) );
  16353. if ( lod > LOD_MIN ) {
  16354. lod --;
  16355. }
  16356. }
  16357. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  16358. }
  16359. function _createRenderTarget( width, height, params ) {
  16360. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  16361. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  16362. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  16363. cubeUVRenderTarget.texture.isPMREMTexture = true;
  16364. cubeUVRenderTarget.scissorTest = true;
  16365. return cubeUVRenderTarget;
  16366. }
  16367. function _setViewport( target, x, y, width, height ) {
  16368. target.viewport.set( x, y, width, height );
  16369. target.scissor.set( x, y, width, height );
  16370. }
  16371. function _getMaterial( type ) {
  16372. const material = new NodeMaterial();
  16373. material.depthTest = false;
  16374. material.depthWrite = false;
  16375. material.blending = NoBlending;
  16376. material.name = `PMREM_${ type }`;
  16377. return material;
  16378. }
  16379. function _getBlurShader( lodMax, width, height ) {
  16380. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  16381. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  16382. const dTheta = uniform( 0 );
  16383. const n = float( MAX_SAMPLES );
  16384. const latitudinal = uniform( 0 ); // false, bool
  16385. const samples = uniform( 1 ); // int
  16386. const envMap = texture( null );
  16387. const mipInt = uniform( 0 ); // int
  16388. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  16389. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  16390. const CUBEUV_MAX_MIP = float( lodMax );
  16391. const materialUniforms = {
  16392. n,
  16393. latitudinal,
  16394. weights,
  16395. poleAxis,
  16396. outputDirection,
  16397. dTheta,
  16398. samples,
  16399. envMap,
  16400. mipInt,
  16401. CUBEUV_TEXEL_WIDTH,
  16402. CUBEUV_TEXEL_HEIGHT,
  16403. CUBEUV_MAX_MIP
  16404. };
  16405. const material = _getMaterial( 'blur' );
  16406. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  16407. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  16408. return material;
  16409. }
  16410. function _getCubemapMaterial( envTexture ) {
  16411. const material = _getMaterial( 'cubemap' );
  16412. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  16413. return material;
  16414. }
  16415. function _getEquirectMaterial( envTexture ) {
  16416. const material = _getMaterial( 'equirect' );
  16417. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  16418. return material;
  16419. }
  16420. const rendererCache = new WeakMap();
  16421. const typeFromArray = new Map( [
  16422. [ Int8Array, 'int' ],
  16423. [ Int16Array, 'int' ],
  16424. [ Int32Array, 'int' ],
  16425. [ Uint8Array, 'uint' ],
  16426. [ Uint16Array, 'uint' ],
  16427. [ Uint32Array, 'uint' ],
  16428. [ Float32Array, 'float' ]
  16429. ] );
  16430. const toFloat = ( value ) => {
  16431. if ( /e/g.test( value ) ) {
  16432. return String( value ).replace( /\+/g, '' );
  16433. } else {
  16434. value = Number( value );
  16435. return value + ( value % 1 ? '' : '.0' );
  16436. }
  16437. };
  16438. /**
  16439. * Base class for builders which generate a shader program based
  16440. * on a 3D object and its node material definition.
  16441. */
  16442. class NodeBuilder {
  16443. /**
  16444. * Constructs a new node builder.
  16445. *
  16446. * @param {Object3D} object - The 3D object.
  16447. * @param {Renderer} renderer - The current renderer.
  16448. * @param {NodeParser} parser - A reference to a node parser.
  16449. */
  16450. constructor( object, renderer, parser ) {
  16451. /**
  16452. * The 3D object.
  16453. *
  16454. * @type {Object3D}
  16455. */
  16456. this.object = object;
  16457. /**
  16458. * The material of the 3D object.
  16459. *
  16460. * @type {Material?}
  16461. */
  16462. this.material = ( object && object.material ) || null;
  16463. /**
  16464. * The geometry of the 3D object.
  16465. *
  16466. * @type {BufferGeometry?}
  16467. */
  16468. this.geometry = ( object && object.geometry ) || null;
  16469. /**
  16470. * The current renderer.
  16471. *
  16472. * @type {Renderer}
  16473. */
  16474. this.renderer = renderer;
  16475. /**
  16476. * A reference to a node parser.
  16477. *
  16478. * @type {NodeParser}
  16479. */
  16480. this.parser = parser;
  16481. /**
  16482. * The scene the 3D object belongs to.
  16483. *
  16484. * @type {Scene?}
  16485. */
  16486. this.scene = null;
  16487. /**
  16488. * The camera the 3D object is rendered with.
  16489. *
  16490. * @type {Camera?}
  16491. */
  16492. this.camera = null;
  16493. this.nodes = [];
  16494. this.sequentialNodes = [];
  16495. this.updateNodes = [];
  16496. this.updateBeforeNodes = [];
  16497. this.updateAfterNodes = [];
  16498. this.hashNodes = {};
  16499. this.monitor = null;
  16500. this.lightsNode = null;
  16501. this.environmentNode = null;
  16502. this.fogNode = null;
  16503. this.clippingContext = null;
  16504. this.vertexShader = null;
  16505. this.fragmentShader = null;
  16506. this.computeShader = null;
  16507. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  16508. this.flowCode = { vertex: '', fragment: '', compute: '' };
  16509. /**
  16510. * This dictionary holds the node uniforms of the builder.
  16511. * The uniforms are maintained in an array for each shader stage.
  16512. *
  16513. * @type {Object}
  16514. */
  16515. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  16516. /**
  16517. * This dictionary holds the output structs of the builder.
  16518. * The structs are maintained in an array for each shader stage.
  16519. *
  16520. * @type {Object}
  16521. */
  16522. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  16523. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  16524. this.bindingsIndexes = {};
  16525. this.bindGroups = null;
  16526. /**
  16527. * This array holds the node attributes of this builder
  16528. * created via {@link AttributeNode}.
  16529. *
  16530. * @type {Array<NodeAttribute>}
  16531. */
  16532. this.attributes = [];
  16533. /**
  16534. * This array holds the node attributes of this builder
  16535. * created via {@link BufferAttributeNode}.
  16536. *
  16537. * @type {Array<NodeAttribute>}
  16538. */
  16539. this.bufferAttributes = [];
  16540. /**
  16541. * This array holds the node varyings of this builder.
  16542. *
  16543. * @type {Array<NodeVarying>}
  16544. */
  16545. this.varyings = [];
  16546. /**
  16547. * This dictionary holds the (native) node codes of this builder.
  16548. * The codes are maintained in an array for each shader stage.
  16549. *
  16550. * @type {Object<String,Array<NodeCode>>}
  16551. */
  16552. this.codes = {};
  16553. /**
  16554. * This dictionary holds the node variables of this builder.
  16555. * The variables are maintained in an array for each shader stage.
  16556. *
  16557. * @type {Object<String,Array<NodeVar>>}
  16558. */
  16559. this.vars = {};
  16560. this.flow = { code: '' };
  16561. this.chaining = [];
  16562. this.stack = stack();
  16563. this.stacks = [];
  16564. this.tab = '\t';
  16565. this.currentFunctionNode = null;
  16566. this.context = {
  16567. material: this.material
  16568. };
  16569. this.cache = new NodeCache();
  16570. this.globalCache = this.cache;
  16571. this.flowsData = new WeakMap();
  16572. /**
  16573. * The current shader stage.
  16574. *
  16575. * @type {('vertex'|'fragment'|'compute')?}
  16576. */
  16577. this.shaderStage = null;
  16578. /**
  16579. * The current build stage.
  16580. *
  16581. * @type {('setup'|'analyze'|'generate')?}
  16582. */
  16583. this.buildStage = null;
  16584. this.useComparisonMethod = false;
  16585. }
  16586. /**
  16587. * Returns the bind groups of the current renderer.
  16588. *
  16589. * @return {ChainMap} The cache.
  16590. */
  16591. getBindGroupsCache() {
  16592. let bindGroupsCache = rendererCache.get( this.renderer );
  16593. if ( bindGroupsCache === undefined ) {
  16594. bindGroupsCache = new ChainMap();
  16595. rendererCache.set( this.renderer, bindGroupsCache );
  16596. }
  16597. return bindGroupsCache;
  16598. }
  16599. /**
  16600. * Factory method for creating an instance of {@link RenderTarget} with the given
  16601. * dimensions and options.
  16602. *
  16603. * @param {Number} width - The width of the render target.
  16604. * @param {Number} height - The height of the render target.
  16605. * @param {Object} options - The options of the render target.
  16606. * @return {RenderTarget} The render target.
  16607. */
  16608. createRenderTarget( width, height, options ) {
  16609. return new RenderTarget( width, height, options );
  16610. }
  16611. /**
  16612. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  16613. * dimensions and options.
  16614. *
  16615. * @param {Number} size - The size of the cube render target.
  16616. * @param {Object} options - The options of the cube render target.
  16617. * @return {CubeRenderTarget} The cube render target.
  16618. */
  16619. createCubeRenderTarget( size, options ) {
  16620. return new CubeRenderTarget( size, options );
  16621. }
  16622. /**
  16623. * Factory method for creating an instance of {@link PMREMGenerator}.
  16624. *
  16625. * @return {PMREMGenerator} The PMREM generator.
  16626. */
  16627. createPMREMGenerator() {
  16628. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  16629. return new PMREMGenerator( this.renderer );
  16630. }
  16631. /**
  16632. * Whether the given node is included in the internal array of nodes or not.
  16633. *
  16634. * @param {Node} node - The node to test.
  16635. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  16636. */
  16637. includes( node ) {
  16638. return this.nodes.includes( node );
  16639. }
  16640. _getBindGroup( groupName, bindings ) {
  16641. const bindGroupsCache = this.getBindGroupsCache();
  16642. //
  16643. const bindingsArray = [];
  16644. let sharedGroup = true;
  16645. for ( const binding of bindings ) {
  16646. bindingsArray.push( binding );
  16647. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  16648. }
  16649. //
  16650. let bindGroup;
  16651. if ( sharedGroup ) {
  16652. bindGroup = bindGroupsCache.get( bindingsArray );
  16653. if ( bindGroup === undefined ) {
  16654. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  16655. bindGroupsCache.set( bindingsArray, bindGroup );
  16656. }
  16657. } else {
  16658. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  16659. }
  16660. return bindGroup;
  16661. }
  16662. getBindGroupArray( groupName, shaderStage ) {
  16663. const bindings = this.bindings[ shaderStage ];
  16664. let bindGroup = bindings[ groupName ];
  16665. if ( bindGroup === undefined ) {
  16666. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  16667. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  16668. }
  16669. bindings[ groupName ] = bindGroup = [];
  16670. }
  16671. return bindGroup;
  16672. }
  16673. getBindings() {
  16674. let bindingsGroups = this.bindGroups;
  16675. if ( bindingsGroups === null ) {
  16676. const groups = {};
  16677. const bindings = this.bindings;
  16678. for ( const shaderStage of shaderStages ) {
  16679. for ( const groupName in bindings[ shaderStage ] ) {
  16680. const uniforms = bindings[ shaderStage ][ groupName ];
  16681. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  16682. groupUniforms.push( ...uniforms );
  16683. }
  16684. }
  16685. bindingsGroups = [];
  16686. for ( const groupName in groups ) {
  16687. const group = groups[ groupName ];
  16688. const bindingsGroup = this._getBindGroup( groupName, group );
  16689. bindingsGroups.push( bindingsGroup );
  16690. }
  16691. this.bindGroups = bindingsGroups;
  16692. }
  16693. return bindingsGroups;
  16694. }
  16695. sortBindingGroups() {
  16696. const bindingsGroups = this.getBindings();
  16697. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  16698. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  16699. const bindingGroup = bindingsGroups[ i ];
  16700. this.bindingsIndexes[ bindingGroup.name ].group = i;
  16701. bindingGroup.index = i;
  16702. }
  16703. }
  16704. setHashNode( node, hash ) {
  16705. this.hashNodes[ hash ] = node;
  16706. }
  16707. addNode( node ) {
  16708. if ( this.nodes.includes( node ) === false ) {
  16709. this.nodes.push( node );
  16710. this.setHashNode( node, node.getHash( this ) );
  16711. }
  16712. }
  16713. addSequentialNode( node ) {
  16714. if ( this.sequentialNodes.includes( node ) === false ) {
  16715. this.sequentialNodes.push( node );
  16716. }
  16717. }
  16718. buildUpdateNodes() {
  16719. for ( const node of this.nodes ) {
  16720. const updateType = node.getUpdateType();
  16721. if ( updateType !== NodeUpdateType.NONE ) {
  16722. this.updateNodes.push( node.getSelf() );
  16723. }
  16724. }
  16725. for ( const node of this.sequentialNodes ) {
  16726. const updateBeforeType = node.getUpdateBeforeType();
  16727. const updateAfterType = node.getUpdateAfterType();
  16728. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  16729. this.updateBeforeNodes.push( node.getSelf() );
  16730. }
  16731. if ( updateAfterType !== NodeUpdateType.NONE ) {
  16732. this.updateAfterNodes.push( node.getSelf() );
  16733. }
  16734. }
  16735. }
  16736. get currentNode() {
  16737. return this.chaining[ this.chaining.length - 1 ];
  16738. }
  16739. isFilteredTexture( texture ) {
  16740. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  16741. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  16742. }
  16743. addChain( node ) {
  16744. /*
  16745. if ( this.chaining.indexOf( node ) !== - 1 ) {
  16746. console.warn( 'Recursive node: ', node );
  16747. }
  16748. */
  16749. this.chaining.push( node );
  16750. }
  16751. removeChain( node ) {
  16752. const lastChain = this.chaining.pop();
  16753. if ( lastChain !== node ) {
  16754. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  16755. }
  16756. }
  16757. getMethod( method ) {
  16758. return method;
  16759. }
  16760. getNodeFromHash( hash ) {
  16761. return this.hashNodes[ hash ];
  16762. }
  16763. addFlow( shaderStage, node ) {
  16764. this.flowNodes[ shaderStage ].push( node );
  16765. return node;
  16766. }
  16767. setContext( context ) {
  16768. this.context = context;
  16769. }
  16770. getContext() {
  16771. return this.context;
  16772. }
  16773. getSharedContext() {
  16774. ({ ...this.context });
  16775. return this.context;
  16776. }
  16777. setCache( cache ) {
  16778. this.cache = cache;
  16779. }
  16780. getCache() {
  16781. return this.cache;
  16782. }
  16783. getCacheFromNode( node, parent = true ) {
  16784. const data = this.getDataFromNode( node );
  16785. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  16786. return data.cache;
  16787. }
  16788. isAvailable( /*name*/ ) {
  16789. return false;
  16790. }
  16791. getVertexIndex() {
  16792. console.warn( 'Abstract function.' );
  16793. }
  16794. getInstanceIndex() {
  16795. console.warn( 'Abstract function.' );
  16796. }
  16797. getDrawIndex() {
  16798. console.warn( 'Abstract function.' );
  16799. }
  16800. getFrontFacing() {
  16801. console.warn( 'Abstract function.' );
  16802. }
  16803. getFragCoord() {
  16804. console.warn( 'Abstract function.' );
  16805. }
  16806. isFlipY() {
  16807. return false;
  16808. }
  16809. increaseUsage( node ) {
  16810. const nodeData = this.getDataFromNode( node );
  16811. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  16812. return nodeData.usageCount;
  16813. }
  16814. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  16815. console.warn( 'Abstract function.' );
  16816. }
  16817. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  16818. console.warn( 'Abstract function.' );
  16819. }
  16820. generateConst( type, value = null ) {
  16821. if ( value === null ) {
  16822. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  16823. else if ( type === 'bool' ) value = false;
  16824. else if ( type === 'color' ) value = new Color();
  16825. else if ( type === 'vec2' ) value = new Vector2();
  16826. else if ( type === 'vec3' ) value = new Vector3();
  16827. else if ( type === 'vec4' ) value = new Vector4();
  16828. }
  16829. if ( type === 'float' ) return toFloat( value );
  16830. if ( type === 'int' ) return `${ Math.round( value ) }`;
  16831. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  16832. if ( type === 'bool' ) return value ? 'true' : 'false';
  16833. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  16834. const typeLength = this.getTypeLength( type );
  16835. const componentType = this.getComponentType( type );
  16836. const generateConst = value => this.generateConst( componentType, value );
  16837. if ( typeLength === 2 ) {
  16838. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  16839. } else if ( typeLength === 3 ) {
  16840. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  16841. } else if ( typeLength === 4 ) {
  16842. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  16843. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  16844. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  16845. } else if ( typeLength > 4 ) {
  16846. return `${ this.getType( type ) }()`;
  16847. }
  16848. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  16849. }
  16850. /**
  16851. * It might be necessary to convert certain data types to different ones
  16852. * so this method can be used to hide the conversion.
  16853. *
  16854. * @param {String} type - The type.
  16855. * @return {String} The updated type.
  16856. */
  16857. getType( type ) {
  16858. if ( type === 'color' ) return 'vec3';
  16859. return type;
  16860. }
  16861. /**
  16862. * Whether the given attribute name is defined in the geometry or not.
  16863. *
  16864. * @param {String} name - The attribute name.
  16865. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  16866. */
  16867. hasGeometryAttribute( name ) {
  16868. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  16869. }
  16870. /**
  16871. * Returns a node attribute for the given name and type.
  16872. *
  16873. * @param {String} name - The attribute's name.
  16874. * @param {String} type - The attribute's type.
  16875. * @return {NodeAttribute} The node attribute.
  16876. */
  16877. getAttribute( name, type ) {
  16878. const attributes = this.attributes;
  16879. // find attribute
  16880. for ( const attribute of attributes ) {
  16881. if ( attribute.name === name ) {
  16882. return attribute;
  16883. }
  16884. }
  16885. // create a new if no exist
  16886. const attribute = new NodeAttribute( name, type );
  16887. attributes.push( attribute );
  16888. return attribute;
  16889. }
  16890. /**
  16891. * Returns for the given node and shader stage the property name for the shader.
  16892. *
  16893. * @param {Node} node - The node.
  16894. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  16895. * @return {String} The property name.
  16896. */
  16897. getPropertyName( node/*, shaderStage*/ ) {
  16898. return node.name;
  16899. }
  16900. /**
  16901. * Whether the given type is a vector type or not.
  16902. *
  16903. * @param {String} type - The type to check.
  16904. * @return {Boolean} Whether the given type is a vector type or not.
  16905. */
  16906. isVector( type ) {
  16907. return /vec\d/.test( type );
  16908. }
  16909. /**
  16910. * Whether the given type is a matrix type or not.
  16911. *
  16912. * @param {String} type - The type to check.
  16913. * @return {Boolean} Whether the given type is a matrix type or not.
  16914. */
  16915. isMatrix( type ) {
  16916. return /mat\d/.test( type );
  16917. }
  16918. /**
  16919. * Whether the given type is a reference type or not.
  16920. *
  16921. * @param {String} type - The type to check.
  16922. * @return {Boolean} Whether the given type is a reference type or not.
  16923. */
  16924. isReference( type ) {
  16925. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  16926. }
  16927. /**
  16928. * Whether the given texture needs a conversion to working color space.
  16929. *
  16930. * @abstract
  16931. * @param {Texture} texture - The texture to check.
  16932. * @return {Boolean} Whether a color space conversion is required or not.
  16933. */
  16934. needsToWorkingColorSpace( /*texture*/ ) {
  16935. return false;
  16936. }
  16937. /**
  16938. * Returns the component type of a given texutre.
  16939. *
  16940. * @param {Texture} texture - The texture.
  16941. * @return {String} The component type.
  16942. */
  16943. getComponentTypeFromTexture( texture ) {
  16944. const type = texture.type;
  16945. if ( texture.isDataTexture ) {
  16946. if ( type === IntType ) return 'int';
  16947. if ( type === UnsignedIntType ) return 'uint';
  16948. }
  16949. return 'float';
  16950. }
  16951. /**
  16952. * Returns the element type for a given type.
  16953. *
  16954. * @param {String} type - The type.
  16955. * @return {String} The element type.
  16956. */
  16957. getElementType( type ) {
  16958. if ( type === 'mat2' ) return 'vec2';
  16959. if ( type === 'mat3' ) return 'vec3';
  16960. if ( type === 'mat4' ) return 'vec4';
  16961. return this.getComponentType( type );
  16962. }
  16963. /**
  16964. * Returns the component type for a given type.
  16965. *
  16966. * @param {String} type - The type.
  16967. * @return {String} The component type.
  16968. */
  16969. getComponentType( type ) {
  16970. type = this.getVectorType( type );
  16971. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  16972. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  16973. if ( componentType === null ) return null;
  16974. if ( componentType[ 1 ] === 'b' ) return 'bool';
  16975. if ( componentType[ 1 ] === 'i' ) return 'int';
  16976. if ( componentType[ 1 ] === 'u' ) return 'uint';
  16977. return 'float';
  16978. }
  16979. /**
  16980. * Returns the vector type for a given type.
  16981. *
  16982. * @param {String} type - The type.
  16983. * @return {String} The vector type.
  16984. */
  16985. getVectorType( type ) {
  16986. if ( type === 'color' ) return 'vec3';
  16987. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  16988. return type;
  16989. }
  16990. /**
  16991. * Returns the data type for the given the length and component type.
  16992. *
  16993. * @param {Number} length - The length.
  16994. * @param {String} [componentType='float'] - The component type.
  16995. * @return {String} The type.
  16996. */
  16997. getTypeFromLength( length, componentType = 'float' ) {
  16998. if ( length === 1 ) return componentType;
  16999. const baseType = getTypeFromLength( length );
  17000. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  17001. return prefix + baseType;
  17002. }
  17003. /**
  17004. * Returns the type for a given typed array.
  17005. *
  17006. * @param {TypedArray} type - The typed array.
  17007. * @return {String} The type.
  17008. */
  17009. getTypeFromArray( array ) {
  17010. return typeFromArray.get( array.constructor );
  17011. }
  17012. /**
  17013. * Returns the type for a given buffer attribute.
  17014. *
  17015. * @param {BufferAttribute} attribute - The buffer attribute.
  17016. * @return {String} The type.
  17017. */
  17018. getTypeFromAttribute( attribute ) {
  17019. let dataAttribute = attribute;
  17020. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  17021. const array = dataAttribute.array;
  17022. const itemSize = attribute.itemSize;
  17023. const normalized = attribute.normalized;
  17024. let arrayType;
  17025. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  17026. arrayType = this.getTypeFromArray( array );
  17027. }
  17028. return this.getTypeFromLength( itemSize, arrayType );
  17029. }
  17030. /**
  17031. * Returns the length for the given data type.
  17032. *
  17033. * @param {String} type - The data type.
  17034. * @return {Number} The length.
  17035. */
  17036. getTypeLength( type ) {
  17037. const vecType = this.getVectorType( type );
  17038. const vecNum = /vec([2-4])/.exec( vecType );
  17039. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  17040. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  17041. if ( /mat2/.test( type ) === true ) return 4;
  17042. if ( /mat3/.test( type ) === true ) return 9;
  17043. if ( /mat4/.test( type ) === true ) return 16;
  17044. return 0;
  17045. }
  17046. /**
  17047. * Returns the vector type for a given matrix type.
  17048. *
  17049. * @param {String} type - The matrix type.
  17050. * @return {String} The vector type.
  17051. */
  17052. getVectorFromMatrix( type ) {
  17053. return type.replace( 'mat', 'vec' );
  17054. }
  17055. /**
  17056. * For a given type this method changes the component type to the
  17057. * given value. E.g. `vec4` should be changed to the new component type
  17058. * `uint` which results in `uvec4`.
  17059. *
  17060. * @param {String} type - The type.
  17061. * @param {String} newComponentType - The new component type.
  17062. * @return {String} The new type.
  17063. */
  17064. changeComponentType( type, newComponentType ) {
  17065. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  17066. }
  17067. /**
  17068. * Returns the integer type pendant for the given type.
  17069. *
  17070. * @param {String} type - The type.
  17071. * @return {String} The integer type.
  17072. */
  17073. getIntegerType( type ) {
  17074. const componentType = this.getComponentType( type );
  17075. if ( componentType === 'int' || componentType === 'uint' ) return type;
  17076. return this.changeComponentType( type, 'int' );
  17077. }
  17078. addStack() {
  17079. this.stack = stack( this.stack );
  17080. this.stacks.push( getCurrentStack() || this.stack );
  17081. setCurrentStack( this.stack );
  17082. return this.stack;
  17083. }
  17084. removeStack() {
  17085. const lastStack = this.stack;
  17086. this.stack = lastStack.parent;
  17087. setCurrentStack( this.stacks.pop() );
  17088. return lastStack;
  17089. }
  17090. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  17091. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  17092. let nodeData = cache.getData( node );
  17093. if ( nodeData === undefined ) {
  17094. nodeData = {};
  17095. cache.setData( node, nodeData );
  17096. }
  17097. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  17098. return nodeData[ shaderStage ];
  17099. }
  17100. getNodeProperties( node, shaderStage = 'any' ) {
  17101. const nodeData = this.getDataFromNode( node, shaderStage );
  17102. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  17103. }
  17104. getBufferAttributeFromNode( node, type ) {
  17105. const nodeData = this.getDataFromNode( node );
  17106. let bufferAttribute = nodeData.bufferAttribute;
  17107. if ( bufferAttribute === undefined ) {
  17108. const index = this.uniforms.index ++;
  17109. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  17110. this.bufferAttributes.push( bufferAttribute );
  17111. nodeData.bufferAttribute = bufferAttribute;
  17112. }
  17113. return bufferAttribute;
  17114. }
  17115. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  17116. const nodeData = this.getDataFromNode( node, shaderStage );
  17117. let structType = nodeData.structType;
  17118. if ( structType === undefined ) {
  17119. const index = this.structs.index ++;
  17120. structType = new StructTypeNode( 'StructType' + index, types );
  17121. this.structs[ shaderStage ].push( structType );
  17122. nodeData.structType = structType;
  17123. }
  17124. return structType;
  17125. }
  17126. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  17127. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  17128. let nodeUniform = nodeData.uniform;
  17129. if ( nodeUniform === undefined ) {
  17130. const index = this.uniforms.index ++;
  17131. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  17132. this.uniforms[ shaderStage ].push( nodeUniform );
  17133. nodeData.uniform = nodeUniform;
  17134. }
  17135. return nodeUniform;
  17136. }
  17137. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  17138. const nodeData = this.getDataFromNode( node, shaderStage );
  17139. let nodeVar = nodeData.variable;
  17140. if ( nodeVar === undefined ) {
  17141. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  17142. if ( name === null ) name = 'nodeVar' + vars.length;
  17143. nodeVar = new NodeVar( name, type );
  17144. vars.push( nodeVar );
  17145. nodeData.variable = nodeVar;
  17146. }
  17147. return nodeVar;
  17148. }
  17149. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  17150. const nodeData = this.getDataFromNode( node, 'any' );
  17151. let nodeVarying = nodeData.varying;
  17152. if ( nodeVarying === undefined ) {
  17153. const varyings = this.varyings;
  17154. const index = varyings.length;
  17155. if ( name === null ) name = 'nodeVarying' + index;
  17156. nodeVarying = new NodeVarying( name, type );
  17157. varyings.push( nodeVarying );
  17158. nodeData.varying = nodeVarying;
  17159. }
  17160. return nodeVarying;
  17161. }
  17162. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  17163. const nodeData = this.getDataFromNode( node );
  17164. let nodeCode = nodeData.code;
  17165. if ( nodeCode === undefined ) {
  17166. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  17167. const index = codes.length;
  17168. nodeCode = new NodeCode( 'nodeCode' + index, type );
  17169. codes.push( nodeCode );
  17170. nodeData.code = nodeCode;
  17171. }
  17172. return nodeCode;
  17173. }
  17174. addFlowCodeHierarchy( node, nodeBlock ) {
  17175. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  17176. let needsFlowCode = true;
  17177. let nodeBlockHierarchy = nodeBlock;
  17178. while ( nodeBlockHierarchy ) {
  17179. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  17180. needsFlowCode = false;
  17181. break;
  17182. }
  17183. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  17184. }
  17185. if ( needsFlowCode ) {
  17186. for ( const flowCode of flowCodes ) {
  17187. this.addLineFlowCode( flowCode );
  17188. }
  17189. }
  17190. }
  17191. addLineFlowCodeBlock( node, code, nodeBlock ) {
  17192. const nodeData = this.getDataFromNode( node );
  17193. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  17194. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  17195. flowCodes.push( code );
  17196. codeBlock.set( nodeBlock, true );
  17197. }
  17198. addLineFlowCode( code, node = null ) {
  17199. if ( code === '' ) return this;
  17200. if ( node !== null && this.context.nodeBlock ) {
  17201. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  17202. }
  17203. code = this.tab + code;
  17204. if ( ! /;\s*$/.test( code ) ) {
  17205. code = code + ';\n';
  17206. }
  17207. this.flow.code += code;
  17208. return this;
  17209. }
  17210. addFlowCode( code ) {
  17211. this.flow.code += code;
  17212. return this;
  17213. }
  17214. addFlowTab() {
  17215. this.tab += '\t';
  17216. return this;
  17217. }
  17218. removeFlowTab() {
  17219. this.tab = this.tab.slice( 0, - 1 );
  17220. return this;
  17221. }
  17222. getFlowData( node/*, shaderStage*/ ) {
  17223. return this.flowsData.get( node );
  17224. }
  17225. flowNode( node ) {
  17226. const output = node.getNodeType( this );
  17227. const flowData = this.flowChildNode( node, output );
  17228. this.flowsData.set( node, flowData );
  17229. return flowData;
  17230. }
  17231. buildFunctionNode( shaderNode ) {
  17232. const fn = new FunctionNode();
  17233. const previous = this.currentFunctionNode;
  17234. this.currentFunctionNode = fn;
  17235. fn.code = this.buildFunctionCode( shaderNode );
  17236. this.currentFunctionNode = previous;
  17237. return fn;
  17238. }
  17239. flowShaderNode( shaderNode ) {
  17240. const layout = shaderNode.layout;
  17241. const inputs = {
  17242. [ Symbol.iterator ]() {
  17243. let index = 0;
  17244. const values = Object.values( this );
  17245. return {
  17246. next: () => ( {
  17247. value: values[ index ],
  17248. done: index ++ >= values.length
  17249. } )
  17250. };
  17251. }
  17252. };
  17253. for ( const input of layout.inputs ) {
  17254. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  17255. }
  17256. //
  17257. shaderNode.layout = null;
  17258. const callNode = shaderNode.call( inputs );
  17259. const flowData = this.flowStagesNode( callNode, layout.type );
  17260. shaderNode.layout = layout;
  17261. return flowData;
  17262. }
  17263. flowStagesNode( node, output = null ) {
  17264. const previousFlow = this.flow;
  17265. const previousVars = this.vars;
  17266. const previousCache = this.cache;
  17267. const previousBuildStage = this.buildStage;
  17268. const previousStack = this.stack;
  17269. const flow = {
  17270. code: ''
  17271. };
  17272. this.flow = flow;
  17273. this.vars = {};
  17274. this.cache = new NodeCache();
  17275. this.stack = stack();
  17276. for ( const buildStage of defaultBuildStages ) {
  17277. this.setBuildStage( buildStage );
  17278. flow.result = node.build( this, output );
  17279. }
  17280. flow.vars = this.getVars( this.shaderStage );
  17281. this.flow = previousFlow;
  17282. this.vars = previousVars;
  17283. this.cache = previousCache;
  17284. this.stack = previousStack;
  17285. this.setBuildStage( previousBuildStage );
  17286. return flow;
  17287. }
  17288. getFunctionOperator() {
  17289. return null;
  17290. }
  17291. flowChildNode( node, output = null ) {
  17292. const previousFlow = this.flow;
  17293. const flow = {
  17294. code: ''
  17295. };
  17296. this.flow = flow;
  17297. flow.result = node.build( this, output );
  17298. this.flow = previousFlow;
  17299. return flow;
  17300. }
  17301. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  17302. const previousShaderStage = this.shaderStage;
  17303. this.setShaderStage( shaderStage );
  17304. const flowData = this.flowChildNode( node, output );
  17305. if ( propertyName !== null ) {
  17306. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  17307. }
  17308. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  17309. this.setShaderStage( previousShaderStage );
  17310. return flowData;
  17311. }
  17312. /**
  17313. * Returns an array holding all node attributes of this node builder.
  17314. *
  17315. * @return {Array<NodeAttribute>} The node attributes of this builder.
  17316. */
  17317. getAttributesArray() {
  17318. return this.attributes.concat( this.bufferAttributes );
  17319. }
  17320. /**
  17321. * Returns the attribute definitions as a shader string for the given shader stage.
  17322. *
  17323. * @abstract
  17324. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17325. * @return {String} The attribute code section.
  17326. */
  17327. getAttributes( /*shaderStage*/ ) {
  17328. console.warn( 'Abstract function.' );
  17329. }
  17330. /**
  17331. * Returns the varying definitions as a shader string for the given shader stage.
  17332. *
  17333. * @abstract
  17334. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17335. * @return {String} The varying code section.
  17336. */
  17337. getVaryings( /*shaderStage*/ ) {
  17338. console.warn( 'Abstract function.' );
  17339. }
  17340. /**
  17341. * Returns a single variable definition as a shader string for the given variable type and name.
  17342. *
  17343. * @param {String} type - The variable's type.
  17344. * @param {String} name - The variable's name.
  17345. * @return {String} The shader string.
  17346. */
  17347. getVar( type, name ) {
  17348. return `${ this.getType( type ) } ${ name }`;
  17349. }
  17350. /**
  17351. * Returns the variable definitions as a shader string for the given shader stage.
  17352. *
  17353. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17354. * @return {String} The variable code section.
  17355. */
  17356. getVars( shaderStage ) {
  17357. let snippet = '';
  17358. const vars = this.vars[ shaderStage ];
  17359. if ( vars !== undefined ) {
  17360. for ( const variable of vars ) {
  17361. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  17362. }
  17363. }
  17364. return snippet;
  17365. }
  17366. /**
  17367. * Returns the uniform definitions as a shader string for the given shader stage.
  17368. *
  17369. * @abstract
  17370. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17371. * @return {String} The uniform code section.
  17372. */
  17373. getUniforms( /*shaderStage*/ ) {
  17374. console.warn( 'Abstract function.' );
  17375. }
  17376. /**
  17377. * Returns the native code definitions as a shader string for the given shader stage.
  17378. *
  17379. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The current shader stage.
  17380. * @return {String} The native code section.
  17381. */
  17382. getCodes( shaderStage ) {
  17383. const codes = this.codes[ shaderStage ];
  17384. let code = '';
  17385. if ( codes !== undefined ) {
  17386. for ( const nodeCode of codes ) {
  17387. code += nodeCode.code + '\n';
  17388. }
  17389. }
  17390. return code;
  17391. }
  17392. getHash() {
  17393. return this.vertexShader + this.fragmentShader + this.computeShader;
  17394. }
  17395. /**
  17396. * Sets the current shader stage.
  17397. *
  17398. * @param {('vertex'|'fragment'|'compute')?} shaderStage - The shader stage to set.
  17399. */
  17400. setShaderStage( shaderStage ) {
  17401. this.shaderStage = shaderStage;
  17402. }
  17403. /**
  17404. * Returns the current shader stage.
  17405. *
  17406. * @return {('vertex'|'fragment'|'compute')?} The current shader stage.
  17407. */
  17408. getShaderStage() {
  17409. return this.shaderStage;
  17410. }
  17411. /**
  17412. * Sets the current build stage.
  17413. *
  17414. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  17415. */
  17416. setBuildStage( buildStage ) {
  17417. this.buildStage = buildStage;
  17418. }
  17419. /**
  17420. * Returns the current build stage.
  17421. *
  17422. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  17423. */
  17424. getBuildStage() {
  17425. return this.buildStage;
  17426. }
  17427. /**
  17428. * Controls the code build of the shader stages.
  17429. *
  17430. * @abstract
  17431. */
  17432. buildCode() {
  17433. console.warn( 'Abstract function.' );
  17434. }
  17435. /**
  17436. * Central build method which controls the build for the given object.
  17437. *
  17438. * @return {NodeBuilder} A reference to this node builder.
  17439. */
  17440. build() {
  17441. const { object, material, renderer } = this;
  17442. if ( material !== null ) {
  17443. let nodeMaterial = renderer.library.fromMaterial( material );
  17444. if ( nodeMaterial === null ) {
  17445. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  17446. nodeMaterial = new NodeMaterial();
  17447. }
  17448. nodeMaterial.build( this );
  17449. } else {
  17450. this.addFlow( 'compute', object );
  17451. }
  17452. // setup() -> stage 1: create possible new nodes and returns an output reference node
  17453. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  17454. // generate() -> stage 3: generate shader
  17455. for ( const buildStage of defaultBuildStages ) {
  17456. this.setBuildStage( buildStage );
  17457. if ( this.context.vertex && this.context.vertex.isNode ) {
  17458. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  17459. }
  17460. for ( const shaderStage of shaderStages ) {
  17461. this.setShaderStage( shaderStage );
  17462. const flowNodes = this.flowNodes[ shaderStage ];
  17463. for ( const node of flowNodes ) {
  17464. if ( buildStage === 'generate' ) {
  17465. this.flowNode( node );
  17466. } else {
  17467. node.build( this );
  17468. }
  17469. }
  17470. }
  17471. }
  17472. this.setBuildStage( null );
  17473. this.setShaderStage( null );
  17474. // stage 4: build code for a specific output
  17475. this.buildCode();
  17476. this.buildUpdateNodes();
  17477. return this;
  17478. }
  17479. getNodeUniform( uniformNode, type ) {
  17480. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  17481. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  17482. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  17483. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  17484. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  17485. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  17486. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  17487. throw new Error( `Uniform "${type}" not declared.` );
  17488. }
  17489. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  17490. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  17491. }
  17492. format( snippet, fromType, toType ) {
  17493. fromType = this.getVectorType( fromType );
  17494. toType = this.getVectorType( toType );
  17495. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  17496. return snippet;
  17497. }
  17498. const fromTypeLength = this.getTypeLength( fromType );
  17499. const toTypeLength = this.getTypeLength( toType );
  17500. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  17501. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  17502. }
  17503. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  17504. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  17505. }
  17506. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  17507. // @TODO: ignore for now
  17508. return snippet;
  17509. }
  17510. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  17511. // @TODO: ignore for now
  17512. return snippet;
  17513. }
  17514. if ( fromTypeLength === toTypeLength ) {
  17515. return `${ this.getType( toType ) }( ${ snippet } )`;
  17516. }
  17517. if ( fromTypeLength > toTypeLength ) {
  17518. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  17519. }
  17520. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  17521. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  17522. }
  17523. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  17524. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  17525. }
  17526. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  17527. // convert a number value to vector type, e.g:
  17528. // vec3( 1u ) -> vec3( float( 1u ) )
  17529. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  17530. }
  17531. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  17532. }
  17533. /**
  17534. * Returns a signature with the engine's current revision.
  17535. *
  17536. * @return {String} The signature.
  17537. */
  17538. getSignature() {
  17539. return `// Three.js r${ REVISION } - Node System\n`;
  17540. }
  17541. }
  17542. /**
  17543. * Management class for updating nodes. The module tracks metrics like
  17544. * the elapsed time, delta time, the render and frame ID to correctly
  17545. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  17546. * and {@link Node#updateAfter} depending on the node's configuration.
  17547. */
  17548. class NodeFrame {
  17549. /**
  17550. * Constructs a new node fame.
  17551. */
  17552. constructor() {
  17553. /**
  17554. * The elapsed time in seconds.
  17555. *
  17556. * @type {Number}
  17557. * @default 0
  17558. */
  17559. this.time = 0;
  17560. /**
  17561. * The delta time in seconds.
  17562. *
  17563. * @type {Number}
  17564. * @default 0
  17565. */
  17566. this.deltaTime = 0;
  17567. /**
  17568. * The frame ID.
  17569. *
  17570. * @type {Number}
  17571. * @default 0
  17572. */
  17573. this.frameId = 0;
  17574. /**
  17575. * The render ID.
  17576. *
  17577. * @type {Number}
  17578. * @default 0
  17579. */
  17580. this.renderId = 0;
  17581. /**
  17582. * Used to control the {@link Node#update} call.
  17583. *
  17584. * @type {WeakMap}
  17585. */
  17586. this.updateMap = new WeakMap();
  17587. /**
  17588. * Used to control the {@link Node#updateBefore} call.
  17589. *
  17590. * @type {WeakMap}
  17591. */
  17592. this.updateBeforeMap = new WeakMap();
  17593. /**
  17594. * Used to control the {@link Node#updateAfter} call.
  17595. *
  17596. * @type {WeakMap}
  17597. */
  17598. this.updateAfterMap = new WeakMap();
  17599. /**
  17600. * A reference to the current renderer.
  17601. *
  17602. * @type {Renderer?}
  17603. * @default null
  17604. */
  17605. this.renderer = null;
  17606. /**
  17607. * A reference to the current material.
  17608. *
  17609. * @type {Material?}
  17610. * @default null
  17611. */
  17612. this.material = null;
  17613. /**
  17614. * A reference to the current camera.
  17615. *
  17616. * @type {Camera?}
  17617. * @default null
  17618. */
  17619. this.camera = null;
  17620. /**
  17621. * A reference to the current 3D object.
  17622. *
  17623. * @type {Object3D?}
  17624. * @default null
  17625. */
  17626. this.object = null;
  17627. /**
  17628. * A reference to the current scene.
  17629. *
  17630. * @type {Scene?}
  17631. * @default null
  17632. */
  17633. this.scene = null;
  17634. }
  17635. /**
  17636. * Returns a dictionary for a given node and update map which
  17637. * is used to correctly call node update methods per frame or render.
  17638. *
  17639. * @private
  17640. * @param {WeakMap} referenceMap - The reference weak map.
  17641. * @param {Node} nodeRef - The reference to the current node.
  17642. * @return {Object<String,WeakMap>} The dictionary.
  17643. */
  17644. _getMaps( referenceMap, nodeRef ) {
  17645. let maps = referenceMap.get( nodeRef );
  17646. if ( maps === undefined ) {
  17647. maps = {
  17648. renderMap: new WeakMap(),
  17649. frameMap: new WeakMap()
  17650. };
  17651. referenceMap.set( nodeRef, maps );
  17652. }
  17653. return maps;
  17654. }
  17655. /**
  17656. * This method executes the {@link Node#updateBefore} for the given node.
  17657. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  17658. * is only executed once per frame, render or object depending on the update
  17659. * type.
  17660. *
  17661. * @param {Node} node - The node that should be updated.
  17662. */
  17663. updateBeforeNode( node ) {
  17664. const updateType = node.getUpdateBeforeType();
  17665. const reference = node.updateReference( this );
  17666. if ( updateType === NodeUpdateType.FRAME ) {
  17667. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  17668. if ( frameMap.get( reference ) !== this.frameId ) {
  17669. if ( node.updateBefore( this ) !== false ) {
  17670. frameMap.set( reference, this.frameId );
  17671. }
  17672. }
  17673. } else if ( updateType === NodeUpdateType.RENDER ) {
  17674. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  17675. if ( renderMap.get( reference ) !== this.renderId ) {
  17676. if ( node.updateBefore( this ) !== false ) {
  17677. renderMap.set( reference, this.renderId );
  17678. }
  17679. }
  17680. } else if ( updateType === NodeUpdateType.OBJECT ) {
  17681. node.updateBefore( this );
  17682. }
  17683. }
  17684. /**
  17685. * This method executes the {@link Node#updateAfter} for the given node.
  17686. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  17687. * is only executed once per frame, render or object depending on the update
  17688. * type.
  17689. *
  17690. * @param {Node} node - The node that should be updated.
  17691. */
  17692. updateAfterNode( node ) {
  17693. const updateType = node.getUpdateAfterType();
  17694. const reference = node.updateReference( this );
  17695. if ( updateType === NodeUpdateType.FRAME ) {
  17696. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  17697. if ( frameMap.get( reference ) !== this.frameId ) {
  17698. if ( node.updateAfter( this ) !== false ) {
  17699. frameMap.set( reference, this.frameId );
  17700. }
  17701. }
  17702. } else if ( updateType === NodeUpdateType.RENDER ) {
  17703. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  17704. if ( renderMap.get( reference ) !== this.renderId ) {
  17705. if ( node.updateAfter( this ) !== false ) {
  17706. renderMap.set( reference, this.renderId );
  17707. }
  17708. }
  17709. } else if ( updateType === NodeUpdateType.OBJECT ) {
  17710. node.updateAfter( this );
  17711. }
  17712. }
  17713. /**
  17714. * This method executes the {@link Node#update} for the given node.
  17715. * It makes sure {@link Node#updateType} is honored meaning the update
  17716. * is only executed once per frame, render or object depending on the update
  17717. * type.
  17718. *
  17719. * @param {Node} node - The node that should be updated.
  17720. */
  17721. updateNode( node ) {
  17722. const updateType = node.getUpdateType();
  17723. const reference = node.updateReference( this );
  17724. if ( updateType === NodeUpdateType.FRAME ) {
  17725. const { frameMap } = this._getMaps( this.updateMap, reference );
  17726. if ( frameMap.get( reference ) !== this.frameId ) {
  17727. if ( node.update( this ) !== false ) {
  17728. frameMap.set( reference, this.frameId );
  17729. }
  17730. }
  17731. } else if ( updateType === NodeUpdateType.RENDER ) {
  17732. const { renderMap } = this._getMaps( this.updateMap, reference );
  17733. if ( renderMap.get( reference ) !== this.renderId ) {
  17734. if ( node.update( this ) !== false ) {
  17735. renderMap.set( reference, this.renderId );
  17736. }
  17737. }
  17738. } else if ( updateType === NodeUpdateType.OBJECT ) {
  17739. node.update( this );
  17740. }
  17741. }
  17742. /**
  17743. * Updates the internal state of the node frame. This method is
  17744. * called by the renderer in its internal animation loop.
  17745. */
  17746. update() {
  17747. this.frameId ++;
  17748. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  17749. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  17750. this.lastTime = performance.now();
  17751. this.time += this.deltaTime;
  17752. }
  17753. }
  17754. /**
  17755. * Describes the input of a {@link NodeFunction}.
  17756. */
  17757. class NodeFunctionInput {
  17758. /**
  17759. * Constructs a new node function input.
  17760. *
  17761. * @param {String} type - The input type.
  17762. * @param {String} name - The input name.
  17763. * @param {Number?} [count=null] - TODO (only relevant for GLSL).
  17764. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  17765. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  17766. */
  17767. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  17768. /**
  17769. * The input type.
  17770. *
  17771. * @type {String}
  17772. */
  17773. this.type = type;
  17774. /**
  17775. * The input name.
  17776. *
  17777. * @type {String}
  17778. */
  17779. this.name = name;
  17780. /**
  17781. * TODO (only relevant for GLSL).
  17782. *
  17783. * @type {Number?}
  17784. * @default null
  17785. */
  17786. this.count = count;
  17787. /**
  17788. *The parameter qualifier (only relevant for GLSL).
  17789. *
  17790. * @type {('in'|'out'|'inout')}
  17791. * @default ''
  17792. */
  17793. this.qualifier = qualifier;
  17794. /**
  17795. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  17796. *
  17797. * @type {Boolean}
  17798. * @default false
  17799. */
  17800. this.isConst = isConst;
  17801. }
  17802. }
  17803. NodeFunctionInput.isNodeFunctionInput = true;
  17804. class DirectionalLightNode extends AnalyticLightNode {
  17805. static get type() {
  17806. return 'DirectionalLightNode';
  17807. }
  17808. constructor( light = null ) {
  17809. super( light );
  17810. }
  17811. setup( builder ) {
  17812. super.setup( builder );
  17813. const lightingModel = builder.context.lightingModel;
  17814. const lightColor = this.colorNode;
  17815. const lightDirection = lightTargetDirection( this.light );
  17816. const reflectedLight = builder.context.reflectedLight;
  17817. lightingModel.direct( {
  17818. lightDirection,
  17819. lightColor,
  17820. reflectedLight
  17821. }, builder.stack, builder );
  17822. }
  17823. }
  17824. const _matrix41 = /*@__PURE__*/ new Matrix4();
  17825. const _matrix42 = /*@__PURE__*/ new Matrix4();
  17826. let ltcLib = null;
  17827. class RectAreaLightNode extends AnalyticLightNode {
  17828. static get type() {
  17829. return 'RectAreaLightNode';
  17830. }
  17831. constructor( light = null ) {
  17832. super( light );
  17833. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  17834. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  17835. this.updateType = NodeUpdateType.RENDER;
  17836. }
  17837. update( frame ) {
  17838. super.update( frame );
  17839. const { light } = this;
  17840. const viewMatrix = frame.camera.matrixWorldInverse;
  17841. _matrix42.identity();
  17842. _matrix41.copy( light.matrixWorld );
  17843. _matrix41.premultiply( viewMatrix );
  17844. _matrix42.extractRotation( _matrix41 );
  17845. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  17846. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  17847. this.halfWidth.value.applyMatrix4( _matrix42 );
  17848. this.halfHeight.value.applyMatrix4( _matrix42 );
  17849. }
  17850. setup( builder ) {
  17851. super.setup( builder );
  17852. let ltc_1, ltc_2;
  17853. if ( builder.isAvailable( 'float32Filterable' ) ) {
  17854. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  17855. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  17856. } else {
  17857. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  17858. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  17859. }
  17860. const { colorNode, light } = this;
  17861. const lightingModel = builder.context.lightingModel;
  17862. const lightPosition = lightViewPosition( light );
  17863. const reflectedLight = builder.context.reflectedLight;
  17864. lightingModel.directRectArea( {
  17865. lightColor: colorNode,
  17866. lightPosition,
  17867. halfWidth: this.halfWidth,
  17868. halfHeight: this.halfHeight,
  17869. reflectedLight,
  17870. ltc_1,
  17871. ltc_2
  17872. }, builder.stack, builder );
  17873. }
  17874. static setLTC( ltc ) {
  17875. ltcLib = ltc;
  17876. }
  17877. }
  17878. class SpotLightNode extends AnalyticLightNode {
  17879. static get type() {
  17880. return 'SpotLightNode';
  17881. }
  17882. constructor( light = null ) {
  17883. super( light );
  17884. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  17885. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  17886. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  17887. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  17888. }
  17889. update( frame ) {
  17890. super.update( frame );
  17891. const { light } = this;
  17892. this.coneCosNode.value = Math.cos( light.angle );
  17893. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  17894. this.cutoffDistanceNode.value = light.distance;
  17895. this.decayExponentNode.value = light.decay;
  17896. }
  17897. getSpotAttenuation( angleCosine ) {
  17898. const { coneCosNode, penumbraCosNode } = this;
  17899. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  17900. }
  17901. setup( builder ) {
  17902. super.setup( builder );
  17903. const lightingModel = builder.context.lightingModel;
  17904. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  17905. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  17906. const lightDirection = lVector.normalize();
  17907. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  17908. const spotAttenuation = this.getSpotAttenuation( angleCos );
  17909. const lightDistance = lVector.length();
  17910. const lightAttenuation = getDistanceAttenuation( {
  17911. lightDistance,
  17912. cutoffDistance: cutoffDistanceNode,
  17913. decayExponent: decayExponentNode
  17914. } );
  17915. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  17916. if ( light.map ) {
  17917. const spotLightCoord = lightProjectionUV( light );
  17918. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  17919. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  17920. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  17921. }
  17922. const reflectedLight = builder.context.reflectedLight;
  17923. lightingModel.direct( {
  17924. lightDirection,
  17925. lightColor,
  17926. reflectedLight
  17927. }, builder.stack, builder );
  17928. }
  17929. }
  17930. class IESSpotLightNode extends SpotLightNode {
  17931. static get type() {
  17932. return 'IESSpotLightNode';
  17933. }
  17934. getSpotAttenuation( angleCosine ) {
  17935. const iesMap = this.light.iesMap;
  17936. let spotAttenuation = null;
  17937. if ( iesMap && iesMap.isTexture === true ) {
  17938. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  17939. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  17940. } else {
  17941. spotAttenuation = super.getSpotAttenuation( angleCosine );
  17942. }
  17943. return spotAttenuation;
  17944. }
  17945. }
  17946. class AmbientLightNode extends AnalyticLightNode {
  17947. static get type() {
  17948. return 'AmbientLightNode';
  17949. }
  17950. constructor( light = null ) {
  17951. super( light );
  17952. }
  17953. setup( { context } ) {
  17954. context.irradiance.addAssign( this.colorNode );
  17955. }
  17956. }
  17957. class HemisphereLightNode extends AnalyticLightNode {
  17958. static get type() {
  17959. return 'HemisphereLightNode';
  17960. }
  17961. constructor( light = null ) {
  17962. super( light );
  17963. this.lightPositionNode = lightPosition( light );
  17964. this.lightDirectionNode = this.lightPositionNode.normalize();
  17965. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  17966. }
  17967. update( frame ) {
  17968. const { light } = this;
  17969. super.update( frame );
  17970. this.lightPositionNode.object3d = light;
  17971. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  17972. }
  17973. setup( builder ) {
  17974. const { colorNode, groundColorNode, lightDirectionNode } = this;
  17975. const dotNL = normalView.dot( lightDirectionNode );
  17976. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  17977. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  17978. builder.context.irradiance.addAssign( irradiance );
  17979. }
  17980. }
  17981. class LightProbeNode extends AnalyticLightNode {
  17982. static get type() {
  17983. return 'LightProbeNode';
  17984. }
  17985. constructor( light = null ) {
  17986. super( light );
  17987. const array = [];
  17988. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  17989. this.lightProbe = uniformArray( array );
  17990. }
  17991. update( frame ) {
  17992. const { light } = this;
  17993. super.update( frame );
  17994. //
  17995. for ( let i = 0; i < 9; i ++ ) {
  17996. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  17997. }
  17998. }
  17999. setup( builder ) {
  18000. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  18001. builder.context.irradiance.addAssign( irradiance );
  18002. }
  18003. }
  18004. /**
  18005. * Base class for node parsers. A derived parser must be implemented
  18006. * for each supported native shader language.
  18007. */
  18008. class NodeParser {
  18009. /**
  18010. * The method parses the given native code an returns a node function.
  18011. *
  18012. * @abstract
  18013. * @param {String} source - The native shader code.
  18014. * @return {NodeFunction} A node function.
  18015. */
  18016. parseFunction( /*source*/ ) {
  18017. console.warn( 'Abstract function.' );
  18018. }
  18019. }
  18020. /**
  18021. * Base class for node functions. A derived module must be implemented
  18022. * for each supported native shader language. Similar to other `Node*` modules,
  18023. * this class is only relevant during the building process and not used
  18024. * in user-level code.
  18025. */
  18026. class NodeFunction {
  18027. /**
  18028. * Constructs a new node function.
  18029. *
  18030. * @param {String} type - The node type. This type is the return type of the node function.
  18031. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  18032. * @param {String} [name=''] - The function's name.
  18033. * @param {String} [precision=''] - The precision qualifier.
  18034. */
  18035. constructor( type, inputs, name = '', precision = '' ) {
  18036. /**
  18037. * The node type. This type is the return type of the node function.
  18038. *
  18039. * @type {String}
  18040. */
  18041. this.type = type;
  18042. /**
  18043. * The function's inputs.
  18044. *
  18045. * @type {Array<NodeFunctionInput>}
  18046. */
  18047. this.inputs = inputs;
  18048. /**
  18049. * The name of the uniform.
  18050. *
  18051. * @type {String}
  18052. * @default ''
  18053. */
  18054. this.name = name;
  18055. /**
  18056. * The precision qualifier.
  18057. *
  18058. * @type {String}
  18059. * @default ''
  18060. */
  18061. this.precision = precision;
  18062. }
  18063. /**
  18064. * This method returns the native code of the node function.
  18065. *
  18066. * @abstract
  18067. * @param {String} name - The function's name.
  18068. * @return {String} A shader code.
  18069. */
  18070. getCode( /*name = this.name*/ ) {
  18071. console.warn( 'Abstract function.' );
  18072. }
  18073. }
  18074. NodeFunction.isNodeFunction = true;
  18075. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  18076. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  18077. const pragmaMain = '#pragma main';
  18078. const parse$1 = ( source ) => {
  18079. source = source.trim();
  18080. const pragmaMainIndex = source.indexOf( pragmaMain );
  18081. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  18082. const declaration = mainCode.match( declarationRegexp$1 );
  18083. if ( declaration !== null && declaration.length === 5 ) {
  18084. // tokenizer
  18085. const inputsCode = declaration[ 4 ];
  18086. const propsMatches = [];
  18087. let nameMatch = null;
  18088. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  18089. propsMatches.push( nameMatch );
  18090. }
  18091. // parser
  18092. const inputs = [];
  18093. let i = 0;
  18094. while ( i < propsMatches.length ) {
  18095. const isConst = propsMatches[ i ][ 0 ] === 'const';
  18096. if ( isConst === true ) {
  18097. i ++;
  18098. }
  18099. let qualifier = propsMatches[ i ][ 0 ];
  18100. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  18101. i ++;
  18102. } else {
  18103. qualifier = '';
  18104. }
  18105. const type = propsMatches[ i ++ ][ 0 ];
  18106. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  18107. if ( Number.isNaN( count ) === false ) i ++;
  18108. else count = null;
  18109. const name = propsMatches[ i ++ ][ 0 ];
  18110. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  18111. }
  18112. //
  18113. const blockCode = mainCode.substring( declaration[ 0 ].length );
  18114. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  18115. const type = declaration[ 2 ];
  18116. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  18117. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  18118. return {
  18119. type,
  18120. inputs,
  18121. name,
  18122. precision,
  18123. inputsCode,
  18124. blockCode,
  18125. headerCode
  18126. };
  18127. } else {
  18128. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  18129. }
  18130. };
  18131. /**
  18132. * This class represents a GLSL node function.
  18133. *
  18134. * @augments NodeFunction
  18135. */
  18136. class GLSLNodeFunction extends NodeFunction {
  18137. /**
  18138. * Constructs a new GLSL node function.
  18139. *
  18140. * @param {String} source - The GLSL source.
  18141. */
  18142. constructor( source ) {
  18143. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  18144. super( type, inputs, name, precision );
  18145. this.inputsCode = inputsCode;
  18146. this.blockCode = blockCode;
  18147. this.headerCode = headerCode;
  18148. }
  18149. /**
  18150. * This method returns the GLSL code of the node function.
  18151. *
  18152. * @param {String} [name=this.name] - The function's name.
  18153. * @return {String} The shader code.
  18154. */
  18155. getCode( name = this.name ) {
  18156. let code;
  18157. const blockCode = this.blockCode;
  18158. if ( blockCode !== '' ) {
  18159. const { type, inputsCode, headerCode, precision } = this;
  18160. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  18161. if ( precision !== '' ) {
  18162. declarationCode = `${ precision } ${ declarationCode }`;
  18163. }
  18164. code = headerCode + declarationCode + blockCode;
  18165. } else {
  18166. // interface function
  18167. code = '';
  18168. }
  18169. return code;
  18170. }
  18171. }
  18172. /**
  18173. * A GLSL node parser.
  18174. *
  18175. * @augments NodeParser
  18176. */
  18177. class GLSLNodeParser extends NodeParser {
  18178. /**
  18179. * The method parses the given GLSL code an returns a node function.
  18180. *
  18181. * @param {String} source - The GLSL code.
  18182. * @return {GLSLNodeFunction} A node function.
  18183. */
  18184. parseFunction( source ) {
  18185. return new GLSLNodeFunction( source );
  18186. }
  18187. }
  18188. const outputNodeMap = new WeakMap();
  18189. class Nodes extends DataMap {
  18190. constructor( renderer, backend ) {
  18191. super();
  18192. this.renderer = renderer;
  18193. this.backend = backend;
  18194. this.nodeFrame = new NodeFrame();
  18195. this.nodeBuilderCache = new Map();
  18196. this.callHashCache = new ChainMap();
  18197. this.groupsData = new ChainMap();
  18198. }
  18199. updateGroup( nodeUniformsGroup ) {
  18200. const groupNode = nodeUniformsGroup.groupNode;
  18201. const name = groupNode.name;
  18202. // objectGroup is every updated
  18203. if ( name === objectGroup.name ) return true;
  18204. // renderGroup is updated once per render/compute call
  18205. if ( name === renderGroup.name ) {
  18206. const uniformsGroupData = this.get( nodeUniformsGroup );
  18207. const renderId = this.nodeFrame.renderId;
  18208. if ( uniformsGroupData.renderId !== renderId ) {
  18209. uniformsGroupData.renderId = renderId;
  18210. return true;
  18211. }
  18212. return false;
  18213. }
  18214. // frameGroup is updated once per frame
  18215. if ( name === frameGroup.name ) {
  18216. const uniformsGroupData = this.get( nodeUniformsGroup );
  18217. const frameId = this.nodeFrame.frameId;
  18218. if ( uniformsGroupData.frameId !== frameId ) {
  18219. uniformsGroupData.frameId = frameId;
  18220. return true;
  18221. }
  18222. return false;
  18223. }
  18224. // other groups are updated just when groupNode.needsUpdate is true
  18225. const groupChain = [ groupNode, nodeUniformsGroup ];
  18226. let groupData = this.groupsData.get( groupChain );
  18227. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  18228. if ( groupData.version !== groupNode.version ) {
  18229. groupData.version = groupNode.version;
  18230. return true;
  18231. }
  18232. return false;
  18233. }
  18234. getForRenderCacheKey( renderObject ) {
  18235. return renderObject.initialCacheKey;
  18236. }
  18237. getForRender( renderObject ) {
  18238. const renderObjectData = this.get( renderObject );
  18239. let nodeBuilderState = renderObjectData.nodeBuilderState;
  18240. if ( nodeBuilderState === undefined ) {
  18241. const { nodeBuilderCache } = this;
  18242. const cacheKey = this.getForRenderCacheKey( renderObject );
  18243. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  18244. if ( nodeBuilderState === undefined ) {
  18245. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  18246. nodeBuilder.scene = renderObject.scene;
  18247. nodeBuilder.material = renderObject.material;
  18248. nodeBuilder.camera = renderObject.camera;
  18249. nodeBuilder.context.material = renderObject.material;
  18250. nodeBuilder.lightsNode = renderObject.lightsNode;
  18251. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  18252. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  18253. nodeBuilder.clippingContext = renderObject.clippingContext;
  18254. nodeBuilder.build();
  18255. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  18256. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  18257. }
  18258. nodeBuilderState.usedTimes ++;
  18259. renderObjectData.nodeBuilderState = nodeBuilderState;
  18260. }
  18261. return nodeBuilderState;
  18262. }
  18263. delete( object ) {
  18264. if ( object.isRenderObject ) {
  18265. const nodeBuilderState = this.get( object ).nodeBuilderState;
  18266. nodeBuilderState.usedTimes --;
  18267. if ( nodeBuilderState.usedTimes === 0 ) {
  18268. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  18269. }
  18270. }
  18271. return super.delete( object );
  18272. }
  18273. getForCompute( computeNode ) {
  18274. const computeData = this.get( computeNode );
  18275. let nodeBuilderState = computeData.nodeBuilderState;
  18276. if ( nodeBuilderState === undefined ) {
  18277. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  18278. nodeBuilder.build();
  18279. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  18280. computeData.nodeBuilderState = nodeBuilderState;
  18281. }
  18282. return nodeBuilderState;
  18283. }
  18284. _createNodeBuilderState( nodeBuilder ) {
  18285. return new NodeBuilderState(
  18286. nodeBuilder.vertexShader,
  18287. nodeBuilder.fragmentShader,
  18288. nodeBuilder.computeShader,
  18289. nodeBuilder.getAttributesArray(),
  18290. nodeBuilder.getBindings(),
  18291. nodeBuilder.updateNodes,
  18292. nodeBuilder.updateBeforeNodes,
  18293. nodeBuilder.updateAfterNodes,
  18294. nodeBuilder.monitor,
  18295. nodeBuilder.transforms
  18296. );
  18297. }
  18298. getEnvironmentNode( scene ) {
  18299. return scene.environmentNode || this.get( scene ).environmentNode || null;
  18300. }
  18301. getBackgroundNode( scene ) {
  18302. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  18303. }
  18304. getFogNode( scene ) {
  18305. return scene.fogNode || this.get( scene ).fogNode || null;
  18306. }
  18307. getCacheKey( scene, lightsNode ) {
  18308. const chain = [ scene, lightsNode ];
  18309. const callId = this.renderer.info.calls;
  18310. let cacheKeyData = this.callHashCache.get( chain );
  18311. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  18312. const environmentNode = this.getEnvironmentNode( scene );
  18313. const fogNode = this.getFogNode( scene );
  18314. const values = [];
  18315. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  18316. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  18317. if ( fogNode ) values.push( fogNode.getCacheKey() );
  18318. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  18319. cacheKeyData = {
  18320. callId,
  18321. cacheKey: hashArray( values )
  18322. };
  18323. this.callHashCache.set( chain, cacheKeyData );
  18324. }
  18325. return cacheKeyData.cacheKey;
  18326. }
  18327. updateScene( scene ) {
  18328. this.updateEnvironment( scene );
  18329. this.updateFog( scene );
  18330. this.updateBackground( scene );
  18331. }
  18332. get isToneMappingState() {
  18333. return this.renderer.getRenderTarget() ? false : true;
  18334. }
  18335. updateBackground( scene ) {
  18336. const sceneData = this.get( scene );
  18337. const background = scene.background;
  18338. if ( background ) {
  18339. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  18340. if ( sceneData.background !== background || forceUpdate ) {
  18341. let backgroundNode = null;
  18342. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  18343. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  18344. backgroundNode = pmremTexture( background );
  18345. } else {
  18346. let envMap;
  18347. if ( background.isCubeTexture === true ) {
  18348. envMap = cubeTexture( background );
  18349. } else {
  18350. envMap = texture( background );
  18351. }
  18352. backgroundNode = cubeMapNode( envMap );
  18353. }
  18354. } else if ( background.isTexture === true ) {
  18355. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  18356. } else if ( background.isColor !== true ) {
  18357. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  18358. }
  18359. sceneData.backgroundNode = backgroundNode;
  18360. sceneData.background = background;
  18361. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  18362. }
  18363. } else if ( sceneData.backgroundNode ) {
  18364. delete sceneData.backgroundNode;
  18365. delete sceneData.background;
  18366. }
  18367. }
  18368. updateFog( scene ) {
  18369. const sceneData = this.get( scene );
  18370. const fog = scene.fog;
  18371. if ( fog ) {
  18372. if ( sceneData.fog !== fog ) {
  18373. let fogNode = null;
  18374. if ( fog.isFogExp2 ) {
  18375. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  18376. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  18377. fogNode = densityFog( color, density );
  18378. } else if ( fog.isFog ) {
  18379. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  18380. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  18381. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  18382. fogNode = rangeFog( color, near, far );
  18383. } else {
  18384. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  18385. }
  18386. sceneData.fogNode = fogNode;
  18387. sceneData.fog = fog;
  18388. }
  18389. } else {
  18390. delete sceneData.fogNode;
  18391. delete sceneData.fog;
  18392. }
  18393. }
  18394. updateEnvironment( scene ) {
  18395. const sceneData = this.get( scene );
  18396. const environment = scene.environment;
  18397. if ( environment ) {
  18398. if ( sceneData.environment !== environment ) {
  18399. let environmentNode = null;
  18400. if ( environment.isCubeTexture === true ) {
  18401. environmentNode = cubeTexture( environment );
  18402. } else if ( environment.isTexture === true ) {
  18403. environmentNode = texture( environment );
  18404. } else {
  18405. console.error( 'Nodes: Unsupported environment configuration.', environment );
  18406. }
  18407. sceneData.environmentNode = environmentNode;
  18408. sceneData.environment = environment;
  18409. }
  18410. } else if ( sceneData.environmentNode ) {
  18411. delete sceneData.environmentNode;
  18412. delete sceneData.environment;
  18413. }
  18414. }
  18415. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  18416. const nodeFrame = this.nodeFrame;
  18417. nodeFrame.renderer = renderer;
  18418. nodeFrame.scene = scene;
  18419. nodeFrame.object = object;
  18420. nodeFrame.camera = camera;
  18421. nodeFrame.material = material;
  18422. return nodeFrame;
  18423. }
  18424. getNodeFrameForRender( renderObject ) {
  18425. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  18426. }
  18427. getOutputCacheKey() {
  18428. const renderer = this.renderer;
  18429. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  18430. }
  18431. hasOutputChange( outputTarget ) {
  18432. const cacheKey = outputNodeMap.get( outputTarget );
  18433. return cacheKey !== this.getOutputCacheKey();
  18434. }
  18435. getOutputNode( outputTexture ) {
  18436. const renderer = this.renderer;
  18437. const cacheKey = this.getOutputCacheKey();
  18438. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  18439. outputNodeMap.set( outputTexture, cacheKey );
  18440. return output;
  18441. }
  18442. updateBefore( renderObject ) {
  18443. const nodeBuilder = renderObject.getNodeBuilderState();
  18444. for ( const node of nodeBuilder.updateBeforeNodes ) {
  18445. // update frame state for each node
  18446. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  18447. }
  18448. }
  18449. updateAfter( renderObject ) {
  18450. const nodeBuilder = renderObject.getNodeBuilderState();
  18451. for ( const node of nodeBuilder.updateAfterNodes ) {
  18452. // update frame state for each node
  18453. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  18454. }
  18455. }
  18456. updateForCompute( computeNode ) {
  18457. const nodeFrame = this.getNodeFrame();
  18458. const nodeBuilder = this.getForCompute( computeNode );
  18459. for ( const node of nodeBuilder.updateNodes ) {
  18460. nodeFrame.updateNode( node );
  18461. }
  18462. }
  18463. updateForRender( renderObject ) {
  18464. const nodeFrame = this.getNodeFrameForRender( renderObject );
  18465. const nodeBuilder = renderObject.getNodeBuilderState();
  18466. for ( const node of nodeBuilder.updateNodes ) {
  18467. nodeFrame.updateNode( node );
  18468. }
  18469. }
  18470. needsRefresh( renderObject ) {
  18471. const nodeFrame = this.getNodeFrameForRender( renderObject );
  18472. const monitor = renderObject.getMonitor();
  18473. return monitor.needsRefresh( renderObject, nodeFrame );
  18474. }
  18475. dispose() {
  18476. super.dispose();
  18477. this.nodeFrame = new NodeFrame();
  18478. this.nodeBuilderCache = new Map();
  18479. }
  18480. }
  18481. const _plane = /*@__PURE__*/ new Plane();
  18482. class ClippingContext {
  18483. constructor( parentContext = null ) {
  18484. this.version = 0;
  18485. this.clipIntersection = null;
  18486. this.cacheKey = '';
  18487. if ( parentContext === null ) {
  18488. this.intersectionPlanes = [];
  18489. this.unionPlanes = [];
  18490. this.viewNormalMatrix = new Matrix3();
  18491. this.clippingGroupContexts = new WeakMap();
  18492. this.shadowPass = false;
  18493. } else {
  18494. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  18495. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  18496. this.shadowPass = parentContext.shadowPass;
  18497. this.viewMatrix = parentContext.viewMatrix;
  18498. }
  18499. this.parentVersion = null;
  18500. }
  18501. projectPlanes( source, destination, offset ) {
  18502. const l = source.length;
  18503. for ( let i = 0; i < l; i ++ ) {
  18504. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  18505. const v = destination[ offset + i ];
  18506. const normal = _plane.normal;
  18507. v.x = - normal.x;
  18508. v.y = - normal.y;
  18509. v.z = - normal.z;
  18510. v.w = _plane.constant;
  18511. }
  18512. }
  18513. updateGlobal( scene, camera ) {
  18514. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  18515. this.viewMatrix = camera.matrixWorldInverse;
  18516. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  18517. }
  18518. update( parentContext, clippingGroup ) {
  18519. let update = false;
  18520. if ( parentContext.version !== this.parentVersion ) {
  18521. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  18522. this.unionPlanes = Array.from( parentContext.unionPlanes );
  18523. this.parentVersion = parentContext.version;
  18524. }
  18525. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  18526. this.clipIntersection = clippingGroup.clipIntersection;
  18527. if ( this.clipIntersection ) {
  18528. this.unionPlanes.length = parentContext.unionPlanes.length;
  18529. } else {
  18530. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  18531. }
  18532. }
  18533. const srcClippingPlanes = clippingGroup.clippingPlanes;
  18534. const l = srcClippingPlanes.length;
  18535. let dstClippingPlanes;
  18536. let offset;
  18537. if ( this.clipIntersection ) {
  18538. dstClippingPlanes = this.intersectionPlanes;
  18539. offset = parentContext.intersectionPlanes.length;
  18540. } else {
  18541. dstClippingPlanes = this.unionPlanes;
  18542. offset = parentContext.unionPlanes.length;
  18543. }
  18544. if ( dstClippingPlanes.length !== offset + l ) {
  18545. dstClippingPlanes.length = offset + l;
  18546. for ( let i = 0; i < l; i ++ ) {
  18547. dstClippingPlanes[ offset + i ] = new Vector4();
  18548. }
  18549. update = true;
  18550. }
  18551. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  18552. if ( update ) {
  18553. this.version ++;
  18554. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  18555. }
  18556. }
  18557. getGroupContext( clippingGroup ) {
  18558. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  18559. let context = this.clippingGroupContexts.get( clippingGroup );
  18560. if ( context === undefined ) {
  18561. context = new ClippingContext( this );
  18562. this.clippingGroupContexts.set( clippingGroup, context );
  18563. }
  18564. context.update( this, clippingGroup );
  18565. return context;
  18566. }
  18567. get unionClippingCount() {
  18568. return this.unionPlanes.length;
  18569. }
  18570. }
  18571. class RenderBundle {
  18572. constructor( scene, camera ) {
  18573. this.scene = scene;
  18574. this.camera = camera;
  18575. }
  18576. clone() {
  18577. return Object.assign( new this.constructor(), this );
  18578. }
  18579. }
  18580. class RenderBundles {
  18581. constructor() {
  18582. this.lists = new ChainMap();
  18583. }
  18584. get( scene, camera ) {
  18585. const lists = this.lists;
  18586. const keys = [ scene, camera ];
  18587. let list = lists.get( keys );
  18588. if ( list === undefined ) {
  18589. list = new RenderBundle( scene, camera );
  18590. lists.set( keys, list );
  18591. }
  18592. return list;
  18593. }
  18594. dispose() {
  18595. this.lists = new ChainMap();
  18596. }
  18597. }
  18598. class NodeLibrary {
  18599. constructor() {
  18600. this.lightNodes = new WeakMap();
  18601. this.materialNodes = new Map();
  18602. this.toneMappingNodes = new Map();
  18603. }
  18604. fromMaterial( material ) {
  18605. if ( material.isNodeMaterial ) return material;
  18606. let nodeMaterial = null;
  18607. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  18608. if ( nodeMaterialClass !== null ) {
  18609. nodeMaterial = new nodeMaterialClass();
  18610. for ( const key in material ) {
  18611. nodeMaterial[ key ] = material[ key ];
  18612. }
  18613. }
  18614. return nodeMaterial;
  18615. }
  18616. addToneMapping( toneMappingNode, toneMapping ) {
  18617. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  18618. }
  18619. getToneMappingFunction( toneMapping ) {
  18620. return this.toneMappingNodes.get( toneMapping ) || null;
  18621. }
  18622. getMaterialNodeClass( materialType ) {
  18623. return this.materialNodes.get( materialType ) || null;
  18624. }
  18625. addMaterial( materialNodeClass, materialClassType ) {
  18626. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  18627. }
  18628. getLightNodeClass( light ) {
  18629. return this.lightNodes.get( light ) || null;
  18630. }
  18631. addLight( lightNodeClass, lightClass ) {
  18632. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  18633. }
  18634. addType( nodeClass, type, library ) {
  18635. if ( library.has( type ) ) {
  18636. console.warn( `Redefinition of node ${ type }` );
  18637. return;
  18638. }
  18639. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  18640. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  18641. library.set( type, nodeClass );
  18642. }
  18643. addClass( nodeClass, baseClass, library ) {
  18644. if ( library.has( baseClass ) ) {
  18645. console.warn( `Redefinition of node ${ baseClass.name }` );
  18646. return;
  18647. }
  18648. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  18649. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  18650. library.set( baseClass, nodeClass );
  18651. }
  18652. }
  18653. const _defaultLights = /*@__PURE__*/ new LightsNode();
  18654. class Lighting extends ChainMap {
  18655. constructor() {
  18656. super();
  18657. }
  18658. createNode( lights = [] ) {
  18659. return new LightsNode().setLights( lights );
  18660. }
  18661. getNode( scene, camera ) {
  18662. // ignore post-processing
  18663. if ( scene.isQuadMesh ) return _defaultLights;
  18664. // tiled lighting
  18665. const keys = [ scene, camera ];
  18666. let node = this.get( keys );
  18667. if ( node === undefined ) {
  18668. node = this.createNode();
  18669. this.set( keys, node );
  18670. }
  18671. return node;
  18672. }
  18673. }
  18674. const _scene = /*@__PURE__*/ new Scene();
  18675. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  18676. const _screen = /*@__PURE__*/ new Vector4();
  18677. const _frustum = /*@__PURE__*/ new Frustum();
  18678. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  18679. const _vector4 = /*@__PURE__*/ new Vector4();
  18680. class Renderer {
  18681. constructor( backend, parameters = {} ) {
  18682. this.isRenderer = true;
  18683. //
  18684. const {
  18685. logarithmicDepthBuffer = false,
  18686. alpha = true,
  18687. depth = true,
  18688. stencil = false,
  18689. antialias = false,
  18690. samples = 0,
  18691. getFallback = null
  18692. } = parameters;
  18693. // public
  18694. this.domElement = backend.getDomElement();
  18695. this.backend = backend;
  18696. this.samples = samples || ( antialias === true ) ? 4 : 0;
  18697. this.autoClear = true;
  18698. this.autoClearColor = true;
  18699. this.autoClearDepth = true;
  18700. this.autoClearStencil = true;
  18701. this.alpha = alpha;
  18702. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  18703. this.outputColorSpace = SRGBColorSpace;
  18704. this.toneMapping = NoToneMapping;
  18705. this.toneMappingExposure = 1.0;
  18706. this.sortObjects = true;
  18707. this.depth = depth;
  18708. this.stencil = stencil;
  18709. this.info = new Info();
  18710. this.nodes = {
  18711. modelViewMatrix: null,
  18712. modelNormalViewMatrix: null
  18713. };
  18714. this.library = new NodeLibrary();
  18715. this.lighting = new Lighting();
  18716. // internals
  18717. this._getFallback = getFallback;
  18718. this._pixelRatio = 1;
  18719. this._width = this.domElement.width;
  18720. this._height = this.domElement.height;
  18721. this._viewport = new Vector4( 0, 0, this._width, this._height );
  18722. this._scissor = new Vector4( 0, 0, this._width, this._height );
  18723. this._scissorTest = false;
  18724. this._attributes = null;
  18725. this._geometries = null;
  18726. this._nodes = null;
  18727. this._animation = null;
  18728. this._bindings = null;
  18729. this._objects = null;
  18730. this._pipelines = null;
  18731. this._bundles = null;
  18732. this._renderLists = null;
  18733. this._renderContexts = null;
  18734. this._textures = null;
  18735. this._background = null;
  18736. this._quad = new QuadMesh( new NodeMaterial() );
  18737. this._quad.material.type = 'Renderer_output';
  18738. this._currentRenderContext = null;
  18739. this._opaqueSort = null;
  18740. this._transparentSort = null;
  18741. this._frameBufferTarget = null;
  18742. const alphaClear = this.alpha === true ? 0 : 1;
  18743. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  18744. this._clearDepth = 1;
  18745. this._clearStencil = 0;
  18746. this._renderTarget = null;
  18747. this._activeCubeFace = 0;
  18748. this._activeMipmapLevel = 0;
  18749. this._mrt = null;
  18750. this._renderObjectFunction = null;
  18751. this._currentRenderObjectFunction = null;
  18752. this._currentRenderBundle = null;
  18753. this._handleObjectFunction = this._renderObjectDirect;
  18754. this._isDeviceLost = false;
  18755. this.onDeviceLost = this._onDeviceLost;
  18756. this._initialized = false;
  18757. this._initPromise = null;
  18758. this._compilationPromises = null;
  18759. this.transparent = true;
  18760. this.opaque = true;
  18761. this.shadowMap = {
  18762. enabled: false,
  18763. type: PCFShadowMap
  18764. };
  18765. this.xr = {
  18766. enabled: false
  18767. };
  18768. this.debug = {
  18769. checkShaderErrors: true,
  18770. onShaderError: null,
  18771. getShaderAsync: async ( scene, camera, object ) => {
  18772. await this.compileAsync( scene, camera );
  18773. const renderList = this._renderLists.get( scene, camera );
  18774. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  18775. const material = scene.overrideMaterial || object.material;
  18776. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  18777. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  18778. return { fragmentShader, vertexShader };
  18779. }
  18780. };
  18781. }
  18782. async init() {
  18783. if ( this._initialized ) {
  18784. throw new Error( 'Renderer: Backend has already been initialized.' );
  18785. }
  18786. if ( this._initPromise !== null ) {
  18787. return this._initPromise;
  18788. }
  18789. this._initPromise = new Promise( async ( resolve, reject ) => {
  18790. let backend = this.backend;
  18791. try {
  18792. await backend.init( this );
  18793. } catch ( error ) {
  18794. if ( this._getFallback !== null ) {
  18795. // try the fallback
  18796. try {
  18797. this.backend = backend = this._getFallback( error );
  18798. await backend.init( this );
  18799. } catch ( error ) {
  18800. reject( error );
  18801. return;
  18802. }
  18803. } else {
  18804. reject( error );
  18805. return;
  18806. }
  18807. }
  18808. this._nodes = new Nodes( this, backend );
  18809. this._animation = new Animation( this._nodes, this.info );
  18810. this._attributes = new Attributes( backend );
  18811. this._background = new Background( this, this._nodes );
  18812. this._geometries = new Geometries( this._attributes, this.info );
  18813. this._textures = new Textures( this, backend, this.info );
  18814. this._pipelines = new Pipelines( backend, this._nodes );
  18815. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  18816. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  18817. this._renderLists = new RenderLists( this.lighting );
  18818. this._bundles = new RenderBundles();
  18819. this._renderContexts = new RenderContexts();
  18820. //
  18821. this._animation.start();
  18822. this._initialized = true;
  18823. resolve();
  18824. } );
  18825. return this._initPromise;
  18826. }
  18827. get coordinateSystem() {
  18828. return this.backend.coordinateSystem;
  18829. }
  18830. async compileAsync( scene, camera, targetScene = null ) {
  18831. if ( this._isDeviceLost === true ) return;
  18832. if ( this._initialized === false ) await this.init();
  18833. // preserve render tree
  18834. const nodeFrame = this._nodes.nodeFrame;
  18835. const previousRenderId = nodeFrame.renderId;
  18836. const previousRenderContext = this._currentRenderContext;
  18837. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  18838. const previousCompilationPromises = this._compilationPromises;
  18839. //
  18840. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  18841. if ( targetScene === null ) targetScene = scene;
  18842. const renderTarget = this._renderTarget;
  18843. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  18844. const activeMipmapLevel = this._activeMipmapLevel;
  18845. const compilationPromises = [];
  18846. this._currentRenderContext = renderContext;
  18847. this._currentRenderObjectFunction = this.renderObject;
  18848. this._handleObjectFunction = this._createObjectPipeline;
  18849. this._compilationPromises = compilationPromises;
  18850. nodeFrame.renderId ++;
  18851. //
  18852. nodeFrame.update();
  18853. //
  18854. renderContext.depth = this.depth;
  18855. renderContext.stencil = this.stencil;
  18856. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  18857. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  18858. //
  18859. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  18860. //
  18861. const renderList = this._renderLists.get( scene, camera );
  18862. renderList.begin();
  18863. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  18864. // include lights from target scene
  18865. if ( targetScene !== scene ) {
  18866. targetScene.traverseVisible( function ( object ) {
  18867. if ( object.isLight && object.layers.test( camera.layers ) ) {
  18868. renderList.pushLight( object );
  18869. }
  18870. } );
  18871. }
  18872. renderList.finish();
  18873. //
  18874. if ( renderTarget !== null ) {
  18875. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  18876. const renderTargetData = this._textures.get( renderTarget );
  18877. renderContext.textures = renderTargetData.textures;
  18878. renderContext.depthTexture = renderTargetData.depthTexture;
  18879. } else {
  18880. renderContext.textures = null;
  18881. renderContext.depthTexture = null;
  18882. }
  18883. //
  18884. this._nodes.updateScene( sceneRef );
  18885. //
  18886. this._background.update( sceneRef, renderList, renderContext );
  18887. // process render lists
  18888. const opaqueObjects = renderList.opaque;
  18889. const transparentObjects = renderList.transparent;
  18890. const transparentDoublePassObjects = renderList.transparentDoublePass;
  18891. const lightsNode = renderList.lightsNode;
  18892. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  18893. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  18894. // restore render tree
  18895. nodeFrame.renderId = previousRenderId;
  18896. this._currentRenderContext = previousRenderContext;
  18897. this._currentRenderObjectFunction = previousRenderObjectFunction;
  18898. this._compilationPromises = previousCompilationPromises;
  18899. this._handleObjectFunction = this._renderObjectDirect;
  18900. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  18901. await Promise.all( compilationPromises );
  18902. }
  18903. async renderAsync( scene, camera ) {
  18904. if ( this._initialized === false ) await this.init();
  18905. const renderContext = this._renderScene( scene, camera );
  18906. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  18907. }
  18908. async waitForGPU() {
  18909. await this.backend.waitForGPU();
  18910. }
  18911. setMRT( mrt ) {
  18912. this._mrt = mrt;
  18913. return this;
  18914. }
  18915. getMRT() {
  18916. return this._mrt;
  18917. }
  18918. _onDeviceLost( info ) {
  18919. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  18920. if ( info.reason ) {
  18921. errorMessage += `\nReason: ${info.reason}`;
  18922. }
  18923. console.error( errorMessage );
  18924. this._isDeviceLost = true;
  18925. }
  18926. _renderBundle( bundle, sceneRef, lightsNode ) {
  18927. const { bundleGroup, camera, renderList } = bundle;
  18928. const renderContext = this._currentRenderContext;
  18929. //
  18930. const renderBundle = this._bundles.get( bundleGroup, camera );
  18931. const renderBundleData = this.backend.get( renderBundle );
  18932. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  18933. //
  18934. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  18935. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  18936. renderBundleData.renderContexts.add( renderContext );
  18937. if ( renderBundleNeedsUpdate ) {
  18938. this.backend.beginBundle( renderContext );
  18939. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  18940. renderBundleData.renderObjects = [];
  18941. }
  18942. this._currentRenderBundle = renderBundle;
  18943. const opaqueObjects = renderList.opaque;
  18944. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  18945. this._currentRenderBundle = null;
  18946. //
  18947. this.backend.finishBundle( renderContext, renderBundle );
  18948. renderBundleData.version = bundleGroup.version;
  18949. } else {
  18950. const { renderObjects } = renderBundleData;
  18951. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  18952. const renderObject = renderObjects[ i ];
  18953. if ( this._nodes.needsRefresh( renderObject ) ) {
  18954. this._nodes.updateBefore( renderObject );
  18955. this._nodes.updateForRender( renderObject );
  18956. this._bindings.updateForRender( renderObject );
  18957. this._nodes.updateAfter( renderObject );
  18958. }
  18959. }
  18960. }
  18961. this.backend.addBundle( renderContext, renderBundle );
  18962. }
  18963. render( scene, camera ) {
  18964. if ( this._initialized === false ) {
  18965. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  18966. return this.renderAsync( scene, camera );
  18967. }
  18968. this._renderScene( scene, camera );
  18969. }
  18970. _getFrameBufferTarget() {
  18971. const { currentToneMapping, currentColorSpace } = this;
  18972. const useToneMapping = currentToneMapping !== NoToneMapping;
  18973. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  18974. if ( useToneMapping === false && useColorSpace === false ) return null;
  18975. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  18976. const { depth, stencil } = this;
  18977. let frameBufferTarget = this._frameBufferTarget;
  18978. if ( frameBufferTarget === null ) {
  18979. frameBufferTarget = new RenderTarget( width, height, {
  18980. depthBuffer: depth,
  18981. stencilBuffer: stencil,
  18982. type: HalfFloatType, // FloatType
  18983. format: RGBAFormat,
  18984. colorSpace: LinearSRGBColorSpace,
  18985. generateMipmaps: false,
  18986. minFilter: LinearFilter,
  18987. magFilter: LinearFilter,
  18988. samples: this.samples
  18989. } );
  18990. frameBufferTarget.isPostProcessingRenderTarget = true;
  18991. this._frameBufferTarget = frameBufferTarget;
  18992. }
  18993. frameBufferTarget.depthBuffer = depth;
  18994. frameBufferTarget.stencilBuffer = stencil;
  18995. frameBufferTarget.setSize( width, height );
  18996. frameBufferTarget.viewport.copy( this._viewport );
  18997. frameBufferTarget.scissor.copy( this._scissor );
  18998. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  18999. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  19000. frameBufferTarget.scissorTest = this._scissorTest;
  19001. return frameBufferTarget;
  19002. }
  19003. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  19004. if ( this._isDeviceLost === true ) return;
  19005. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  19006. // preserve render tree
  19007. const nodeFrame = this._nodes.nodeFrame;
  19008. const previousRenderId = nodeFrame.renderId;
  19009. const previousRenderContext = this._currentRenderContext;
  19010. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  19011. //
  19012. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  19013. const outputRenderTarget = this._renderTarget;
  19014. const activeCubeFace = this._activeCubeFace;
  19015. const activeMipmapLevel = this._activeMipmapLevel;
  19016. //
  19017. let renderTarget;
  19018. if ( frameBufferTarget !== null ) {
  19019. renderTarget = frameBufferTarget;
  19020. this.setRenderTarget( renderTarget );
  19021. } else {
  19022. renderTarget = outputRenderTarget;
  19023. }
  19024. //
  19025. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  19026. this._currentRenderContext = renderContext;
  19027. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  19028. //
  19029. this.info.calls ++;
  19030. this.info.render.calls ++;
  19031. this.info.render.frameCalls ++;
  19032. nodeFrame.renderId = this.info.calls;
  19033. //
  19034. const coordinateSystem = this.coordinateSystem;
  19035. if ( camera.coordinateSystem !== coordinateSystem ) {
  19036. camera.coordinateSystem = coordinateSystem;
  19037. camera.updateProjectionMatrix();
  19038. }
  19039. //
  19040. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  19041. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  19042. //
  19043. let viewport = this._viewport;
  19044. let scissor = this._scissor;
  19045. let pixelRatio = this._pixelRatio;
  19046. if ( renderTarget !== null ) {
  19047. viewport = renderTarget.viewport;
  19048. scissor = renderTarget.scissor;
  19049. pixelRatio = 1;
  19050. }
  19051. this.getDrawingBufferSize( _drawingBufferSize );
  19052. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  19053. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  19054. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  19055. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  19056. renderContext.viewportValue.width >>= activeMipmapLevel;
  19057. renderContext.viewportValue.height >>= activeMipmapLevel;
  19058. renderContext.viewportValue.minDepth = minDepth;
  19059. renderContext.viewportValue.maxDepth = maxDepth;
  19060. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  19061. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  19062. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  19063. renderContext.scissorValue.width >>= activeMipmapLevel;
  19064. renderContext.scissorValue.height >>= activeMipmapLevel;
  19065. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  19066. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  19067. //
  19068. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  19069. //
  19070. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  19071. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  19072. const renderList = this._renderLists.get( scene, camera );
  19073. renderList.begin();
  19074. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  19075. renderList.finish();
  19076. if ( this.sortObjects === true ) {
  19077. renderList.sort( this._opaqueSort, this._transparentSort );
  19078. }
  19079. //
  19080. if ( renderTarget !== null ) {
  19081. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  19082. const renderTargetData = this._textures.get( renderTarget );
  19083. renderContext.textures = renderTargetData.textures;
  19084. renderContext.depthTexture = renderTargetData.depthTexture;
  19085. renderContext.width = renderTargetData.width;
  19086. renderContext.height = renderTargetData.height;
  19087. renderContext.renderTarget = renderTarget;
  19088. renderContext.depth = renderTarget.depthBuffer;
  19089. renderContext.stencil = renderTarget.stencilBuffer;
  19090. } else {
  19091. renderContext.textures = null;
  19092. renderContext.depthTexture = null;
  19093. renderContext.width = this.domElement.width;
  19094. renderContext.height = this.domElement.height;
  19095. renderContext.depth = this.depth;
  19096. renderContext.stencil = this.stencil;
  19097. }
  19098. renderContext.width >>= activeMipmapLevel;
  19099. renderContext.height >>= activeMipmapLevel;
  19100. renderContext.activeCubeFace = activeCubeFace;
  19101. renderContext.activeMipmapLevel = activeMipmapLevel;
  19102. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  19103. //
  19104. this._nodes.updateScene( sceneRef );
  19105. //
  19106. this._background.update( sceneRef, renderList, renderContext );
  19107. //
  19108. this.backend.beginRender( renderContext );
  19109. // process render lists
  19110. const {
  19111. bundles,
  19112. lightsNode,
  19113. transparentDoublePass: transparentDoublePassObjects,
  19114. transparent: transparentObjects,
  19115. opaque: opaqueObjects
  19116. } = renderList;
  19117. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  19118. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  19119. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  19120. // finish render pass
  19121. this.backend.finishRender( renderContext );
  19122. // restore render tree
  19123. nodeFrame.renderId = previousRenderId;
  19124. this._currentRenderContext = previousRenderContext;
  19125. this._currentRenderObjectFunction = previousRenderObjectFunction;
  19126. //
  19127. if ( frameBufferTarget !== null ) {
  19128. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  19129. const quad = this._quad;
  19130. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  19131. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  19132. quad.material.needsUpdate = true;
  19133. }
  19134. this._renderScene( quad, quad.camera, false );
  19135. }
  19136. //
  19137. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  19138. //
  19139. return renderContext;
  19140. }
  19141. getMaxAnisotropy() {
  19142. return this.backend.getMaxAnisotropy();
  19143. }
  19144. getActiveCubeFace() {
  19145. return this._activeCubeFace;
  19146. }
  19147. getActiveMipmapLevel() {
  19148. return this._activeMipmapLevel;
  19149. }
  19150. async setAnimationLoop( callback ) {
  19151. if ( this._initialized === false ) await this.init();
  19152. this._animation.setAnimationLoop( callback );
  19153. }
  19154. async getArrayBufferAsync( attribute ) {
  19155. return await this.backend.getArrayBufferAsync( attribute );
  19156. }
  19157. getContext() {
  19158. return this.backend.getContext();
  19159. }
  19160. getPixelRatio() {
  19161. return this._pixelRatio;
  19162. }
  19163. getDrawingBufferSize( target ) {
  19164. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  19165. }
  19166. getSize( target ) {
  19167. return target.set( this._width, this._height );
  19168. }
  19169. setPixelRatio( value = 1 ) {
  19170. if ( this._pixelRatio === value ) return;
  19171. this._pixelRatio = value;
  19172. this.setSize( this._width, this._height, false );
  19173. }
  19174. setDrawingBufferSize( width, height, pixelRatio ) {
  19175. this._width = width;
  19176. this._height = height;
  19177. this._pixelRatio = pixelRatio;
  19178. this.domElement.width = Math.floor( width * pixelRatio );
  19179. this.domElement.height = Math.floor( height * pixelRatio );
  19180. this.setViewport( 0, 0, width, height );
  19181. if ( this._initialized ) this.backend.updateSize();
  19182. }
  19183. setSize( width, height, updateStyle = true ) {
  19184. this._width = width;
  19185. this._height = height;
  19186. this.domElement.width = Math.floor( width * this._pixelRatio );
  19187. this.domElement.height = Math.floor( height * this._pixelRatio );
  19188. if ( updateStyle === true ) {
  19189. this.domElement.style.width = width + 'px';
  19190. this.domElement.style.height = height + 'px';
  19191. }
  19192. this.setViewport( 0, 0, width, height );
  19193. if ( this._initialized ) this.backend.updateSize();
  19194. }
  19195. setOpaqueSort( method ) {
  19196. this._opaqueSort = method;
  19197. }
  19198. setTransparentSort( method ) {
  19199. this._transparentSort = method;
  19200. }
  19201. getScissor( target ) {
  19202. const scissor = this._scissor;
  19203. target.x = scissor.x;
  19204. target.y = scissor.y;
  19205. target.width = scissor.width;
  19206. target.height = scissor.height;
  19207. return target;
  19208. }
  19209. setScissor( x, y, width, height ) {
  19210. const scissor = this._scissor;
  19211. if ( x.isVector4 ) {
  19212. scissor.copy( x );
  19213. } else {
  19214. scissor.set( x, y, width, height );
  19215. }
  19216. }
  19217. getScissorTest() {
  19218. return this._scissorTest;
  19219. }
  19220. setScissorTest( boolean ) {
  19221. this._scissorTest = boolean;
  19222. this.backend.setScissorTest( boolean );
  19223. }
  19224. getViewport( target ) {
  19225. return target.copy( this._viewport );
  19226. }
  19227. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  19228. const viewport = this._viewport;
  19229. if ( x.isVector4 ) {
  19230. viewport.copy( x );
  19231. } else {
  19232. viewport.set( x, y, width, height );
  19233. }
  19234. viewport.minDepth = minDepth;
  19235. viewport.maxDepth = maxDepth;
  19236. }
  19237. getClearColor( target ) {
  19238. return target.copy( this._clearColor );
  19239. }
  19240. setClearColor( color, alpha = 1 ) {
  19241. this._clearColor.set( color );
  19242. this._clearColor.a = alpha;
  19243. }
  19244. getClearAlpha() {
  19245. return this._clearColor.a;
  19246. }
  19247. setClearAlpha( alpha ) {
  19248. this._clearColor.a = alpha;
  19249. }
  19250. getClearDepth() {
  19251. return this._clearDepth;
  19252. }
  19253. setClearDepth( depth ) {
  19254. this._clearDepth = depth;
  19255. }
  19256. getClearStencil() {
  19257. return this._clearStencil;
  19258. }
  19259. setClearStencil( stencil ) {
  19260. this._clearStencil = stencil;
  19261. }
  19262. isOccluded( object ) {
  19263. const renderContext = this._currentRenderContext;
  19264. return renderContext && this.backend.isOccluded( renderContext, object );
  19265. }
  19266. clear( color = true, depth = true, stencil = true ) {
  19267. if ( this._initialized === false ) {
  19268. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  19269. return this.clearAsync( color, depth, stencil );
  19270. }
  19271. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  19272. let renderTargetData = null;
  19273. if ( renderTarget !== null ) {
  19274. this._textures.updateRenderTarget( renderTarget );
  19275. renderTargetData = this._textures.get( renderTarget );
  19276. }
  19277. this.backend.clear( color, depth, stencil, renderTargetData );
  19278. if ( renderTarget !== null && this._renderTarget === null ) {
  19279. // If a color space transform or tone mapping is required,
  19280. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  19281. const quad = this._quad;
  19282. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  19283. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  19284. quad.material.needsUpdate = true;
  19285. }
  19286. this._renderScene( quad, quad.camera, false );
  19287. }
  19288. }
  19289. clearColor() {
  19290. return this.clear( true, false, false );
  19291. }
  19292. clearDepth() {
  19293. return this.clear( false, true, false );
  19294. }
  19295. clearStencil() {
  19296. return this.clear( false, false, true );
  19297. }
  19298. async clearAsync( color = true, depth = true, stencil = true ) {
  19299. if ( this._initialized === false ) await this.init();
  19300. this.clear( color, depth, stencil );
  19301. }
  19302. clearColorAsync() {
  19303. return this.clearAsync( true, false, false );
  19304. }
  19305. clearDepthAsync() {
  19306. return this.clearAsync( false, true, false );
  19307. }
  19308. clearStencilAsync() {
  19309. return this.clearAsync( false, false, true );
  19310. }
  19311. get currentToneMapping() {
  19312. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  19313. }
  19314. get currentColorSpace() {
  19315. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  19316. }
  19317. dispose() {
  19318. this.info.dispose();
  19319. this.backend.dispose();
  19320. this._animation.dispose();
  19321. this._objects.dispose();
  19322. this._pipelines.dispose();
  19323. this._nodes.dispose();
  19324. this._bindings.dispose();
  19325. this._renderLists.dispose();
  19326. this._renderContexts.dispose();
  19327. this._textures.dispose();
  19328. this.setRenderTarget( null );
  19329. this.setAnimationLoop( null );
  19330. }
  19331. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  19332. this._renderTarget = renderTarget;
  19333. this._activeCubeFace = activeCubeFace;
  19334. this._activeMipmapLevel = activeMipmapLevel;
  19335. }
  19336. getRenderTarget() {
  19337. return this._renderTarget;
  19338. }
  19339. setRenderObjectFunction( renderObjectFunction ) {
  19340. this._renderObjectFunction = renderObjectFunction;
  19341. }
  19342. getRenderObjectFunction() {
  19343. return this._renderObjectFunction;
  19344. }
  19345. compute( computeNodes ) {
  19346. if ( this.isDeviceLost === true ) return;
  19347. if ( this._initialized === false ) {
  19348. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  19349. return this.computeAsync( computeNodes );
  19350. }
  19351. //
  19352. const nodeFrame = this._nodes.nodeFrame;
  19353. const previousRenderId = nodeFrame.renderId;
  19354. //
  19355. this.info.calls ++;
  19356. this.info.compute.calls ++;
  19357. this.info.compute.frameCalls ++;
  19358. nodeFrame.renderId = this.info.calls;
  19359. //
  19360. const backend = this.backend;
  19361. const pipelines = this._pipelines;
  19362. const bindings = this._bindings;
  19363. const nodes = this._nodes;
  19364. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  19365. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  19366. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  19367. }
  19368. backend.beginCompute( computeNodes );
  19369. for ( const computeNode of computeList ) {
  19370. // onInit
  19371. if ( pipelines.has( computeNode ) === false ) {
  19372. const dispose = () => {
  19373. computeNode.removeEventListener( 'dispose', dispose );
  19374. pipelines.delete( computeNode );
  19375. bindings.delete( computeNode );
  19376. nodes.delete( computeNode );
  19377. };
  19378. computeNode.addEventListener( 'dispose', dispose );
  19379. //
  19380. const onInitFn = computeNode.onInitFunction;
  19381. if ( onInitFn !== null ) {
  19382. onInitFn.call( computeNode, { renderer: this } );
  19383. }
  19384. }
  19385. nodes.updateForCompute( computeNode );
  19386. bindings.updateForCompute( computeNode );
  19387. const computeBindings = bindings.getForCompute( computeNode );
  19388. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  19389. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  19390. }
  19391. backend.finishCompute( computeNodes );
  19392. //
  19393. nodeFrame.renderId = previousRenderId;
  19394. }
  19395. async computeAsync( computeNodes ) {
  19396. if ( this._initialized === false ) await this.init();
  19397. this.compute( computeNodes );
  19398. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  19399. }
  19400. async hasFeatureAsync( name ) {
  19401. if ( this._initialized === false ) await this.init();
  19402. return this.backend.hasFeature( name );
  19403. }
  19404. hasFeature( name ) {
  19405. if ( this._initialized === false ) {
  19406. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  19407. return false;
  19408. }
  19409. return this.backend.hasFeature( name );
  19410. }
  19411. hasInitialized() {
  19412. return this._initialized;
  19413. }
  19414. async initTextureAsync( texture ) {
  19415. if ( this._initialized === false ) await this.init();
  19416. this._textures.updateTexture( texture );
  19417. }
  19418. initTexture( texture ) {
  19419. if ( this._initialized === false ) {
  19420. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  19421. return false;
  19422. }
  19423. this._textures.updateTexture( texture );
  19424. }
  19425. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  19426. if ( rectangle !== null ) {
  19427. if ( rectangle.isVector2 ) {
  19428. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  19429. } else if ( rectangle.isVector4 ) {
  19430. rectangle = _vector4.copy( rectangle ).floor();
  19431. } else {
  19432. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  19433. return;
  19434. }
  19435. } else {
  19436. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  19437. }
  19438. //
  19439. let renderContext = this._currentRenderContext;
  19440. let renderTarget;
  19441. if ( renderContext !== null ) {
  19442. renderTarget = renderContext.renderTarget;
  19443. } else {
  19444. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  19445. if ( renderTarget !== null ) {
  19446. this._textures.updateRenderTarget( renderTarget );
  19447. renderContext = this._textures.get( renderTarget );
  19448. }
  19449. }
  19450. //
  19451. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  19452. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  19453. }
  19454. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  19455. this._textures.updateTexture( srcTexture );
  19456. this._textures.updateTexture( dstTexture );
  19457. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  19458. }
  19459. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  19460. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  19461. }
  19462. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  19463. if ( object.visible === false ) return;
  19464. const visible = object.layers.test( camera.layers );
  19465. if ( visible ) {
  19466. if ( object.isGroup ) {
  19467. groupOrder = object.renderOrder;
  19468. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  19469. } else if ( object.isLOD ) {
  19470. if ( object.autoUpdate === true ) object.update( camera );
  19471. } else if ( object.isLight ) {
  19472. renderList.pushLight( object );
  19473. } else if ( object.isSprite ) {
  19474. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  19475. if ( this.sortObjects === true ) {
  19476. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  19477. }
  19478. const { geometry, material } = object;
  19479. if ( material.visible ) {
  19480. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  19481. }
  19482. }
  19483. } else if ( object.isLineLoop ) {
  19484. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  19485. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  19486. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  19487. const { geometry, material } = object;
  19488. if ( this.sortObjects === true ) {
  19489. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19490. _vector4
  19491. .copy( geometry.boundingSphere.center )
  19492. .applyMatrix4( object.matrixWorld )
  19493. .applyMatrix4( _projScreenMatrix );
  19494. }
  19495. if ( Array.isArray( material ) ) {
  19496. const groups = geometry.groups;
  19497. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  19498. const group = groups[ i ];
  19499. const groupMaterial = material[ group.materialIndex ];
  19500. if ( groupMaterial && groupMaterial.visible ) {
  19501. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  19502. }
  19503. }
  19504. } else if ( material.visible ) {
  19505. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  19506. }
  19507. }
  19508. }
  19509. }
  19510. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  19511. const baseRenderList = renderList;
  19512. // replace render list
  19513. renderList = this._renderLists.get( object, camera );
  19514. renderList.begin();
  19515. baseRenderList.pushBundle( {
  19516. bundleGroup: object,
  19517. camera,
  19518. renderList,
  19519. } );
  19520. renderList.finish();
  19521. }
  19522. const children = object.children;
  19523. for ( let i = 0, l = children.length; i < l; i ++ ) {
  19524. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  19525. }
  19526. }
  19527. _renderBundles( bundles, sceneRef, lightsNode ) {
  19528. for ( const bundle of bundles ) {
  19529. this._renderBundle( bundle, sceneRef, lightsNode );
  19530. }
  19531. }
  19532. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  19533. if ( doublePassList.length > 0 ) {
  19534. // render back side
  19535. for ( const { material } of doublePassList ) {
  19536. material.side = BackSide;
  19537. }
  19538. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  19539. // render front side
  19540. for ( const { material } of doublePassList ) {
  19541. material.side = FrontSide;
  19542. }
  19543. this._renderObjects( renderList, camera, scene, lightsNode );
  19544. // restore
  19545. for ( const { material } of doublePassList ) {
  19546. material.side = DoubleSide;
  19547. }
  19548. } else {
  19549. this._renderObjects( renderList, camera, scene, lightsNode );
  19550. }
  19551. }
  19552. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  19553. // process renderable objects
  19554. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  19555. const renderItem = renderList[ i ];
  19556. // @TODO: Add support for multiple materials per object. This will require to extract
  19557. // the material from the renderItem object and pass it with its group data to renderObject().
  19558. const { object, geometry, material, group, clippingContext } = renderItem;
  19559. if ( camera.isArrayCamera ) {
  19560. const cameras = camera.cameras;
  19561. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  19562. const camera2 = cameras[ j ];
  19563. if ( object.layers.test( camera2.layers ) ) {
  19564. const vp = camera2.viewport;
  19565. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  19566. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  19567. const viewportValue = this._currentRenderContext.viewportValue;
  19568. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  19569. viewportValue.minDepth = minDepth;
  19570. viewportValue.maxDepth = maxDepth;
  19571. this.backend.updateViewport( this._currentRenderContext );
  19572. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  19573. }
  19574. }
  19575. } else {
  19576. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  19577. }
  19578. }
  19579. }
  19580. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  19581. let overridePositionNode;
  19582. let overrideColorNode;
  19583. let overrideDepthNode;
  19584. //
  19585. object.onBeforeRender( this, scene, camera, geometry, material, group );
  19586. //
  19587. if ( scene.overrideMaterial !== null ) {
  19588. const overrideMaterial = scene.overrideMaterial;
  19589. if ( material.positionNode && material.positionNode.isNode ) {
  19590. overridePositionNode = overrideMaterial.positionNode;
  19591. overrideMaterial.positionNode = material.positionNode;
  19592. }
  19593. overrideMaterial.alphaTest = material.alphaTest;
  19594. overrideMaterial.alphaMap = material.alphaMap;
  19595. if ( overrideMaterial.isShadowNodeMaterial ) {
  19596. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  19597. if ( material.depthNode && material.depthNode.isNode ) {
  19598. overrideDepthNode = overrideMaterial.depthNode;
  19599. overrideMaterial.depthNode = material.depthNode;
  19600. }
  19601. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  19602. overrideColorNode = overrideMaterial.colorNode;
  19603. overrideMaterial.colorNode = material.castShadowNode;
  19604. }
  19605. }
  19606. material = overrideMaterial;
  19607. }
  19608. //
  19609. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  19610. material.side = BackSide;
  19611. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  19612. material.side = FrontSide;
  19613. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  19614. material.side = DoubleSide;
  19615. } else {
  19616. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  19617. }
  19618. //
  19619. if ( overridePositionNode !== undefined ) {
  19620. scene.overrideMaterial.positionNode = overridePositionNode;
  19621. }
  19622. if ( overrideDepthNode !== undefined ) {
  19623. scene.overrideMaterial.depthNode = overrideDepthNode;
  19624. }
  19625. if ( overrideColorNode !== undefined ) {
  19626. scene.overrideMaterial.colorNode = overrideColorNode;
  19627. }
  19628. //
  19629. object.onAfterRender( this, scene, camera, geometry, material, group );
  19630. }
  19631. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  19632. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  19633. renderObject.drawRange = object.geometry.drawRange;
  19634. renderObject.group = group;
  19635. //
  19636. const needsRefresh = this._nodes.needsRefresh( renderObject );
  19637. if ( needsRefresh ) {
  19638. this._nodes.updateBefore( renderObject );
  19639. this._geometries.updateForRender( renderObject );
  19640. this._nodes.updateForRender( renderObject );
  19641. this._bindings.updateForRender( renderObject );
  19642. }
  19643. this._pipelines.updateForRender( renderObject );
  19644. //
  19645. if ( this._currentRenderBundle !== null ) {
  19646. const renderBundleData = this.backend.get( this._currentRenderBundle );
  19647. renderBundleData.renderObjects.push( renderObject );
  19648. renderObject.bundle = this._currentRenderBundle.scene;
  19649. }
  19650. this.backend.draw( renderObject, this.info );
  19651. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  19652. }
  19653. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  19654. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  19655. //
  19656. this._nodes.updateBefore( renderObject );
  19657. this._geometries.updateForRender( renderObject );
  19658. this._nodes.updateForRender( renderObject );
  19659. this._bindings.updateForRender( renderObject );
  19660. this._pipelines.getForRender( renderObject, this._compilationPromises );
  19661. this._nodes.updateAfter( renderObject );
  19662. }
  19663. get compile() {
  19664. return this.compileAsync;
  19665. }
  19666. }
  19667. class Binding {
  19668. constructor( name = '' ) {
  19669. this.name = name;
  19670. this.visibility = 0;
  19671. }
  19672. setVisibility( visibility ) {
  19673. this.visibility |= visibility;
  19674. }
  19675. clone() {
  19676. return Object.assign( new this.constructor(), this );
  19677. }
  19678. }
  19679. function getFloatLength( floatLength ) {
  19680. // ensure chunk size alignment (STD140 layout)
  19681. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  19682. }
  19683. class Buffer extends Binding {
  19684. constructor( name, buffer = null ) {
  19685. super( name );
  19686. this.isBuffer = true;
  19687. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  19688. this._buffer = buffer;
  19689. }
  19690. get byteLength() {
  19691. return getFloatLength( this._buffer.byteLength );
  19692. }
  19693. get buffer() {
  19694. return this._buffer;
  19695. }
  19696. update() {
  19697. return true;
  19698. }
  19699. }
  19700. class UniformBuffer extends Buffer {
  19701. constructor( name, buffer = null ) {
  19702. super( name, buffer );
  19703. this.isUniformBuffer = true;
  19704. }
  19705. }
  19706. let _id$4 = 0;
  19707. class NodeUniformBuffer extends UniformBuffer {
  19708. constructor( nodeUniform, groupNode ) {
  19709. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  19710. this.nodeUniform = nodeUniform;
  19711. this.groupNode = groupNode;
  19712. }
  19713. get buffer() {
  19714. return this.nodeUniform.value;
  19715. }
  19716. }
  19717. class UniformsGroup extends UniformBuffer {
  19718. constructor( name ) {
  19719. super( name );
  19720. this.isUniformsGroup = true;
  19721. this._values = null;
  19722. // the order of uniforms in this array must match the order of uniforms in the shader
  19723. this.uniforms = [];
  19724. }
  19725. addUniform( uniform ) {
  19726. this.uniforms.push( uniform );
  19727. return this;
  19728. }
  19729. removeUniform( uniform ) {
  19730. const index = this.uniforms.indexOf( uniform );
  19731. if ( index !== - 1 ) {
  19732. this.uniforms.splice( index, 1 );
  19733. }
  19734. return this;
  19735. }
  19736. get values() {
  19737. if ( this._values === null ) {
  19738. this._values = Array.from( this.buffer );
  19739. }
  19740. return this._values;
  19741. }
  19742. get buffer() {
  19743. let buffer = this._buffer;
  19744. if ( buffer === null ) {
  19745. const byteLength = this.byteLength;
  19746. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  19747. this._buffer = buffer;
  19748. }
  19749. return buffer;
  19750. }
  19751. get byteLength() {
  19752. let offset = 0; // global buffer offset in bytes
  19753. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  19754. const uniform = this.uniforms[ i ];
  19755. const { boundary, itemSize } = uniform;
  19756. // offset within a single chunk in bytes
  19757. const chunkOffset = offset % GPU_CHUNK_BYTES;
  19758. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  19759. // conformance tests
  19760. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  19761. // check for chunk overflow
  19762. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  19763. } else if ( chunkOffset % boundary !== 0 ) {
  19764. // check for correct alignment
  19765. offset += ( chunkOffset % boundary );
  19766. }
  19767. uniform.offset = ( offset / this.bytesPerElement );
  19768. offset += ( itemSize * this.bytesPerElement );
  19769. }
  19770. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  19771. }
  19772. update() {
  19773. let updated = false;
  19774. for ( const uniform of this.uniforms ) {
  19775. if ( this.updateByType( uniform ) === true ) {
  19776. updated = true;
  19777. }
  19778. }
  19779. return updated;
  19780. }
  19781. updateByType( uniform ) {
  19782. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  19783. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  19784. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  19785. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  19786. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  19787. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  19788. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  19789. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  19790. }
  19791. updateNumber( uniform ) {
  19792. let updated = false;
  19793. const a = this.values;
  19794. const v = uniform.getValue();
  19795. const offset = uniform.offset;
  19796. const type = uniform.getType();
  19797. if ( a[ offset ] !== v ) {
  19798. const b = this._getBufferForType( type );
  19799. b[ offset ] = a[ offset ] = v;
  19800. updated = true;
  19801. }
  19802. return updated;
  19803. }
  19804. updateVector2( uniform ) {
  19805. let updated = false;
  19806. const a = this.values;
  19807. const v = uniform.getValue();
  19808. const offset = uniform.offset;
  19809. const type = uniform.getType();
  19810. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  19811. const b = this._getBufferForType( type );
  19812. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  19813. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  19814. updated = true;
  19815. }
  19816. return updated;
  19817. }
  19818. updateVector3( uniform ) {
  19819. let updated = false;
  19820. const a = this.values;
  19821. const v = uniform.getValue();
  19822. const offset = uniform.offset;
  19823. const type = uniform.getType();
  19824. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  19825. const b = this._getBufferForType( type );
  19826. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  19827. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  19828. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  19829. updated = true;
  19830. }
  19831. return updated;
  19832. }
  19833. updateVector4( uniform ) {
  19834. let updated = false;
  19835. const a = this.values;
  19836. const v = uniform.getValue();
  19837. const offset = uniform.offset;
  19838. const type = uniform.getType();
  19839. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  19840. const b = this._getBufferForType( type );
  19841. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  19842. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  19843. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  19844. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  19845. updated = true;
  19846. }
  19847. return updated;
  19848. }
  19849. updateColor( uniform ) {
  19850. let updated = false;
  19851. const a = this.values;
  19852. const c = uniform.getValue();
  19853. const offset = uniform.offset;
  19854. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  19855. const b = this.buffer;
  19856. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  19857. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  19858. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  19859. updated = true;
  19860. }
  19861. return updated;
  19862. }
  19863. updateMatrix3( uniform ) {
  19864. let updated = false;
  19865. const a = this.values;
  19866. const e = uniform.getValue().elements;
  19867. const offset = uniform.offset;
  19868. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  19869. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  19870. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  19871. const b = this.buffer;
  19872. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  19873. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  19874. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  19875. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  19876. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  19877. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  19878. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  19879. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  19880. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  19881. updated = true;
  19882. }
  19883. return updated;
  19884. }
  19885. updateMatrix4( uniform ) {
  19886. let updated = false;
  19887. const a = this.values;
  19888. const e = uniform.getValue().elements;
  19889. const offset = uniform.offset;
  19890. if ( arraysEqual( a, e, offset ) === false ) {
  19891. const b = this.buffer;
  19892. b.set( e, offset );
  19893. setArray( a, e, offset );
  19894. updated = true;
  19895. }
  19896. return updated;
  19897. }
  19898. _getBufferForType( type ) {
  19899. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  19900. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  19901. return this.buffer;
  19902. }
  19903. }
  19904. function setArray( a, b, offset ) {
  19905. for ( let i = 0, l = b.length; i < l; i ++ ) {
  19906. a[ offset + i ] = b[ i ];
  19907. }
  19908. }
  19909. function arraysEqual( a, b, offset ) {
  19910. for ( let i = 0, l = b.length; i < l; i ++ ) {
  19911. if ( a[ offset + i ] !== b[ i ] ) return false;
  19912. }
  19913. return true;
  19914. }
  19915. let _id$3 = 0;
  19916. class NodeUniformsGroup extends UniformsGroup {
  19917. constructor( name, groupNode ) {
  19918. super( name );
  19919. this.id = _id$3 ++;
  19920. this.groupNode = groupNode;
  19921. this.isNodeUniformsGroup = true;
  19922. }
  19923. getNodes() {
  19924. const nodes = [];
  19925. for ( const uniform of this.uniforms ) {
  19926. const node = uniform.nodeUniform.node;
  19927. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  19928. nodes.push( node );
  19929. }
  19930. return nodes;
  19931. }
  19932. }
  19933. let _id$2 = 0;
  19934. class SampledTexture extends Binding {
  19935. constructor( name, texture ) {
  19936. super( name );
  19937. this.id = _id$2 ++;
  19938. this.texture = texture;
  19939. this.version = texture ? texture.version : 0;
  19940. this.store = false;
  19941. this.generation = null;
  19942. this.isSampledTexture = true;
  19943. }
  19944. needsBindingsUpdate( generation ) {
  19945. const { texture } = this;
  19946. if ( generation !== this.generation ) {
  19947. this.generation = generation;
  19948. return true;
  19949. }
  19950. return texture.isVideoTexture;
  19951. }
  19952. update() {
  19953. const { texture, version } = this;
  19954. if ( version !== texture.version ) {
  19955. this.version = texture.version;
  19956. return true;
  19957. }
  19958. return false;
  19959. }
  19960. }
  19961. class NodeSampledTexture extends SampledTexture {
  19962. constructor( name, textureNode, groupNode, access = null ) {
  19963. super( name, textureNode ? textureNode.value : null );
  19964. this.textureNode = textureNode;
  19965. this.groupNode = groupNode;
  19966. this.access = access;
  19967. }
  19968. needsBindingsUpdate( generation ) {
  19969. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  19970. }
  19971. update() {
  19972. const { textureNode } = this;
  19973. if ( this.texture !== textureNode.value ) {
  19974. this.texture = textureNode.value;
  19975. return true;
  19976. }
  19977. return super.update();
  19978. }
  19979. }
  19980. class NodeSampledCubeTexture extends NodeSampledTexture {
  19981. constructor( name, textureNode, groupNode, access ) {
  19982. super( name, textureNode, groupNode, access );
  19983. this.isSampledCubeTexture = true;
  19984. }
  19985. }
  19986. class NodeSampledTexture3D extends NodeSampledTexture {
  19987. constructor( name, textureNode, groupNode, access ) {
  19988. super( name, textureNode, groupNode, access );
  19989. this.isSampledTexture3D = true;
  19990. }
  19991. }
  19992. const glslMethods = {
  19993. atan2: 'atan',
  19994. textureDimensions: 'textureSize',
  19995. equals: 'equal'
  19996. };
  19997. const precisionLib = {
  19998. low: 'lowp',
  19999. medium: 'mediump',
  20000. high: 'highp'
  20001. };
  20002. const supports$1 = {
  20003. swizzleAssign: true,
  20004. storageBuffer: false
  20005. };
  20006. const defaultPrecisions = `
  20007. precision highp float;
  20008. precision highp int;
  20009. precision highp sampler2D;
  20010. precision highp sampler3D;
  20011. precision highp samplerCube;
  20012. precision highp sampler2DArray;
  20013. precision highp usampler2D;
  20014. precision highp usampler3D;
  20015. precision highp usamplerCube;
  20016. precision highp usampler2DArray;
  20017. precision highp isampler2D;
  20018. precision highp isampler3D;
  20019. precision highp isamplerCube;
  20020. precision highp isampler2DArray;
  20021. precision lowp sampler2DShadow;
  20022. `;
  20023. class GLSLNodeBuilder extends NodeBuilder {
  20024. constructor( object, renderer ) {
  20025. super( object, renderer, new GLSLNodeParser() );
  20026. this.uniformGroups = {};
  20027. this.transforms = [];
  20028. this.extensions = {};
  20029. this.builtins = { vertex: [], fragment: [], compute: [] };
  20030. this.useComparisonMethod = true;
  20031. }
  20032. needsToWorkingColorSpace( texture ) {
  20033. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  20034. }
  20035. getMethod( method ) {
  20036. return glslMethods[ method ] || method;
  20037. }
  20038. getOutputStructName() {
  20039. return '';
  20040. }
  20041. buildFunctionCode( shaderNode ) {
  20042. const layout = shaderNode.layout;
  20043. const flowData = this.flowShaderNode( shaderNode );
  20044. const parameters = [];
  20045. for ( const input of layout.inputs ) {
  20046. parameters.push( this.getType( input.type ) + ' ' + input.name );
  20047. }
  20048. //
  20049. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  20050. ${ flowData.vars }
  20051. ${ flowData.code }
  20052. return ${ flowData.result };
  20053. }`;
  20054. //
  20055. return code;
  20056. }
  20057. setupPBO( storageBufferNode ) {
  20058. const attribute = storageBufferNode.value;
  20059. if ( attribute.pbo === undefined ) {
  20060. const originalArray = attribute.array;
  20061. const numElements = attribute.count * attribute.itemSize;
  20062. const { itemSize } = attribute;
  20063. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  20064. let format = isInteger ? RedIntegerFormat : RedFormat;
  20065. if ( itemSize === 2 ) {
  20066. format = isInteger ? RGIntegerFormat : RGFormat;
  20067. } else if ( itemSize === 3 ) {
  20068. format = isInteger ? RGBIntegerFormat : RGBFormat;
  20069. } else if ( itemSize === 4 ) {
  20070. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  20071. }
  20072. const typeMap = {
  20073. Float32Array: FloatType,
  20074. Uint8Array: UnsignedByteType,
  20075. Uint16Array: UnsignedShortType,
  20076. Uint32Array: UnsignedIntType,
  20077. Int8Array: ByteType,
  20078. Int16Array: ShortType,
  20079. Int32Array: IntType,
  20080. Uint8ClampedArray: UnsignedByteType,
  20081. };
  20082. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  20083. let height = Math.ceil( ( numElements / itemSize ) / width );
  20084. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  20085. const newSize = width * height * itemSize;
  20086. const newArray = new originalArray.constructor( newSize );
  20087. newArray.set( originalArray, 0 );
  20088. attribute.array = newArray;
  20089. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  20090. pboTexture.needsUpdate = true;
  20091. pboTexture.isPBOTexture = true;
  20092. const pbo = new TextureNode( pboTexture, null, null );
  20093. pbo.setPrecision( 'high' );
  20094. attribute.pboNode = pbo;
  20095. attribute.pbo = pbo.value;
  20096. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  20097. }
  20098. }
  20099. getPropertyName( node, shaderStage = this.shaderStage ) {
  20100. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  20101. return shaderStage.charAt( 0 ) + '_' + node.name;
  20102. }
  20103. return super.getPropertyName( node, shaderStage );
  20104. }
  20105. generatePBO( storageArrayElementNode ) {
  20106. const { node, indexNode } = storageArrayElementNode;
  20107. const attribute = node.value;
  20108. if ( this.renderer.backend.has( attribute ) ) {
  20109. const attributeData = this.renderer.backend.get( attribute );
  20110. attributeData.pbo = attribute.pbo;
  20111. }
  20112. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  20113. const textureName = this.getPropertyName( nodeUniform );
  20114. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  20115. const indexSnippet = indexNode.build( this, 'uint' );
  20116. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  20117. let propertyName = elementNodeData.propertyName;
  20118. if ( propertyName === undefined ) {
  20119. // property element
  20120. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  20121. propertyName = this.getPropertyName( nodeVar );
  20122. // property size
  20123. const bufferNodeData = this.getDataFromNode( node );
  20124. let propertySizeName = bufferNodeData.propertySizeName;
  20125. if ( propertySizeName === undefined ) {
  20126. propertySizeName = propertyName + 'Size';
  20127. this.getVarFromNode( node, propertySizeName, 'uint' );
  20128. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  20129. bufferNodeData.propertySizeName = propertySizeName;
  20130. }
  20131. //
  20132. const { itemSize } = attribute;
  20133. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  20134. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  20135. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  20136. //
  20137. let prefix = 'vec4';
  20138. if ( attribute.pbo.type === UnsignedIntType ) {
  20139. prefix = 'uvec4';
  20140. } else if ( attribute.pbo.type === IntType ) {
  20141. prefix = 'ivec4';
  20142. }
  20143. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  20144. elementNodeData.propertyName = propertyName;
  20145. }
  20146. return propertyName;
  20147. }
  20148. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  20149. if ( depthSnippet ) {
  20150. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  20151. } else {
  20152. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  20153. }
  20154. }
  20155. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  20156. if ( texture.isDepthTexture ) {
  20157. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  20158. } else {
  20159. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  20160. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  20161. }
  20162. }
  20163. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  20164. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  20165. }
  20166. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  20167. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  20168. }
  20169. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  20170. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  20171. }
  20172. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  20173. if ( shaderStage === 'fragment' ) {
  20174. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  20175. } else {
  20176. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  20177. }
  20178. }
  20179. getVars( shaderStage ) {
  20180. const snippets = [];
  20181. const vars = this.vars[ shaderStage ];
  20182. if ( vars !== undefined ) {
  20183. for ( const variable of vars ) {
  20184. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  20185. }
  20186. }
  20187. return snippets.join( '\n\t' );
  20188. }
  20189. getUniforms( shaderStage ) {
  20190. const uniforms = this.uniforms[ shaderStage ];
  20191. const bindingSnippets = [];
  20192. const uniformGroups = {};
  20193. for ( const uniform of uniforms ) {
  20194. let snippet = null;
  20195. let group = false;
  20196. if ( uniform.type === 'texture' ) {
  20197. const texture = uniform.node.value;
  20198. let typePrefix = '';
  20199. if ( texture.isDataTexture === true ) {
  20200. if ( texture.type === UnsignedIntType ) {
  20201. typePrefix = 'u';
  20202. } else if ( texture.type === IntType ) {
  20203. typePrefix = 'i';
  20204. }
  20205. }
  20206. if ( texture.compareFunction ) {
  20207. snippet = `sampler2DShadow ${ uniform.name };`;
  20208. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  20209. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  20210. } else {
  20211. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  20212. }
  20213. } else if ( uniform.type === 'cubeTexture' ) {
  20214. snippet = `samplerCube ${ uniform.name };`;
  20215. } else if ( uniform.type === 'texture3D' ) {
  20216. snippet = `sampler3D ${ uniform.name };`;
  20217. } else if ( uniform.type === 'buffer' ) {
  20218. const bufferNode = uniform.node;
  20219. const bufferType = this.getType( bufferNode.bufferType );
  20220. const bufferCount = bufferNode.bufferCount;
  20221. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  20222. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  20223. } else {
  20224. const vectorType = this.getVectorType( uniform.type );
  20225. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  20226. group = true;
  20227. }
  20228. const precision = uniform.node.precision;
  20229. if ( precision !== null ) {
  20230. snippet = precisionLib[ precision ] + ' ' + snippet;
  20231. }
  20232. if ( group ) {
  20233. snippet = '\t' + snippet;
  20234. const groupName = uniform.groupNode.name;
  20235. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  20236. groupSnippets.push( snippet );
  20237. } else {
  20238. snippet = 'uniform ' + snippet;
  20239. bindingSnippets.push( snippet );
  20240. }
  20241. }
  20242. let output = '';
  20243. for ( const name in uniformGroups ) {
  20244. const groupSnippets = uniformGroups[ name ];
  20245. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  20246. }
  20247. output += bindingSnippets.join( '\n' );
  20248. return output;
  20249. }
  20250. getTypeFromAttribute( attribute ) {
  20251. let nodeType = super.getTypeFromAttribute( attribute );
  20252. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  20253. let dataAttribute = attribute;
  20254. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  20255. const array = dataAttribute.array;
  20256. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  20257. nodeType = nodeType.slice( 1 );
  20258. }
  20259. }
  20260. return nodeType;
  20261. }
  20262. getAttributes( shaderStage ) {
  20263. let snippet = '';
  20264. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  20265. const attributes = this.getAttributesArray();
  20266. let location = 0;
  20267. for ( const attribute of attributes ) {
  20268. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  20269. }
  20270. }
  20271. return snippet;
  20272. }
  20273. getStructMembers( struct ) {
  20274. const snippets = [];
  20275. const members = struct.getMemberTypes();
  20276. for ( let i = 0; i < members.length; i ++ ) {
  20277. const member = members[ i ];
  20278. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  20279. }
  20280. return snippets.join( '\n' );
  20281. }
  20282. getStructs( shaderStage ) {
  20283. const snippets = [];
  20284. const structs = this.structs[ shaderStage ];
  20285. if ( structs.length === 0 ) {
  20286. return 'layout( location = 0 ) out vec4 fragColor;\n';
  20287. }
  20288. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  20289. const struct = structs[ index ];
  20290. let snippet = '\n';
  20291. snippet += this.getStructMembers( struct );
  20292. snippet += '\n';
  20293. snippets.push( snippet );
  20294. }
  20295. return snippets.join( '\n\n' );
  20296. }
  20297. getVaryings( shaderStage ) {
  20298. let snippet = '';
  20299. const varyings = this.varyings;
  20300. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  20301. for ( const varying of varyings ) {
  20302. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  20303. const type = this.getType( varying.type );
  20304. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  20305. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  20306. }
  20307. } else if ( shaderStage === 'fragment' ) {
  20308. for ( const varying of varyings ) {
  20309. if ( varying.needsInterpolation ) {
  20310. const type = this.getType( varying.type );
  20311. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  20312. snippet += `${flat}in ${type} ${varying.name};\n`;
  20313. }
  20314. }
  20315. }
  20316. for ( const builtin of this.builtins[ shaderStage ] ) {
  20317. snippet += `${builtin};\n`;
  20318. }
  20319. return snippet;
  20320. }
  20321. getVertexIndex() {
  20322. return 'uint( gl_VertexID )';
  20323. }
  20324. getInstanceIndex() {
  20325. return 'uint( gl_InstanceID )';
  20326. }
  20327. getInvocationLocalIndex() {
  20328. const workgroupSize = this.object.workgroupSize;
  20329. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  20330. return `uint( gl_InstanceID ) % ${size}u`;
  20331. }
  20332. getDrawIndex() {
  20333. const extensions = this.renderer.backend.extensions;
  20334. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  20335. return 'uint( gl_DrawID )';
  20336. }
  20337. return null;
  20338. }
  20339. getFrontFacing() {
  20340. return 'gl_FrontFacing';
  20341. }
  20342. getFragCoord() {
  20343. return 'gl_FragCoord.xy';
  20344. }
  20345. getFragDepth() {
  20346. return 'gl_FragDepth';
  20347. }
  20348. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  20349. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  20350. if ( map.has( name ) === false ) {
  20351. map.set( name, {
  20352. name,
  20353. behavior
  20354. } );
  20355. }
  20356. }
  20357. getExtensions( shaderStage ) {
  20358. const snippets = [];
  20359. if ( shaderStage === 'vertex' ) {
  20360. const ext = this.renderer.backend.extensions;
  20361. const isBatchedMesh = this.object.isBatchedMesh;
  20362. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  20363. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  20364. }
  20365. }
  20366. const extensions = this.extensions[ shaderStage ];
  20367. if ( extensions !== undefined ) {
  20368. for ( const { name, behavior } of extensions.values() ) {
  20369. snippets.push( `#extension ${name} : ${behavior}` );
  20370. }
  20371. }
  20372. return snippets.join( '\n' );
  20373. }
  20374. getClipDistance() {
  20375. return 'gl_ClipDistance';
  20376. }
  20377. isAvailable( name ) {
  20378. let result = supports$1[ name ];
  20379. if ( result === undefined ) {
  20380. let extensionName;
  20381. result = false;
  20382. switch ( name ) {
  20383. case 'float32Filterable':
  20384. extensionName = 'OES_texture_float_linear';
  20385. break;
  20386. case 'clipDistance':
  20387. extensionName = 'WEBGL_clip_cull_distance';
  20388. break;
  20389. }
  20390. if ( extensionName !== undefined ) {
  20391. const extensions = this.renderer.backend.extensions;
  20392. if ( extensions.has( extensionName ) ) {
  20393. extensions.get( extensionName );
  20394. result = true;
  20395. }
  20396. }
  20397. supports$1[ name ] = result;
  20398. }
  20399. return result;
  20400. }
  20401. isFlipY() {
  20402. return true;
  20403. }
  20404. enableHardwareClipping( planeCount ) {
  20405. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  20406. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  20407. }
  20408. registerTransform( varyingName, attributeNode ) {
  20409. this.transforms.push( { varyingName, attributeNode } );
  20410. }
  20411. getTransforms( /* shaderStage */ ) {
  20412. const transforms = this.transforms;
  20413. let snippet = '';
  20414. for ( let i = 0; i < transforms.length; i ++ ) {
  20415. const transform = transforms[ i ];
  20416. const attributeName = this.getPropertyName( transform.attributeNode );
  20417. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  20418. }
  20419. return snippet;
  20420. }
  20421. _getGLSLUniformStruct( name, vars ) {
  20422. return `
  20423. layout( std140 ) uniform ${name} {
  20424. ${vars}
  20425. };`;
  20426. }
  20427. _getGLSLVertexCode( shaderData ) {
  20428. return `#version 300 es
  20429. ${ this.getSignature() }
  20430. // extensions
  20431. ${shaderData.extensions}
  20432. // precision
  20433. ${ defaultPrecisions }
  20434. // uniforms
  20435. ${shaderData.uniforms}
  20436. // varyings
  20437. ${shaderData.varyings}
  20438. // attributes
  20439. ${shaderData.attributes}
  20440. // codes
  20441. ${shaderData.codes}
  20442. void main() {
  20443. // vars
  20444. ${shaderData.vars}
  20445. // transforms
  20446. ${shaderData.transforms}
  20447. // flow
  20448. ${shaderData.flow}
  20449. gl_PointSize = 1.0;
  20450. }
  20451. `;
  20452. }
  20453. _getGLSLFragmentCode( shaderData ) {
  20454. return `#version 300 es
  20455. ${ this.getSignature() }
  20456. // precision
  20457. ${ defaultPrecisions }
  20458. // uniforms
  20459. ${shaderData.uniforms}
  20460. // varyings
  20461. ${shaderData.varyings}
  20462. // codes
  20463. ${shaderData.codes}
  20464. ${shaderData.structs}
  20465. void main() {
  20466. // vars
  20467. ${shaderData.vars}
  20468. // flow
  20469. ${shaderData.flow}
  20470. }
  20471. `;
  20472. }
  20473. buildCode() {
  20474. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  20475. this.sortBindingGroups();
  20476. for ( const shaderStage in shadersData ) {
  20477. let flow = '// code\n\n';
  20478. flow += this.flowCode[ shaderStage ];
  20479. const flowNodes = this.flowNodes[ shaderStage ];
  20480. const mainNode = flowNodes[ flowNodes.length - 1 ];
  20481. for ( const node of flowNodes ) {
  20482. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  20483. const slotName = node.name;
  20484. if ( slotName ) {
  20485. if ( flow.length > 0 ) flow += '\n';
  20486. flow += `\t// flow -> ${ slotName }\n\t`;
  20487. }
  20488. flow += `${ flowSlotData.code }\n\t`;
  20489. if ( node === mainNode && shaderStage !== 'compute' ) {
  20490. flow += '// result\n\t';
  20491. if ( shaderStage === 'vertex' ) {
  20492. flow += 'gl_Position = ';
  20493. flow += `${ flowSlotData.result };`;
  20494. } else if ( shaderStage === 'fragment' ) {
  20495. if ( ! node.outputNode.isOutputStructNode ) {
  20496. flow += 'fragColor = ';
  20497. flow += `${ flowSlotData.result };`;
  20498. }
  20499. }
  20500. }
  20501. }
  20502. const stageData = shadersData[ shaderStage ];
  20503. stageData.extensions = this.getExtensions( shaderStage );
  20504. stageData.uniforms = this.getUniforms( shaderStage );
  20505. stageData.attributes = this.getAttributes( shaderStage );
  20506. stageData.varyings = this.getVaryings( shaderStage );
  20507. stageData.vars = this.getVars( shaderStage );
  20508. stageData.structs = this.getStructs( shaderStage );
  20509. stageData.codes = this.getCodes( shaderStage );
  20510. stageData.transforms = this.getTransforms( shaderStage );
  20511. stageData.flow = flow;
  20512. }
  20513. if ( this.material !== null ) {
  20514. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  20515. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  20516. } else {
  20517. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  20518. }
  20519. }
  20520. getUniformFromNode( node, type, shaderStage, name = null ) {
  20521. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  20522. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  20523. let uniformGPU = nodeData.uniformGPU;
  20524. if ( uniformGPU === undefined ) {
  20525. const group = node.groupNode;
  20526. const groupName = group.name;
  20527. const bindings = this.getBindGroupArray( groupName, shaderStage );
  20528. if ( type === 'texture' ) {
  20529. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  20530. bindings.push( uniformGPU );
  20531. } else if ( type === 'cubeTexture' ) {
  20532. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  20533. bindings.push( uniformGPU );
  20534. } else if ( type === 'texture3D' ) {
  20535. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  20536. bindings.push( uniformGPU );
  20537. } else if ( type === 'buffer' ) {
  20538. node.name = `NodeBuffer_${ node.id }`;
  20539. uniformNode.name = `buffer${ node.id }`;
  20540. const buffer = new NodeUniformBuffer( node, group );
  20541. buffer.name = node.name;
  20542. bindings.push( buffer );
  20543. uniformGPU = buffer;
  20544. } else {
  20545. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  20546. let uniformsGroup = uniformsStage[ groupName ];
  20547. if ( uniformsGroup === undefined ) {
  20548. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  20549. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  20550. uniformsStage[ groupName ] = uniformsGroup;
  20551. bindings.push( uniformsGroup );
  20552. }
  20553. uniformGPU = this.getNodeUniform( uniformNode, type );
  20554. uniformsGroup.addUniform( uniformGPU );
  20555. }
  20556. nodeData.uniformGPU = uniformGPU;
  20557. }
  20558. return uniformNode;
  20559. }
  20560. }
  20561. let vector2 = null;
  20562. let vector4 = null;
  20563. let color4 = null;
  20564. class Backend {
  20565. constructor( parameters = {} ) {
  20566. this.parameters = Object.assign( {}, parameters );
  20567. this.data = new WeakMap();
  20568. this.renderer = null;
  20569. this.domElement = null;
  20570. }
  20571. async init( renderer ) {
  20572. this.renderer = renderer;
  20573. }
  20574. // render context
  20575. begin( /*renderContext*/ ) { }
  20576. finish( /*renderContext*/ ) { }
  20577. // render object
  20578. draw( /*renderObject, info*/ ) { }
  20579. // program
  20580. createProgram( /*program*/ ) { }
  20581. destroyProgram( /*program*/ ) { }
  20582. // bindings
  20583. createBindings( /*bingGroup, bindings*/ ) { }
  20584. updateBindings( /*bingGroup, bindings*/ ) { }
  20585. // pipeline
  20586. createRenderPipeline( /*renderObject*/ ) { }
  20587. createComputePipeline( /*computeNode, pipeline*/ ) { }
  20588. destroyPipeline( /*pipeline*/ ) { }
  20589. // cache key
  20590. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  20591. getRenderCacheKey( /*renderObject*/ ) { } // return String
  20592. // node builder
  20593. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  20594. // textures
  20595. createSampler( /*texture*/ ) { }
  20596. createDefaultTexture( /*texture*/ ) { }
  20597. createTexture( /*texture*/ ) { }
  20598. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  20599. // attributes
  20600. createAttribute( /*attribute*/ ) { }
  20601. createIndexAttribute( /*attribute*/ ) { }
  20602. updateAttribute( /*attribute*/ ) { }
  20603. destroyAttribute( /*attribute*/ ) { }
  20604. // canvas
  20605. getContext() { }
  20606. updateSize() { }
  20607. // utils
  20608. resolveTimestampAsync( /*renderContext, type*/ ) { }
  20609. hasFeatureAsync( /*name*/ ) { } // return Boolean
  20610. hasFeature( /*name*/ ) { } // return Boolean
  20611. getInstanceCount( renderObject ) {
  20612. const { object, geometry } = renderObject;
  20613. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  20614. }
  20615. getDrawingBufferSize() {
  20616. vector2 = vector2 || new Vector2();
  20617. return this.renderer.getDrawingBufferSize( vector2 );
  20618. }
  20619. getScissor() {
  20620. vector4 = vector4 || new Vector4();
  20621. return this.renderer.getScissor( vector4 );
  20622. }
  20623. setScissorTest( /*boolean*/ ) { }
  20624. getClearColor() {
  20625. const renderer = this.renderer;
  20626. color4 = color4 || new Color4();
  20627. renderer.getClearColor( color4 );
  20628. color4.getRGB( color4, this.renderer.currentColorSpace );
  20629. return color4;
  20630. }
  20631. getDomElement() {
  20632. let domElement = this.domElement;
  20633. if ( domElement === null ) {
  20634. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  20635. // OffscreenCanvas does not have setAttribute, see #22811
  20636. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  20637. this.domElement = domElement;
  20638. }
  20639. return domElement;
  20640. }
  20641. // resource properties
  20642. set( object, value ) {
  20643. this.data.set( object, value );
  20644. }
  20645. get( object ) {
  20646. let map = this.data.get( object );
  20647. if ( map === undefined ) {
  20648. map = {};
  20649. this.data.set( object, map );
  20650. }
  20651. return map;
  20652. }
  20653. has( object ) {
  20654. return this.data.has( object );
  20655. }
  20656. delete( object ) {
  20657. this.data.delete( object );
  20658. }
  20659. dispose() { }
  20660. }
  20661. let _id$1 = 0;
  20662. class DualAttributeData {
  20663. constructor( attributeData, dualBuffer ) {
  20664. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  20665. this.type = attributeData.type;
  20666. this.bufferType = attributeData.bufferType;
  20667. this.pbo = attributeData.pbo;
  20668. this.byteLength = attributeData.byteLength;
  20669. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  20670. this.version = attributeData.version;
  20671. this.isInteger = attributeData.isInteger;
  20672. this.activeBufferIndex = 0;
  20673. this.baseId = attributeData.id;
  20674. }
  20675. get id() {
  20676. return `${ this.baseId }|${ this.activeBufferIndex }`;
  20677. }
  20678. get bufferGPU() {
  20679. return this.buffers[ this.activeBufferIndex ];
  20680. }
  20681. get transformBuffer() {
  20682. return this.buffers[ this.activeBufferIndex ^ 1 ];
  20683. }
  20684. switchBuffers() {
  20685. this.activeBufferIndex ^= 1;
  20686. }
  20687. }
  20688. class WebGLAttributeUtils {
  20689. constructor( backend ) {
  20690. this.backend = backend;
  20691. }
  20692. createAttribute( attribute, bufferType ) {
  20693. const backend = this.backend;
  20694. const { gl } = backend;
  20695. const array = attribute.array;
  20696. const usage = attribute.usage || gl.STATIC_DRAW;
  20697. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20698. const bufferData = backend.get( bufferAttribute );
  20699. let bufferGPU = bufferData.bufferGPU;
  20700. if ( bufferGPU === undefined ) {
  20701. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  20702. bufferData.bufferGPU = bufferGPU;
  20703. bufferData.bufferType = bufferType;
  20704. bufferData.version = bufferAttribute.version;
  20705. }
  20706. //attribute.onUploadCallback();
  20707. let type;
  20708. if ( array instanceof Float32Array ) {
  20709. type = gl.FLOAT;
  20710. } else if ( array instanceof Uint16Array ) {
  20711. if ( attribute.isFloat16BufferAttribute ) {
  20712. type = gl.HALF_FLOAT;
  20713. } else {
  20714. type = gl.UNSIGNED_SHORT;
  20715. }
  20716. } else if ( array instanceof Int16Array ) {
  20717. type = gl.SHORT;
  20718. } else if ( array instanceof Uint32Array ) {
  20719. type = gl.UNSIGNED_INT;
  20720. } else if ( array instanceof Int32Array ) {
  20721. type = gl.INT;
  20722. } else if ( array instanceof Int8Array ) {
  20723. type = gl.BYTE;
  20724. } else if ( array instanceof Uint8Array ) {
  20725. type = gl.UNSIGNED_BYTE;
  20726. } else if ( array instanceof Uint8ClampedArray ) {
  20727. type = gl.UNSIGNED_BYTE;
  20728. } else {
  20729. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  20730. }
  20731. let attributeData = {
  20732. bufferGPU,
  20733. bufferType,
  20734. type,
  20735. byteLength: array.byteLength,
  20736. bytesPerElement: array.BYTES_PER_ELEMENT,
  20737. version: attribute.version,
  20738. pbo: attribute.pbo,
  20739. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  20740. id: _id$1 ++
  20741. };
  20742. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20743. // create buffer for tranform feedback use
  20744. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  20745. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  20746. }
  20747. backend.set( attribute, attributeData );
  20748. }
  20749. updateAttribute( attribute ) {
  20750. const backend = this.backend;
  20751. const { gl } = backend;
  20752. const array = attribute.array;
  20753. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20754. const bufferData = backend.get( bufferAttribute );
  20755. const bufferType = bufferData.bufferType;
  20756. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  20757. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  20758. if ( updateRanges.length === 0 ) {
  20759. // Not using update ranges
  20760. gl.bufferSubData( bufferType, 0, array );
  20761. } else {
  20762. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  20763. const range = updateRanges[ i ];
  20764. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  20765. array, range.start, range.count );
  20766. }
  20767. bufferAttribute.clearUpdateRanges();
  20768. }
  20769. gl.bindBuffer( bufferType, null );
  20770. bufferData.version = bufferAttribute.version;
  20771. }
  20772. destroyAttribute( attribute ) {
  20773. const backend = this.backend;
  20774. const { gl } = backend;
  20775. if ( attribute.isInterleavedBufferAttribute ) {
  20776. backend.delete( attribute.data );
  20777. }
  20778. const attributeData = backend.get( attribute );
  20779. gl.deleteBuffer( attributeData.bufferGPU );
  20780. backend.delete( attribute );
  20781. }
  20782. async getArrayBufferAsync( attribute ) {
  20783. const backend = this.backend;
  20784. const { gl } = backend;
  20785. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20786. const { bufferGPU } = backend.get( bufferAttribute );
  20787. const array = attribute.array;
  20788. const byteLength = array.byteLength;
  20789. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  20790. const writeBuffer = gl.createBuffer();
  20791. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  20792. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  20793. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  20794. await backend.utils._clientWaitAsync();
  20795. const dstBuffer = new attribute.array.constructor( array.length );
  20796. // Ensure the buffer is bound before reading
  20797. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  20798. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  20799. gl.deleteBuffer( writeBuffer );
  20800. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  20801. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  20802. return dstBuffer.buffer;
  20803. }
  20804. _createBuffer( gl, bufferType, array, usage ) {
  20805. const bufferGPU = gl.createBuffer();
  20806. gl.bindBuffer( bufferType, bufferGPU );
  20807. gl.bufferData( bufferType, array, usage );
  20808. gl.bindBuffer( bufferType, null );
  20809. return bufferGPU;
  20810. }
  20811. }
  20812. let initialized$1 = false, equationToGL, factorToGL;
  20813. class WebGLState {
  20814. constructor( backend ) {
  20815. this.backend = backend;
  20816. this.gl = this.backend.gl;
  20817. this.enabled = {};
  20818. this.currentFlipSided = null;
  20819. this.currentCullFace = null;
  20820. this.currentProgram = null;
  20821. this.currentBlendingEnabled = false;
  20822. this.currentBlending = null;
  20823. this.currentBlendSrc = null;
  20824. this.currentBlendDst = null;
  20825. this.currentBlendSrcAlpha = null;
  20826. this.currentBlendDstAlpha = null;
  20827. this.currentPremultipledAlpha = null;
  20828. this.currentPolygonOffsetFactor = null;
  20829. this.currentPolygonOffsetUnits = null;
  20830. this.currentColorMask = null;
  20831. this.currentDepthFunc = null;
  20832. this.currentDepthMask = null;
  20833. this.currentStencilFunc = null;
  20834. this.currentStencilRef = null;
  20835. this.currentStencilFuncMask = null;
  20836. this.currentStencilFail = null;
  20837. this.currentStencilZFail = null;
  20838. this.currentStencilZPass = null;
  20839. this.currentStencilMask = null;
  20840. this.currentLineWidth = null;
  20841. this.currentClippingPlanes = 0;
  20842. this.currentBoundFramebuffers = {};
  20843. this.currentDrawbuffers = new WeakMap();
  20844. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  20845. this.currentTextureSlot = null;
  20846. this.currentBoundTextures = {};
  20847. this.currentBoundBufferBases = {};
  20848. if ( initialized$1 === false ) {
  20849. this._init( this.gl );
  20850. initialized$1 = true;
  20851. }
  20852. }
  20853. _init( gl ) {
  20854. // Store only WebGL constants here.
  20855. equationToGL = {
  20856. [ AddEquation ]: gl.FUNC_ADD,
  20857. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  20858. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  20859. };
  20860. factorToGL = {
  20861. [ ZeroFactor ]: gl.ZERO,
  20862. [ OneFactor ]: gl.ONE,
  20863. [ SrcColorFactor ]: gl.SRC_COLOR,
  20864. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  20865. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  20866. [ DstColorFactor ]: gl.DST_COLOR,
  20867. [ DstAlphaFactor ]: gl.DST_ALPHA,
  20868. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  20869. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  20870. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  20871. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  20872. };
  20873. }
  20874. enable( id ) {
  20875. const { enabled } = this;
  20876. if ( enabled[ id ] !== true ) {
  20877. this.gl.enable( id );
  20878. enabled[ id ] = true;
  20879. }
  20880. }
  20881. disable( id ) {
  20882. const { enabled } = this;
  20883. if ( enabled[ id ] !== false ) {
  20884. this.gl.disable( id );
  20885. enabled[ id ] = false;
  20886. }
  20887. }
  20888. setFlipSided( flipSided ) {
  20889. if ( this.currentFlipSided !== flipSided ) {
  20890. const { gl } = this;
  20891. if ( flipSided ) {
  20892. gl.frontFace( gl.CW );
  20893. } else {
  20894. gl.frontFace( gl.CCW );
  20895. }
  20896. this.currentFlipSided = flipSided;
  20897. }
  20898. }
  20899. setCullFace( cullFace ) {
  20900. const { gl } = this;
  20901. if ( cullFace !== CullFaceNone ) {
  20902. this.enable( gl.CULL_FACE );
  20903. if ( cullFace !== this.currentCullFace ) {
  20904. if ( cullFace === CullFaceBack ) {
  20905. gl.cullFace( gl.BACK );
  20906. } else if ( cullFace === CullFaceFront ) {
  20907. gl.cullFace( gl.FRONT );
  20908. } else {
  20909. gl.cullFace( gl.FRONT_AND_BACK );
  20910. }
  20911. }
  20912. } else {
  20913. this.disable( gl.CULL_FACE );
  20914. }
  20915. this.currentCullFace = cullFace;
  20916. }
  20917. setLineWidth( width ) {
  20918. const { currentLineWidth, gl } = this;
  20919. if ( width !== currentLineWidth ) {
  20920. gl.lineWidth( width );
  20921. this.currentLineWidth = width;
  20922. }
  20923. }
  20924. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  20925. const { gl } = this;
  20926. if ( blending === NoBlending ) {
  20927. if ( this.currentBlendingEnabled === true ) {
  20928. this.disable( gl.BLEND );
  20929. this.currentBlendingEnabled = false;
  20930. }
  20931. return;
  20932. }
  20933. if ( this.currentBlendingEnabled === false ) {
  20934. this.enable( gl.BLEND );
  20935. this.currentBlendingEnabled = true;
  20936. }
  20937. if ( blending !== CustomBlending ) {
  20938. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  20939. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  20940. gl.blendEquation( gl.FUNC_ADD );
  20941. this.currentBlendEquation = AddEquation;
  20942. this.currentBlendEquationAlpha = AddEquation;
  20943. }
  20944. if ( premultipliedAlpha ) {
  20945. switch ( blending ) {
  20946. case NormalBlending:
  20947. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  20948. break;
  20949. case AdditiveBlending:
  20950. gl.blendFunc( gl.ONE, gl.ONE );
  20951. break;
  20952. case SubtractiveBlending:
  20953. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  20954. break;
  20955. case MultiplyBlending:
  20956. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  20957. break;
  20958. default:
  20959. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  20960. break;
  20961. }
  20962. } else {
  20963. switch ( blending ) {
  20964. case NormalBlending:
  20965. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  20966. break;
  20967. case AdditiveBlending:
  20968. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  20969. break;
  20970. case SubtractiveBlending:
  20971. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  20972. break;
  20973. case MultiplyBlending:
  20974. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  20975. break;
  20976. default:
  20977. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  20978. break;
  20979. }
  20980. }
  20981. this.currentBlendSrc = null;
  20982. this.currentBlendDst = null;
  20983. this.currentBlendSrcAlpha = null;
  20984. this.currentBlendDstAlpha = null;
  20985. this.currentBlending = blending;
  20986. this.currentPremultipledAlpha = premultipliedAlpha;
  20987. }
  20988. return;
  20989. }
  20990. // custom blending
  20991. blendEquationAlpha = blendEquationAlpha || blendEquation;
  20992. blendSrcAlpha = blendSrcAlpha || blendSrc;
  20993. blendDstAlpha = blendDstAlpha || blendDst;
  20994. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  20995. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  20996. this.currentBlendEquation = blendEquation;
  20997. this.currentBlendEquationAlpha = blendEquationAlpha;
  20998. }
  20999. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  21000. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  21001. this.currentBlendSrc = blendSrc;
  21002. this.currentBlendDst = blendDst;
  21003. this.currentBlendSrcAlpha = blendSrcAlpha;
  21004. this.currentBlendDstAlpha = blendDstAlpha;
  21005. }
  21006. this.currentBlending = blending;
  21007. this.currentPremultipledAlpha = false;
  21008. }
  21009. setColorMask( colorMask ) {
  21010. if ( this.currentColorMask !== colorMask ) {
  21011. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  21012. this.currentColorMask = colorMask;
  21013. }
  21014. }
  21015. setDepthTest( depthTest ) {
  21016. const { gl } = this;
  21017. if ( depthTest ) {
  21018. this.enable( gl.DEPTH_TEST );
  21019. } else {
  21020. this.disable( gl.DEPTH_TEST );
  21021. }
  21022. }
  21023. setDepthMask( depthMask ) {
  21024. if ( this.currentDepthMask !== depthMask ) {
  21025. this.gl.depthMask( depthMask );
  21026. this.currentDepthMask = depthMask;
  21027. }
  21028. }
  21029. setDepthFunc( depthFunc ) {
  21030. if ( this.currentDepthFunc !== depthFunc ) {
  21031. const { gl } = this;
  21032. switch ( depthFunc ) {
  21033. case NeverDepth:
  21034. gl.depthFunc( gl.NEVER );
  21035. break;
  21036. case AlwaysDepth:
  21037. gl.depthFunc( gl.ALWAYS );
  21038. break;
  21039. case LessDepth:
  21040. gl.depthFunc( gl.LESS );
  21041. break;
  21042. case LessEqualDepth:
  21043. gl.depthFunc( gl.LEQUAL );
  21044. break;
  21045. case EqualDepth:
  21046. gl.depthFunc( gl.EQUAL );
  21047. break;
  21048. case GreaterEqualDepth:
  21049. gl.depthFunc( gl.GEQUAL );
  21050. break;
  21051. case GreaterDepth:
  21052. gl.depthFunc( gl.GREATER );
  21053. break;
  21054. case NotEqualDepth:
  21055. gl.depthFunc( gl.NOTEQUAL );
  21056. break;
  21057. default:
  21058. gl.depthFunc( gl.LEQUAL );
  21059. }
  21060. this.currentDepthFunc = depthFunc;
  21061. }
  21062. }
  21063. setStencilTest( stencilTest ) {
  21064. const { gl } = this;
  21065. if ( stencilTest ) {
  21066. this.enable( gl.STENCIL_TEST );
  21067. } else {
  21068. this.disable( gl.STENCIL_TEST );
  21069. }
  21070. }
  21071. setStencilMask( stencilMask ) {
  21072. if ( this.currentStencilMask !== stencilMask ) {
  21073. this.gl.stencilMask( stencilMask );
  21074. this.currentStencilMask = stencilMask;
  21075. }
  21076. }
  21077. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  21078. if ( this.currentStencilFunc !== stencilFunc ||
  21079. this.currentStencilRef !== stencilRef ||
  21080. this.currentStencilFuncMask !== stencilMask ) {
  21081. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  21082. this.currentStencilFunc = stencilFunc;
  21083. this.currentStencilRef = stencilRef;
  21084. this.currentStencilFuncMask = stencilMask;
  21085. }
  21086. }
  21087. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  21088. if ( this.currentStencilFail !== stencilFail ||
  21089. this.currentStencilZFail !== stencilZFail ||
  21090. this.currentStencilZPass !== stencilZPass ) {
  21091. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  21092. this.currentStencilFail = stencilFail;
  21093. this.currentStencilZFail = stencilZFail;
  21094. this.currentStencilZPass = stencilZPass;
  21095. }
  21096. }
  21097. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  21098. const { gl } = this;
  21099. material.side === DoubleSide
  21100. ? this.disable( gl.CULL_FACE )
  21101. : this.enable( gl.CULL_FACE );
  21102. let flipSided = ( material.side === BackSide );
  21103. if ( frontFaceCW ) flipSided = ! flipSided;
  21104. this.setFlipSided( flipSided );
  21105. ( material.blending === NormalBlending && material.transparent === false )
  21106. ? this.setBlending( NoBlending )
  21107. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  21108. this.setDepthFunc( material.depthFunc );
  21109. this.setDepthTest( material.depthTest );
  21110. this.setDepthMask( material.depthWrite );
  21111. this.setColorMask( material.colorWrite );
  21112. const stencilWrite = material.stencilWrite;
  21113. this.setStencilTest( stencilWrite );
  21114. if ( stencilWrite ) {
  21115. this.setStencilMask( material.stencilWriteMask );
  21116. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  21117. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  21118. }
  21119. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  21120. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  21121. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  21122. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  21123. if ( hardwareClippingPlanes > 0 ) {
  21124. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  21125. const CLIP_DISTANCE0_WEBGL = 0x3000;
  21126. for ( let i = 0; i < 8; i ++ ) {
  21127. if ( i < hardwareClippingPlanes ) {
  21128. this.enable( CLIP_DISTANCE0_WEBGL + i );
  21129. } else {
  21130. this.disable( CLIP_DISTANCE0_WEBGL + i );
  21131. }
  21132. }
  21133. }
  21134. }
  21135. }
  21136. setPolygonOffset( polygonOffset, factor, units ) {
  21137. const { gl } = this;
  21138. if ( polygonOffset ) {
  21139. this.enable( gl.POLYGON_OFFSET_FILL );
  21140. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  21141. gl.polygonOffset( factor, units );
  21142. this.currentPolygonOffsetFactor = factor;
  21143. this.currentPolygonOffsetUnits = units;
  21144. }
  21145. } else {
  21146. this.disable( gl.POLYGON_OFFSET_FILL );
  21147. }
  21148. }
  21149. useProgram( program ) {
  21150. if ( this.currentProgram !== program ) {
  21151. this.gl.useProgram( program );
  21152. this.currentProgram = program;
  21153. return true;
  21154. }
  21155. return false;
  21156. }
  21157. // framebuffer
  21158. bindFramebuffer( target, framebuffer ) {
  21159. const { gl, currentBoundFramebuffers } = this;
  21160. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  21161. gl.bindFramebuffer( target, framebuffer );
  21162. currentBoundFramebuffers[ target ] = framebuffer;
  21163. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  21164. if ( target === gl.DRAW_FRAMEBUFFER ) {
  21165. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  21166. }
  21167. if ( target === gl.FRAMEBUFFER ) {
  21168. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  21169. }
  21170. return true;
  21171. }
  21172. return false;
  21173. }
  21174. drawBuffers( renderContext, framebuffer ) {
  21175. const { gl } = this;
  21176. let drawBuffers = [];
  21177. let needsUpdate = false;
  21178. if ( renderContext.textures !== null ) {
  21179. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  21180. if ( drawBuffers === undefined ) {
  21181. drawBuffers = [];
  21182. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  21183. }
  21184. const textures = renderContext.textures;
  21185. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  21186. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  21187. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  21188. }
  21189. drawBuffers.length = textures.length;
  21190. needsUpdate = true;
  21191. }
  21192. } else {
  21193. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  21194. drawBuffers[ 0 ] = gl.BACK;
  21195. needsUpdate = true;
  21196. }
  21197. }
  21198. if ( needsUpdate ) {
  21199. gl.drawBuffers( drawBuffers );
  21200. }
  21201. }
  21202. // texture
  21203. activeTexture( webglSlot ) {
  21204. const { gl, currentTextureSlot, maxTextures } = this;
  21205. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  21206. if ( currentTextureSlot !== webglSlot ) {
  21207. gl.activeTexture( webglSlot );
  21208. this.currentTextureSlot = webglSlot;
  21209. }
  21210. }
  21211. bindTexture( webglType, webglTexture, webglSlot ) {
  21212. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  21213. if ( webglSlot === undefined ) {
  21214. if ( currentTextureSlot === null ) {
  21215. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  21216. } else {
  21217. webglSlot = currentTextureSlot;
  21218. }
  21219. }
  21220. let boundTexture = currentBoundTextures[ webglSlot ];
  21221. if ( boundTexture === undefined ) {
  21222. boundTexture = { type: undefined, texture: undefined };
  21223. currentBoundTextures[ webglSlot ] = boundTexture;
  21224. }
  21225. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  21226. if ( currentTextureSlot !== webglSlot ) {
  21227. gl.activeTexture( webglSlot );
  21228. this.currentTextureSlot = webglSlot;
  21229. }
  21230. gl.bindTexture( webglType, webglTexture );
  21231. boundTexture.type = webglType;
  21232. boundTexture.texture = webglTexture;
  21233. }
  21234. }
  21235. bindBufferBase( target, index, buffer ) {
  21236. const { gl } = this;
  21237. const key = `${target}-${index}`;
  21238. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  21239. gl.bindBufferBase( target, index, buffer );
  21240. this.currentBoundBufferBases[ key ] = buffer;
  21241. return true;
  21242. }
  21243. return false;
  21244. }
  21245. unbindTexture() {
  21246. const { gl, currentTextureSlot, currentBoundTextures } = this;
  21247. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  21248. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  21249. gl.bindTexture( boundTexture.type, null );
  21250. boundTexture.type = undefined;
  21251. boundTexture.texture = undefined;
  21252. }
  21253. }
  21254. }
  21255. class WebGLUtils {
  21256. constructor( backend ) {
  21257. this.backend = backend;
  21258. this.gl = this.backend.gl;
  21259. this.extensions = backend.extensions;
  21260. }
  21261. convert( p, colorSpace = NoColorSpace ) {
  21262. const { gl, extensions } = this;
  21263. let extension;
  21264. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  21265. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  21266. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  21267. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  21268. if ( p === ByteType ) return gl.BYTE;
  21269. if ( p === ShortType ) return gl.SHORT;
  21270. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  21271. if ( p === IntType ) return gl.INT;
  21272. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  21273. if ( p === FloatType ) return gl.FLOAT;
  21274. if ( p === HalfFloatType ) {
  21275. return gl.HALF_FLOAT;
  21276. }
  21277. if ( p === AlphaFormat ) return gl.ALPHA;
  21278. if ( p === RGBFormat ) return gl.RGB;
  21279. if ( p === RGBAFormat ) return gl.RGBA;
  21280. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  21281. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  21282. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  21283. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  21284. // WebGL2 formats.
  21285. if ( p === RedFormat ) return gl.RED;
  21286. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  21287. if ( p === RGFormat ) return gl.RG;
  21288. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  21289. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  21290. // S3TC
  21291. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  21292. if ( colorSpace === SRGBColorSpace ) {
  21293. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  21294. if ( extension !== null ) {
  21295. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  21296. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  21297. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  21298. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  21299. } else {
  21300. return null;
  21301. }
  21302. } else {
  21303. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  21304. if ( extension !== null ) {
  21305. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  21306. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21307. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21308. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21309. } else {
  21310. return null;
  21311. }
  21312. }
  21313. }
  21314. // PVRTC
  21315. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  21316. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  21317. if ( extension !== null ) {
  21318. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  21319. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  21320. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  21321. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  21322. } else {
  21323. return null;
  21324. }
  21325. }
  21326. // ETC
  21327. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  21328. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  21329. if ( extension !== null ) {
  21330. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  21331. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  21332. } else {
  21333. return null;
  21334. }
  21335. }
  21336. // ASTC
  21337. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  21338. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  21339. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  21340. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  21341. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  21342. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  21343. if ( extension !== null ) {
  21344. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  21345. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  21346. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  21347. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  21348. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  21349. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  21350. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  21351. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  21352. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  21353. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  21354. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  21355. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  21356. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  21357. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  21358. } else {
  21359. return null;
  21360. }
  21361. }
  21362. // BPTC
  21363. if ( p === RGBA_BPTC_Format ) {
  21364. extension = extensions.get( 'EXT_texture_compression_bptc' );
  21365. if ( extension !== null ) {
  21366. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  21367. } else {
  21368. return null;
  21369. }
  21370. }
  21371. // RGTC
  21372. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  21373. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  21374. if ( extension !== null ) {
  21375. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  21376. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  21377. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  21378. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  21379. } else {
  21380. return null;
  21381. }
  21382. }
  21383. //
  21384. if ( p === UnsignedInt248Type ) {
  21385. return gl.UNSIGNED_INT_24_8;
  21386. }
  21387. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  21388. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  21389. }
  21390. _clientWaitAsync() {
  21391. const { gl } = this;
  21392. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  21393. gl.flush();
  21394. return new Promise( ( resolve, reject ) => {
  21395. function test() {
  21396. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  21397. if ( res === gl.WAIT_FAILED ) {
  21398. gl.deleteSync( sync );
  21399. reject();
  21400. return;
  21401. }
  21402. if ( res === gl.TIMEOUT_EXPIRED ) {
  21403. requestAnimationFrame( test );
  21404. return;
  21405. }
  21406. gl.deleteSync( sync );
  21407. resolve();
  21408. }
  21409. test();
  21410. } );
  21411. }
  21412. }
  21413. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  21414. class WebGLTextureUtils {
  21415. constructor( backend ) {
  21416. this.backend = backend;
  21417. this.gl = backend.gl;
  21418. this.extensions = backend.extensions;
  21419. this.defaultTextures = {};
  21420. if ( initialized === false ) {
  21421. this._init( this.gl );
  21422. initialized = true;
  21423. }
  21424. }
  21425. _init( gl ) {
  21426. // Store only WebGL constants here.
  21427. wrappingToGL = {
  21428. [ RepeatWrapping ]: gl.REPEAT,
  21429. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  21430. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  21431. };
  21432. filterToGL = {
  21433. [ NearestFilter ]: gl.NEAREST,
  21434. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  21435. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  21436. [ LinearFilter ]: gl.LINEAR,
  21437. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  21438. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  21439. };
  21440. compareToGL = {
  21441. [ NeverCompare ]: gl.NEVER,
  21442. [ AlwaysCompare ]: gl.ALWAYS,
  21443. [ LessCompare ]: gl.LESS,
  21444. [ LessEqualCompare ]: gl.LEQUAL,
  21445. [ EqualCompare ]: gl.EQUAL,
  21446. [ GreaterEqualCompare ]: gl.GEQUAL,
  21447. [ GreaterCompare ]: gl.GREATER,
  21448. [ NotEqualCompare ]: gl.NOTEQUAL
  21449. };
  21450. }
  21451. filterFallback( f ) {
  21452. const { gl } = this;
  21453. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  21454. return gl.NEAREST;
  21455. }
  21456. return gl.LINEAR;
  21457. }
  21458. getGLTextureType( texture ) {
  21459. const { gl } = this;
  21460. let glTextureType;
  21461. if ( texture.isCubeTexture === true ) {
  21462. glTextureType = gl.TEXTURE_CUBE_MAP;
  21463. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  21464. glTextureType = gl.TEXTURE_2D_ARRAY;
  21465. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  21466. glTextureType = gl.TEXTURE_3D;
  21467. } else {
  21468. glTextureType = gl.TEXTURE_2D;
  21469. }
  21470. return glTextureType;
  21471. }
  21472. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  21473. const { gl, extensions } = this;
  21474. if ( internalFormatName !== null ) {
  21475. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  21476. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  21477. }
  21478. let internalFormat = glFormat;
  21479. if ( glFormat === gl.RED ) {
  21480. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  21481. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  21482. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  21483. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  21484. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  21485. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  21486. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  21487. if ( glType === gl.INT ) internalFormat = gl.R32I;
  21488. }
  21489. if ( glFormat === gl.RED_INTEGER ) {
  21490. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  21491. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  21492. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  21493. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  21494. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  21495. if ( glType === gl.INT ) internalFormat = gl.R32I;
  21496. }
  21497. if ( glFormat === gl.RG ) {
  21498. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  21499. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  21500. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  21501. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  21502. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  21503. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  21504. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  21505. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  21506. }
  21507. if ( glFormat === gl.RG_INTEGER ) {
  21508. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  21509. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  21510. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  21511. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  21512. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  21513. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  21514. }
  21515. if ( glFormat === gl.RGB ) {
  21516. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  21517. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  21518. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  21519. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  21520. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  21521. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  21522. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  21523. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  21524. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  21525. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  21526. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  21527. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  21528. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  21529. }
  21530. if ( glFormat === gl.RGB_INTEGER ) {
  21531. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  21532. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  21533. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  21534. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  21535. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  21536. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  21537. }
  21538. if ( glFormat === gl.RGBA ) {
  21539. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  21540. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  21541. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  21542. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  21543. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  21544. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  21545. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  21546. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  21547. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  21548. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  21549. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  21550. }
  21551. if ( glFormat === gl.RGBA_INTEGER ) {
  21552. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  21553. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  21554. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  21555. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  21556. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  21557. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  21558. }
  21559. if ( glFormat === gl.DEPTH_COMPONENT ) {
  21560. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  21561. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  21562. }
  21563. if ( glFormat === gl.DEPTH_STENCIL ) {
  21564. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  21565. }
  21566. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  21567. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  21568. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  21569. extensions.get( 'EXT_color_buffer_float' );
  21570. }
  21571. return internalFormat;
  21572. }
  21573. setTextureParameters( textureType, texture ) {
  21574. const { gl, extensions, backend } = this;
  21575. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  21576. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  21577. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  21578. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  21579. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  21580. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  21581. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  21582. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  21583. }
  21584. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  21585. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  21586. // follow WebGPU backend mapping for texture filtering
  21587. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  21588. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  21589. if ( texture.compareFunction ) {
  21590. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  21591. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  21592. }
  21593. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  21594. if ( texture.magFilter === NearestFilter ) return;
  21595. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  21596. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  21597. if ( texture.anisotropy > 1 ) {
  21598. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  21599. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  21600. }
  21601. }
  21602. }
  21603. createDefaultTexture( texture ) {
  21604. const { gl, backend, defaultTextures } = this;
  21605. const glTextureType = this.getGLTextureType( texture );
  21606. let textureGPU = defaultTextures[ glTextureType ];
  21607. if ( textureGPU === undefined ) {
  21608. textureGPU = gl.createTexture();
  21609. backend.state.bindTexture( glTextureType, textureGPU );
  21610. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  21611. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  21612. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  21613. defaultTextures[ glTextureType ] = textureGPU;
  21614. }
  21615. backend.set( texture, {
  21616. textureGPU,
  21617. glTextureType,
  21618. isDefault: true
  21619. } );
  21620. }
  21621. createTexture( texture, options ) {
  21622. const { gl, backend } = this;
  21623. const { levels, width, height, depth } = options;
  21624. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  21625. const glType = backend.utils.convert( texture.type );
  21626. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  21627. const textureGPU = gl.createTexture();
  21628. const glTextureType = this.getGLTextureType( texture );
  21629. backend.state.bindTexture( glTextureType, textureGPU );
  21630. this.setTextureParameters( glTextureType, texture );
  21631. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  21632. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  21633. } else if ( texture.isData3DTexture ) {
  21634. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  21635. } else if ( ! texture.isVideoTexture ) {
  21636. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  21637. }
  21638. backend.set( texture, {
  21639. textureGPU,
  21640. glTextureType,
  21641. glFormat,
  21642. glType,
  21643. glInternalFormat
  21644. } );
  21645. }
  21646. copyBufferToTexture( buffer, texture ) {
  21647. const { gl, backend } = this;
  21648. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  21649. const { width, height } = texture.source.data;
  21650. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  21651. backend.state.bindTexture( glTextureType, textureGPU );
  21652. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  21653. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  21654. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  21655. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  21656. backend.state.unbindTexture();
  21657. // debug
  21658. // const framebuffer = gl.createFramebuffer();
  21659. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  21660. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  21661. // const readout = new Float32Array( width * height * 4 );
  21662. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  21663. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  21664. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  21665. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  21666. // console.log( readout );
  21667. }
  21668. updateTexture( texture, options ) {
  21669. const { gl } = this;
  21670. const { width, height } = options;
  21671. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  21672. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  21673. return;
  21674. const getImage = ( source ) => {
  21675. if ( source.isDataTexture ) {
  21676. return source.image.data;
  21677. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  21678. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  21679. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  21680. source instanceof OffscreenCanvas ) {
  21681. return source;
  21682. }
  21683. return source.data;
  21684. };
  21685. this.backend.state.bindTexture( glTextureType, textureGPU );
  21686. this.setTextureParameters( glTextureType, texture );
  21687. if ( texture.isCompressedTexture ) {
  21688. const mipmaps = texture.mipmaps;
  21689. const image = options.image;
  21690. for ( let i = 0; i < mipmaps.length; i ++ ) {
  21691. const mipmap = mipmaps[ i ];
  21692. if ( texture.isCompressedArrayTexture ) {
  21693. if ( texture.format !== gl.RGBA ) {
  21694. if ( glFormat !== null ) {
  21695. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  21696. } else {
  21697. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  21698. }
  21699. } else {
  21700. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  21701. }
  21702. } else {
  21703. if ( glFormat !== null ) {
  21704. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  21705. } else {
  21706. console.warn( 'Unsupported compressed texture format' );
  21707. }
  21708. }
  21709. }
  21710. } else if ( texture.isCubeTexture ) {
  21711. const images = options.images;
  21712. for ( let i = 0; i < 6; i ++ ) {
  21713. const image = getImage( images[ i ] );
  21714. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  21715. }
  21716. } else if ( texture.isDataArrayTexture ) {
  21717. const image = options.image;
  21718. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  21719. } else if ( texture.isData3DTexture ) {
  21720. const image = options.image;
  21721. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  21722. } else if ( texture.isVideoTexture ) {
  21723. texture.update();
  21724. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  21725. } else {
  21726. const image = getImage( options.image );
  21727. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  21728. }
  21729. }
  21730. generateMipmaps( texture ) {
  21731. const { gl, backend } = this;
  21732. const { textureGPU, glTextureType } = backend.get( texture );
  21733. backend.state.bindTexture( glTextureType, textureGPU );
  21734. gl.generateMipmap( glTextureType );
  21735. }
  21736. deallocateRenderBuffers( renderTarget ) {
  21737. const { gl, backend } = this;
  21738. // remove framebuffer reference
  21739. if ( renderTarget ) {
  21740. const renderContextData = backend.get( renderTarget );
  21741. renderContextData.renderBufferStorageSetup = undefined;
  21742. if ( renderContextData.framebuffers ) {
  21743. for ( const cacheKey in renderContextData.framebuffers ) {
  21744. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  21745. }
  21746. delete renderContextData.framebuffers;
  21747. }
  21748. if ( renderContextData.depthRenderbuffer ) {
  21749. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  21750. delete renderContextData.depthRenderbuffer;
  21751. }
  21752. if ( renderContextData.stencilRenderbuffer ) {
  21753. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  21754. delete renderContextData.stencilRenderbuffer;
  21755. }
  21756. if ( renderContextData.msaaFrameBuffer ) {
  21757. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  21758. delete renderContextData.msaaFrameBuffer;
  21759. }
  21760. if ( renderContextData.msaaRenderbuffers ) {
  21761. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  21762. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  21763. }
  21764. delete renderContextData.msaaRenderbuffers;
  21765. }
  21766. }
  21767. }
  21768. destroyTexture( texture ) {
  21769. const { gl, backend } = this;
  21770. const { textureGPU, renderTarget } = backend.get( texture );
  21771. this.deallocateRenderBuffers( renderTarget );
  21772. gl.deleteTexture( textureGPU );
  21773. backend.delete( texture );
  21774. }
  21775. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  21776. const { gl, backend } = this;
  21777. const { state } = this.backend;
  21778. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  21779. let width, height, minX, minY;
  21780. let dstX, dstY;
  21781. if ( srcRegion !== null ) {
  21782. width = srcRegion.max.x - srcRegion.min.x;
  21783. height = srcRegion.max.y - srcRegion.min.y;
  21784. minX = srcRegion.min.x;
  21785. minY = srcRegion.min.y;
  21786. } else {
  21787. width = srcTexture.image.width;
  21788. height = srcTexture.image.height;
  21789. minX = 0;
  21790. minY = 0;
  21791. }
  21792. if ( dstPosition !== null ) {
  21793. dstX = dstPosition.x;
  21794. dstY = dstPosition.y;
  21795. } else {
  21796. dstX = 0;
  21797. dstY = 0;
  21798. }
  21799. state.bindTexture( glTextureType, dstTextureGPU );
  21800. // As another texture upload may have changed pixelStorei
  21801. // parameters, make sure they are correct for the dstTexture
  21802. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  21803. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  21804. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  21805. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  21806. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  21807. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  21808. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  21809. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  21810. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  21811. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  21812. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  21813. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  21814. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  21815. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  21816. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  21817. const srcTextureData = backend.get( srcTexture );
  21818. const dstTextureData = backend.get( dstTexture );
  21819. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  21820. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  21821. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  21822. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  21823. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  21824. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  21825. let mask = gl.COLOR_BUFFER_BIT;
  21826. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  21827. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  21828. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  21829. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  21830. } else {
  21831. if ( srcTexture.isDataTexture ) {
  21832. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  21833. } else {
  21834. if ( srcTexture.isCompressedTexture ) {
  21835. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  21836. } else {
  21837. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  21838. }
  21839. }
  21840. }
  21841. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  21842. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  21843. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  21844. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  21845. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  21846. // Generate mipmaps only when copying level 0
  21847. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  21848. state.unbindTexture();
  21849. }
  21850. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  21851. const { gl } = this;
  21852. const { state } = this.backend;
  21853. const { textureGPU } = this.backend.get( texture );
  21854. const { x, y, z: width, w: height } = rectangle;
  21855. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  21856. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  21857. if ( requireDrawFrameBuffer ) {
  21858. const partial = ( x !== 0 || y !== 0 );
  21859. let mask;
  21860. let attachment;
  21861. if ( texture.isDepthTexture === true ) {
  21862. mask = gl.DEPTH_BUFFER_BIT;
  21863. attachment = gl.DEPTH_ATTACHMENT;
  21864. if ( renderContext.stencil ) {
  21865. mask |= gl.STENCIL_BUFFER_BIT;
  21866. }
  21867. } else {
  21868. mask = gl.COLOR_BUFFER_BIT;
  21869. attachment = gl.COLOR_ATTACHMENT0;
  21870. }
  21871. if ( partial ) {
  21872. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  21873. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  21874. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  21875. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  21876. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  21877. const flippedY = srcHeight - y - height;
  21878. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  21879. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  21880. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  21881. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  21882. state.unbindTexture();
  21883. } else {
  21884. const fb = gl.createFramebuffer();
  21885. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  21886. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  21887. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  21888. gl.deleteFramebuffer( fb );
  21889. }
  21890. } else {
  21891. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  21892. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  21893. state.unbindTexture();
  21894. }
  21895. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  21896. this.backend._setFramebuffer( renderContext );
  21897. }
  21898. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  21899. setupRenderBufferStorage( renderbuffer, renderContext ) {
  21900. const { gl } = this;
  21901. const renderTarget = renderContext.renderTarget;
  21902. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  21903. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  21904. if ( depthBuffer && ! stencilBuffer ) {
  21905. let glInternalFormat = gl.DEPTH_COMPONENT24;
  21906. if ( samples > 0 ) {
  21907. if ( depthTexture && depthTexture.isDepthTexture ) {
  21908. if ( depthTexture.type === gl.FLOAT ) {
  21909. glInternalFormat = gl.DEPTH_COMPONENT32F;
  21910. }
  21911. }
  21912. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  21913. } else {
  21914. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  21915. }
  21916. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  21917. } else if ( depthBuffer && stencilBuffer ) {
  21918. if ( samples > 0 ) {
  21919. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  21920. } else {
  21921. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  21922. }
  21923. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  21924. }
  21925. }
  21926. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  21927. const { backend, gl } = this;
  21928. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  21929. const fb = gl.createFramebuffer();
  21930. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  21931. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  21932. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  21933. const typedArrayType = this._getTypedArrayType( glType );
  21934. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  21935. const elementCount = width * height;
  21936. const byteLength = elementCount * bytesPerTexel;
  21937. const buffer = gl.createBuffer();
  21938. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  21939. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  21940. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  21941. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  21942. await backend.utils._clientWaitAsync();
  21943. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  21944. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  21945. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  21946. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  21947. gl.deleteFramebuffer( fb );
  21948. return dstBuffer;
  21949. }
  21950. _getTypedArrayType( glType ) {
  21951. const { gl } = this;
  21952. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  21953. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  21954. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  21955. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  21956. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  21957. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  21958. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  21959. if ( glType === gl.FLOAT ) return Float32Array;
  21960. throw new Error( `Unsupported WebGL type: ${glType}` );
  21961. }
  21962. _getBytesPerTexel( glType, glFormat ) {
  21963. const { gl } = this;
  21964. let bytesPerComponent = 0;
  21965. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  21966. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  21967. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  21968. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  21969. glType === gl.UNSIGNED_SHORT ||
  21970. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  21971. if ( glType === gl.UNSIGNED_INT ||
  21972. glType === gl.FLOAT ) bytesPerComponent = 4;
  21973. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  21974. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  21975. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  21976. }
  21977. }
  21978. class WebGLExtensions {
  21979. constructor( backend ) {
  21980. this.backend = backend;
  21981. this.gl = this.backend.gl;
  21982. this.availableExtensions = this.gl.getSupportedExtensions();
  21983. this.extensions = {};
  21984. }
  21985. get( name ) {
  21986. let extension = this.extensions[ name ];
  21987. if ( extension === undefined ) {
  21988. extension = this.gl.getExtension( name );
  21989. this.extensions[ name ] = extension;
  21990. }
  21991. return extension;
  21992. }
  21993. has( name ) {
  21994. return this.availableExtensions.includes( name );
  21995. }
  21996. }
  21997. class WebGLCapabilities {
  21998. constructor( backend ) {
  21999. this.backend = backend;
  22000. this.maxAnisotropy = null;
  22001. }
  22002. getMaxAnisotropy() {
  22003. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  22004. const gl = this.backend.gl;
  22005. const extensions = this.backend.extensions;
  22006. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  22007. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  22008. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  22009. } else {
  22010. this.maxAnisotropy = 0;
  22011. }
  22012. return this.maxAnisotropy;
  22013. }
  22014. }
  22015. const GLFeatureName = {
  22016. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  22017. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  22018. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  22019. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  22020. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  22021. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  22022. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  22023. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  22024. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  22025. };
  22026. class WebGLBufferRenderer {
  22027. constructor( backend ) {
  22028. this.gl = backend.gl;
  22029. this.extensions = backend.extensions;
  22030. this.info = backend.renderer.info;
  22031. this.mode = null;
  22032. this.index = 0;
  22033. this.type = null;
  22034. this.object = null;
  22035. }
  22036. render( start, count ) {
  22037. const { gl, mode, object, type, info, index } = this;
  22038. if ( index !== 0 ) {
  22039. gl.drawElements( mode, count, type, start );
  22040. } else {
  22041. gl.drawArrays( mode, start, count );
  22042. }
  22043. info.update( object, count, mode, 1 );
  22044. }
  22045. renderInstances( start, count, primcount ) {
  22046. const { gl, mode, type, index, object, info } = this;
  22047. if ( primcount === 0 ) return;
  22048. if ( index !== 0 ) {
  22049. gl.drawElementsInstanced( mode, count, type, start, primcount );
  22050. } else {
  22051. gl.drawArraysInstanced( mode, start, count, primcount );
  22052. }
  22053. info.update( object, count, mode, primcount );
  22054. }
  22055. renderMultiDraw( starts, counts, drawCount ) {
  22056. const { extensions, mode, object, info } = this;
  22057. if ( drawCount === 0 ) return;
  22058. const extension = extensions.get( 'WEBGL_multi_draw' );
  22059. if ( extension === null ) {
  22060. for ( let i = 0; i < drawCount; i ++ ) {
  22061. this.render( starts[ i ], counts[ i ] );
  22062. }
  22063. } else {
  22064. if ( this.index !== 0 ) {
  22065. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  22066. } else {
  22067. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  22068. }
  22069. let elementCount = 0;
  22070. for ( let i = 0; i < drawCount; i ++ ) {
  22071. elementCount += counts[ i ];
  22072. }
  22073. info.update( object, elementCount, mode, 1 );
  22074. }
  22075. }
  22076. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  22077. const { extensions, mode, object, info } = this;
  22078. if ( drawCount === 0 ) return;
  22079. const extension = extensions.get( 'WEBGL_multi_draw' );
  22080. if ( extension === null ) {
  22081. for ( let i = 0; i < drawCount; i ++ ) {
  22082. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  22083. }
  22084. } else {
  22085. if ( this.index !== 0 ) {
  22086. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  22087. } else {
  22088. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  22089. }
  22090. let elementCount = 0;
  22091. for ( let i = 0; i < drawCount; i ++ ) {
  22092. elementCount += counts[ i ] * primcount[ i ];
  22093. }
  22094. info.update( object, elementCount, mode, 1 );
  22095. }
  22096. }
  22097. //
  22098. }
  22099. //
  22100. class WebGLBackend extends Backend {
  22101. constructor( parameters = {} ) {
  22102. super( parameters );
  22103. this.isWebGLBackend = true;
  22104. }
  22105. init( renderer ) {
  22106. super.init( renderer );
  22107. //
  22108. const parameters = this.parameters;
  22109. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  22110. function onContextLost( event ) {
  22111. event.preventDefault();
  22112. const contextLossInfo = {
  22113. api: 'WebGL',
  22114. message: event.statusMessage || 'Unknown reason',
  22115. reason: null,
  22116. originalEvent: event
  22117. };
  22118. renderer.onDeviceLost( contextLossInfo );
  22119. }
  22120. this._onContextLost = onContextLost;
  22121. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  22122. this.gl = glContext;
  22123. this.extensions = new WebGLExtensions( this );
  22124. this.capabilities = new WebGLCapabilities( this );
  22125. this.attributeUtils = new WebGLAttributeUtils( this );
  22126. this.textureUtils = new WebGLTextureUtils( this );
  22127. this.bufferRenderer = new WebGLBufferRenderer( this );
  22128. this.state = new WebGLState( this );
  22129. this.utils = new WebGLUtils( this );
  22130. this.vaoCache = {};
  22131. this.transformFeedbackCache = {};
  22132. this.discard = false;
  22133. this.trackTimestamp = ( parameters.trackTimestamp === true );
  22134. this.extensions.get( 'EXT_color_buffer_float' );
  22135. this.extensions.get( 'WEBGL_clip_cull_distance' );
  22136. this.extensions.get( 'OES_texture_float_linear' );
  22137. this.extensions.get( 'EXT_color_buffer_half_float' );
  22138. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  22139. this.extensions.get( 'WEBGL_render_shared_exponent' );
  22140. this.extensions.get( 'WEBGL_multi_draw' );
  22141. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  22142. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  22143. this._knownBindings = new WeakSet();
  22144. this._currentContext = null;
  22145. }
  22146. get coordinateSystem() {
  22147. return WebGLCoordinateSystem;
  22148. }
  22149. async getArrayBufferAsync( attribute ) {
  22150. return await this.attributeUtils.getArrayBufferAsync( attribute );
  22151. }
  22152. async waitForGPU() {
  22153. await this.utils._clientWaitAsync();
  22154. }
  22155. initTimestampQuery( renderContext ) {
  22156. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  22157. const renderContextData = this.get( renderContext );
  22158. if ( this.queryRunning ) {
  22159. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  22160. renderContextData.queryQueue.push( renderContext );
  22161. return;
  22162. }
  22163. if ( renderContextData.activeQuery ) {
  22164. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  22165. renderContextData.activeQuery = null;
  22166. }
  22167. renderContextData.activeQuery = this.gl.createQuery();
  22168. if ( renderContextData.activeQuery !== null ) {
  22169. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  22170. this.queryRunning = true;
  22171. }
  22172. }
  22173. // timestamp utils
  22174. prepareTimestampBuffer( renderContext ) {
  22175. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  22176. const renderContextData = this.get( renderContext );
  22177. if ( renderContextData.activeQuery ) {
  22178. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  22179. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  22180. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  22181. renderContextData.activeQuery = null;
  22182. this.queryRunning = false;
  22183. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  22184. const nextRenderContext = renderContextData.queryQueue.shift();
  22185. this.initTimestampQuery( nextRenderContext );
  22186. }
  22187. }
  22188. }
  22189. async resolveTimestampAsync( renderContext, type = 'render' ) {
  22190. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  22191. const renderContextData = this.get( renderContext );
  22192. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  22193. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  22194. const queryInfo = renderContextData.gpuQueries[ i ];
  22195. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  22196. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  22197. if ( available && ! disjoint ) {
  22198. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  22199. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  22200. this.gl.deleteQuery( queryInfo.query );
  22201. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  22202. i --;
  22203. this.renderer.info.updateTimestamp( type, duration );
  22204. }
  22205. }
  22206. }
  22207. getContext() {
  22208. return this.gl;
  22209. }
  22210. beginRender( renderContext ) {
  22211. const { gl } = this;
  22212. const renderContextData = this.get( renderContext );
  22213. //
  22214. //
  22215. this.initTimestampQuery( renderContext );
  22216. renderContextData.previousContext = this._currentContext;
  22217. this._currentContext = renderContext;
  22218. this._setFramebuffer( renderContext );
  22219. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  22220. //
  22221. if ( renderContext.viewport ) {
  22222. this.updateViewport( renderContext );
  22223. } else {
  22224. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  22225. }
  22226. if ( renderContext.scissor ) {
  22227. const { x, y, width, height } = renderContext.scissorValue;
  22228. gl.scissor( x, renderContext.height - height - y, width, height );
  22229. }
  22230. const occlusionQueryCount = renderContext.occlusionQueryCount;
  22231. if ( occlusionQueryCount > 0 ) {
  22232. // Get a reference to the array of objects with queries. The renderContextData property
  22233. // can be changed by another render pass before the async reading of all previous queries complete
  22234. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  22235. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  22236. renderContextData.lastOcclusionObject = null;
  22237. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  22238. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  22239. renderContextData.occlusionQueryIndex = 0;
  22240. }
  22241. }
  22242. finishRender( renderContext ) {
  22243. const { gl, state } = this;
  22244. const renderContextData = this.get( renderContext );
  22245. const previousContext = renderContextData.previousContext;
  22246. const occlusionQueryCount = renderContext.occlusionQueryCount;
  22247. if ( occlusionQueryCount > 0 ) {
  22248. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  22249. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  22250. }
  22251. this.resolveOccludedAsync( renderContext );
  22252. }
  22253. const textures = renderContext.textures;
  22254. if ( textures !== null ) {
  22255. for ( let i = 0; i < textures.length; i ++ ) {
  22256. const texture = textures[ i ];
  22257. if ( texture.generateMipmaps ) {
  22258. this.generateMipmaps( texture );
  22259. }
  22260. }
  22261. }
  22262. this._currentContext = previousContext;
  22263. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  22264. const renderTargetContextData = this.get( renderContext.renderTarget );
  22265. const { samples } = renderContext.renderTarget;
  22266. if ( samples > 0 ) {
  22267. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  22268. const mask = gl.COLOR_BUFFER_BIT;
  22269. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  22270. const textures = renderContext.textures;
  22271. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  22272. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  22273. for ( let i = 0; i < textures.length; i ++ ) {
  22274. // TODO Add support for MRT
  22275. if ( renderContext.scissor ) {
  22276. const { x, y, width, height } = renderContext.scissorValue;
  22277. const viewY = renderContext.height - height - y;
  22278. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  22279. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  22280. } else {
  22281. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  22282. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  22283. }
  22284. }
  22285. }
  22286. }
  22287. if ( previousContext !== null ) {
  22288. this._setFramebuffer( previousContext );
  22289. if ( previousContext.viewport ) {
  22290. this.updateViewport( previousContext );
  22291. } else {
  22292. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  22293. }
  22294. }
  22295. this.prepareTimestampBuffer( renderContext );
  22296. }
  22297. resolveOccludedAsync( renderContext ) {
  22298. const renderContextData = this.get( renderContext );
  22299. // handle occlusion query results
  22300. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  22301. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  22302. const occluded = new WeakSet();
  22303. const { gl } = this;
  22304. renderContextData.currentOcclusionQueryObjects = null;
  22305. renderContextData.currentOcclusionQueries = null;
  22306. const check = () => {
  22307. let completed = 0;
  22308. // check all queries and requeue as appropriate
  22309. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  22310. const query = currentOcclusionQueries[ i ];
  22311. if ( query === null ) continue;
  22312. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  22313. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  22314. currentOcclusionQueries[ i ] = null;
  22315. gl.deleteQuery( query );
  22316. completed ++;
  22317. }
  22318. }
  22319. if ( completed < currentOcclusionQueries.length ) {
  22320. requestAnimationFrame( check );
  22321. } else {
  22322. renderContextData.occluded = occluded;
  22323. }
  22324. };
  22325. check();
  22326. }
  22327. }
  22328. isOccluded( renderContext, object ) {
  22329. const renderContextData = this.get( renderContext );
  22330. return renderContextData.occluded && renderContextData.occluded.has( object );
  22331. }
  22332. updateViewport( renderContext ) {
  22333. const gl = this.gl;
  22334. const { x, y, width, height } = renderContext.viewportValue;
  22335. gl.viewport( x, renderContext.height - height - y, width, height );
  22336. }
  22337. setScissorTest( boolean ) {
  22338. const gl = this.gl;
  22339. if ( boolean ) {
  22340. gl.enable( gl.SCISSOR_TEST );
  22341. } else {
  22342. gl.disable( gl.SCISSOR_TEST );
  22343. }
  22344. }
  22345. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  22346. const { gl } = this;
  22347. if ( descriptor === null ) {
  22348. const clearColor = this.getClearColor();
  22349. // premultiply alpha
  22350. clearColor.r *= clearColor.a;
  22351. clearColor.g *= clearColor.a;
  22352. clearColor.b *= clearColor.a;
  22353. descriptor = {
  22354. textures: null,
  22355. clearColorValue: clearColor
  22356. };
  22357. }
  22358. //
  22359. let clear = 0;
  22360. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  22361. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  22362. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  22363. if ( clear !== 0 ) {
  22364. let clearColor;
  22365. if ( descriptor.clearColorValue ) {
  22366. clearColor = descriptor.clearColorValue;
  22367. } else {
  22368. clearColor = this.getClearColor();
  22369. // premultiply alpha
  22370. clearColor.r *= clearColor.a;
  22371. clearColor.g *= clearColor.a;
  22372. clearColor.b *= clearColor.a;
  22373. }
  22374. if ( depth ) this.state.setDepthMask( true );
  22375. if ( descriptor.textures === null ) {
  22376. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  22377. gl.clear( clear );
  22378. } else {
  22379. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  22380. if ( color ) {
  22381. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  22382. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  22383. }
  22384. }
  22385. if ( depth && stencil ) {
  22386. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  22387. } else if ( depth ) {
  22388. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  22389. } else if ( stencil ) {
  22390. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  22391. }
  22392. }
  22393. }
  22394. }
  22395. beginCompute( computeGroup ) {
  22396. const { state, gl } = this;
  22397. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  22398. this.initTimestampQuery( computeGroup );
  22399. }
  22400. compute( computeGroup, computeNode, bindings, pipeline ) {
  22401. const { state, gl } = this;
  22402. if ( ! this.discard ) {
  22403. // required here to handle async behaviour of render.compute()
  22404. gl.enable( gl.RASTERIZER_DISCARD );
  22405. this.discard = true;
  22406. }
  22407. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  22408. const vaoKey = this._getVaoKey( null, attributes );
  22409. const vaoGPU = this.vaoCache[ vaoKey ];
  22410. if ( vaoGPU === undefined ) {
  22411. this._createVao( null, attributes );
  22412. } else {
  22413. gl.bindVertexArray( vaoGPU );
  22414. }
  22415. state.useProgram( programGPU );
  22416. this._bindUniforms( bindings );
  22417. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  22418. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  22419. gl.beginTransformFeedback( gl.POINTS );
  22420. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  22421. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  22422. } else {
  22423. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  22424. }
  22425. gl.endTransformFeedback();
  22426. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  22427. // switch active buffers
  22428. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  22429. const dualAttributeData = transformBuffers[ i ];
  22430. if ( dualAttributeData.pbo ) {
  22431. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  22432. }
  22433. dualAttributeData.switchBuffers();
  22434. }
  22435. }
  22436. finishCompute( computeGroup ) {
  22437. const gl = this.gl;
  22438. this.discard = false;
  22439. gl.disable( gl.RASTERIZER_DISCARD );
  22440. this.prepareTimestampBuffer( computeGroup );
  22441. if ( this._currentContext ) {
  22442. this._setFramebuffer( this._currentContext );
  22443. }
  22444. }
  22445. draw( renderObject/*, info*/ ) {
  22446. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  22447. const { programGPU } = this.get( pipeline );
  22448. const { gl, state } = this;
  22449. const contextData = this.get( context );
  22450. const drawParams = renderObject.getDrawParameters();
  22451. if ( drawParams === null ) return;
  22452. //
  22453. this._bindUniforms( renderObject.getBindings() );
  22454. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  22455. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  22456. state.useProgram( programGPU );
  22457. //
  22458. const renderObjectData = this.get( renderObject );
  22459. let vaoGPU = renderObjectData.staticVao;
  22460. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  22461. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  22462. vaoGPU = this.vaoCache[ vaoKey ];
  22463. if ( vaoGPU === undefined ) {
  22464. let staticVao;
  22465. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  22466. if ( staticVao ) {
  22467. renderObjectData.staticVao = vaoGPU;
  22468. renderObjectData.geometryId = renderObject.geometry.id;
  22469. }
  22470. }
  22471. }
  22472. gl.bindVertexArray( vaoGPU );
  22473. //
  22474. const index = renderObject.getIndex();
  22475. //
  22476. const lastObject = contextData.lastOcclusionObject;
  22477. if ( lastObject !== object && lastObject !== undefined ) {
  22478. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  22479. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  22480. contextData.occlusionQueryIndex ++;
  22481. }
  22482. if ( object.occlusionTest === true ) {
  22483. const query = gl.createQuery();
  22484. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  22485. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  22486. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  22487. }
  22488. contextData.lastOcclusionObject = object;
  22489. }
  22490. //
  22491. const renderer = this.bufferRenderer;
  22492. if ( object.isPoints ) renderer.mode = gl.POINTS;
  22493. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  22494. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  22495. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  22496. else {
  22497. if ( material.wireframe === true ) {
  22498. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  22499. renderer.mode = gl.LINES;
  22500. } else {
  22501. renderer.mode = gl.TRIANGLES;
  22502. }
  22503. }
  22504. //
  22505. const { vertexCount, instanceCount } = drawParams;
  22506. let { firstVertex } = drawParams;
  22507. renderer.object = object;
  22508. if ( index !== null ) {
  22509. firstVertex *= index.array.BYTES_PER_ELEMENT;
  22510. const indexData = this.get( index );
  22511. renderer.index = index.count;
  22512. renderer.type = indexData.type;
  22513. } else {
  22514. renderer.index = 0;
  22515. }
  22516. if ( object.isBatchedMesh ) {
  22517. if ( object._multiDrawInstances !== null ) {
  22518. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  22519. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  22520. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  22521. } else {
  22522. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  22523. }
  22524. } else if ( instanceCount > 1 ) {
  22525. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  22526. } else {
  22527. renderer.render( firstVertex, vertexCount );
  22528. }
  22529. //
  22530. gl.bindVertexArray( null );
  22531. }
  22532. needsRenderUpdate( /*renderObject*/ ) {
  22533. return false;
  22534. }
  22535. getRenderCacheKey( /*renderObject*/ ) {
  22536. return '';
  22537. }
  22538. // textures
  22539. createDefaultTexture( texture ) {
  22540. this.textureUtils.createDefaultTexture( texture );
  22541. }
  22542. createTexture( texture, options ) {
  22543. this.textureUtils.createTexture( texture, options );
  22544. }
  22545. updateTexture( texture, options ) {
  22546. this.textureUtils.updateTexture( texture, options );
  22547. }
  22548. generateMipmaps( texture ) {
  22549. this.textureUtils.generateMipmaps( texture );
  22550. }
  22551. destroyTexture( texture ) {
  22552. this.textureUtils.destroyTexture( texture );
  22553. }
  22554. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  22555. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  22556. }
  22557. createSampler( /*texture*/ ) {
  22558. //console.warn( 'Abstract class.' );
  22559. }
  22560. destroySampler() {}
  22561. // node builder
  22562. createNodeBuilder( object, renderer ) {
  22563. return new GLSLNodeBuilder( object, renderer );
  22564. }
  22565. // program
  22566. createProgram( program ) {
  22567. const gl = this.gl;
  22568. const { stage, code } = program;
  22569. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  22570. gl.shaderSource( shader, code );
  22571. gl.compileShader( shader );
  22572. this.set( program, {
  22573. shaderGPU: shader
  22574. } );
  22575. }
  22576. destroyProgram( /*program*/ ) {
  22577. console.warn( 'Abstract class.' );
  22578. }
  22579. createRenderPipeline( renderObject, promises ) {
  22580. const gl = this.gl;
  22581. const pipeline = renderObject.pipeline;
  22582. // Program
  22583. const { fragmentProgram, vertexProgram } = pipeline;
  22584. const programGPU = gl.createProgram();
  22585. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  22586. const vertexShader = this.get( vertexProgram ).shaderGPU;
  22587. gl.attachShader( programGPU, fragmentShader );
  22588. gl.attachShader( programGPU, vertexShader );
  22589. gl.linkProgram( programGPU );
  22590. this.set( pipeline, {
  22591. programGPU,
  22592. fragmentShader,
  22593. vertexShader
  22594. } );
  22595. if ( promises !== null && this.parallel ) {
  22596. const p = new Promise( ( resolve /*, reject*/ ) => {
  22597. const parallel = this.parallel;
  22598. const checkStatus = () => {
  22599. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  22600. this._completeCompile( renderObject, pipeline );
  22601. resolve();
  22602. } else {
  22603. requestAnimationFrame( checkStatus );
  22604. }
  22605. };
  22606. checkStatus();
  22607. } );
  22608. promises.push( p );
  22609. return;
  22610. }
  22611. this._completeCompile( renderObject, pipeline );
  22612. }
  22613. _handleSource( string, errorLine ) {
  22614. const lines = string.split( '\n' );
  22615. const lines2 = [];
  22616. const from = Math.max( errorLine - 6, 0 );
  22617. const to = Math.min( errorLine + 6, lines.length );
  22618. for ( let i = from; i < to; i ++ ) {
  22619. const line = i + 1;
  22620. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  22621. }
  22622. return lines2.join( '\n' );
  22623. }
  22624. _getShaderErrors( gl, shader, type ) {
  22625. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  22626. const errors = gl.getShaderInfoLog( shader ).trim();
  22627. if ( status && errors === '' ) return '';
  22628. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  22629. if ( errorMatches ) {
  22630. const errorLine = parseInt( errorMatches[ 1 ] );
  22631. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  22632. } else {
  22633. return errors;
  22634. }
  22635. }
  22636. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  22637. if ( this.renderer.debug.checkShaderErrors ) {
  22638. const gl = this.gl;
  22639. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  22640. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  22641. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  22642. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  22643. } else {
  22644. // default error reporting
  22645. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  22646. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  22647. console.error(
  22648. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  22649. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  22650. 'Program Info Log: ' + programLog + '\n' +
  22651. vertexErrors + '\n' +
  22652. fragmentErrors
  22653. );
  22654. }
  22655. } else if ( programLog !== '' ) {
  22656. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  22657. }
  22658. }
  22659. }
  22660. _completeCompile( renderObject, pipeline ) {
  22661. const { state, gl } = this;
  22662. const pipelineData = this.get( pipeline );
  22663. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  22664. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  22665. this._logProgramError( programGPU, fragmentShader, vertexShader );
  22666. }
  22667. state.useProgram( programGPU );
  22668. // Bindings
  22669. const bindings = renderObject.getBindings();
  22670. this._setupBindings( bindings, programGPU );
  22671. //
  22672. this.set( pipeline, {
  22673. programGPU
  22674. } );
  22675. }
  22676. createComputePipeline( computePipeline, bindings ) {
  22677. const { state, gl } = this;
  22678. // Program
  22679. const fragmentProgram = {
  22680. stage: 'fragment',
  22681. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  22682. };
  22683. this.createProgram( fragmentProgram );
  22684. const { computeProgram } = computePipeline;
  22685. const programGPU = gl.createProgram();
  22686. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  22687. const vertexShader = this.get( computeProgram ).shaderGPU;
  22688. const transforms = computeProgram.transforms;
  22689. const transformVaryingNames = [];
  22690. const transformAttributeNodes = [];
  22691. for ( let i = 0; i < transforms.length; i ++ ) {
  22692. const transform = transforms[ i ];
  22693. transformVaryingNames.push( transform.varyingName );
  22694. transformAttributeNodes.push( transform.attributeNode );
  22695. }
  22696. gl.attachShader( programGPU, fragmentShader );
  22697. gl.attachShader( programGPU, vertexShader );
  22698. gl.transformFeedbackVaryings(
  22699. programGPU,
  22700. transformVaryingNames,
  22701. gl.SEPARATE_ATTRIBS
  22702. );
  22703. gl.linkProgram( programGPU );
  22704. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  22705. this._logProgramError( programGPU, fragmentShader, vertexShader );
  22706. }
  22707. state.useProgram( programGPU );
  22708. // Bindings
  22709. this._setupBindings( bindings, programGPU );
  22710. const attributeNodes = computeProgram.attributes;
  22711. const attributes = [];
  22712. const transformBuffers = [];
  22713. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  22714. const attribute = attributeNodes[ i ].node.attribute;
  22715. attributes.push( attribute );
  22716. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  22717. }
  22718. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  22719. const attribute = transformAttributeNodes[ i ].attribute;
  22720. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  22721. const attributeData = this.get( attribute );
  22722. transformBuffers.push( attributeData );
  22723. }
  22724. //
  22725. this.set( computePipeline, {
  22726. programGPU,
  22727. transformBuffers,
  22728. attributes
  22729. } );
  22730. }
  22731. createBindings( bindGroup, bindings ) {
  22732. if ( this._knownBindings.has( bindings ) === false ) {
  22733. this._knownBindings.add( bindings );
  22734. let uniformBuffers = 0;
  22735. let textures = 0;
  22736. for ( const bindGroup of bindings ) {
  22737. this.set( bindGroup, {
  22738. textures: textures,
  22739. uniformBuffers: uniformBuffers
  22740. } );
  22741. for ( const binding of bindGroup.bindings ) {
  22742. if ( binding.isUniformBuffer ) uniformBuffers ++;
  22743. if ( binding.isSampledTexture ) textures ++;
  22744. }
  22745. }
  22746. }
  22747. this.updateBindings( bindGroup, bindings );
  22748. }
  22749. updateBindings( bindGroup /*, bindings*/ ) {
  22750. const { gl } = this;
  22751. const bindGroupData = this.get( bindGroup );
  22752. let i = bindGroupData.uniformBuffers;
  22753. let t = bindGroupData.textures;
  22754. for ( const binding of bindGroup.bindings ) {
  22755. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  22756. const data = binding.buffer;
  22757. const bufferGPU = gl.createBuffer();
  22758. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  22759. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  22760. this.set( binding, {
  22761. index: i ++,
  22762. bufferGPU
  22763. } );
  22764. } else if ( binding.isSampledTexture ) {
  22765. const { textureGPU, glTextureType } = this.get( binding.texture );
  22766. this.set( binding, {
  22767. index: t ++,
  22768. textureGPU,
  22769. glTextureType
  22770. } );
  22771. }
  22772. }
  22773. }
  22774. updateBinding( binding ) {
  22775. const gl = this.gl;
  22776. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  22777. const bindingData = this.get( binding );
  22778. const bufferGPU = bindingData.bufferGPU;
  22779. const data = binding.buffer;
  22780. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  22781. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  22782. }
  22783. }
  22784. // attributes
  22785. createIndexAttribute( attribute ) {
  22786. const gl = this.gl;
  22787. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  22788. }
  22789. createAttribute( attribute ) {
  22790. if ( this.has( attribute ) ) return;
  22791. const gl = this.gl;
  22792. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  22793. }
  22794. createStorageAttribute( attribute ) {
  22795. if ( this.has( attribute ) ) return;
  22796. const gl = this.gl;
  22797. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  22798. }
  22799. updateAttribute( attribute ) {
  22800. this.attributeUtils.updateAttribute( attribute );
  22801. }
  22802. destroyAttribute( attribute ) {
  22803. this.attributeUtils.destroyAttribute( attribute );
  22804. }
  22805. updateSize() {
  22806. //console.warn( 'Abstract class.' );
  22807. }
  22808. hasFeature( name ) {
  22809. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  22810. const extensions = this.extensions;
  22811. for ( let i = 0; i < keysMatching.length; i ++ ) {
  22812. if ( extensions.has( keysMatching[ i ] ) ) return true;
  22813. }
  22814. return false;
  22815. }
  22816. getMaxAnisotropy() {
  22817. return this.capabilities.getMaxAnisotropy();
  22818. }
  22819. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  22820. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  22821. }
  22822. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  22823. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  22824. }
  22825. _setFramebuffer( descriptor ) {
  22826. const { gl, state } = this;
  22827. let currentFrameBuffer = null;
  22828. if ( descriptor.textures !== null ) {
  22829. const renderTarget = descriptor.renderTarget;
  22830. const renderTargetContextData = this.get( renderTarget );
  22831. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  22832. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  22833. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  22834. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  22835. const cacheKey = getCacheKey( descriptor );
  22836. let fb;
  22837. if ( isCube ) {
  22838. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  22839. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  22840. } else {
  22841. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  22842. fb = renderTargetContextData.framebuffers[ cacheKey ];
  22843. }
  22844. if ( fb === undefined ) {
  22845. fb = gl.createFramebuffer();
  22846. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  22847. const textures = descriptor.textures;
  22848. if ( isCube ) {
  22849. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  22850. const { textureGPU } = this.get( textures[ 0 ] );
  22851. const cubeFace = this.renderer._activeCubeFace;
  22852. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  22853. } else {
  22854. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  22855. for ( let i = 0; i < textures.length; i ++ ) {
  22856. const texture = textures[ i ];
  22857. const textureData = this.get( texture );
  22858. textureData.renderTarget = descriptor.renderTarget;
  22859. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  22860. const attachment = gl.COLOR_ATTACHMENT0 + i;
  22861. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  22862. }
  22863. state.drawBuffers( descriptor, fb );
  22864. }
  22865. if ( descriptor.depthTexture !== null ) {
  22866. const textureData = this.get( descriptor.depthTexture );
  22867. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  22868. textureData.renderTarget = descriptor.renderTarget;
  22869. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  22870. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  22871. }
  22872. }
  22873. if ( samples > 0 ) {
  22874. if ( msaaFb === undefined ) {
  22875. const invalidationArray = [];
  22876. msaaFb = gl.createFramebuffer();
  22877. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  22878. const msaaRenderbuffers = [];
  22879. const textures = descriptor.textures;
  22880. for ( let i = 0; i < textures.length; i ++ ) {
  22881. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  22882. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  22883. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  22884. if ( depthBuffer ) {
  22885. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  22886. invalidationArray.push( depthStyle );
  22887. }
  22888. const texture = descriptor.textures[ i ];
  22889. const textureData = this.get( texture );
  22890. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  22891. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  22892. }
  22893. renderTargetContextData.msaaFrameBuffer = msaaFb;
  22894. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  22895. if ( depthRenderbuffer === undefined ) {
  22896. depthRenderbuffer = gl.createRenderbuffer();
  22897. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  22898. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  22899. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  22900. invalidationArray.push( depthStyle );
  22901. }
  22902. renderTargetContextData.invalidationArray = invalidationArray;
  22903. }
  22904. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  22905. } else {
  22906. currentFrameBuffer = fb;
  22907. }
  22908. }
  22909. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  22910. }
  22911. _getVaoKey( index, attributes ) {
  22912. let key = [];
  22913. if ( index !== null ) {
  22914. const indexData = this.get( index );
  22915. key += ':' + indexData.id;
  22916. }
  22917. for ( let i = 0; i < attributes.length; i ++ ) {
  22918. const attributeData = this.get( attributes[ i ] );
  22919. key += ':' + attributeData.id;
  22920. }
  22921. return key;
  22922. }
  22923. _createVao( index, attributes ) {
  22924. const { gl } = this;
  22925. const vaoGPU = gl.createVertexArray();
  22926. let key = '';
  22927. let staticVao = true;
  22928. gl.bindVertexArray( vaoGPU );
  22929. if ( index !== null ) {
  22930. const indexData = this.get( index );
  22931. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  22932. key += ':' + indexData.id;
  22933. }
  22934. for ( let i = 0; i < attributes.length; i ++ ) {
  22935. const attribute = attributes[ i ];
  22936. const attributeData = this.get( attribute );
  22937. key += ':' + attributeData.id;
  22938. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  22939. gl.enableVertexAttribArray( i );
  22940. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  22941. let stride, offset;
  22942. if ( attribute.isInterleavedBufferAttribute === true ) {
  22943. stride = attribute.data.stride * attributeData.bytesPerElement;
  22944. offset = attribute.offset * attributeData.bytesPerElement;
  22945. } else {
  22946. stride = 0;
  22947. offset = 0;
  22948. }
  22949. if ( attributeData.isInteger ) {
  22950. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  22951. } else {
  22952. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  22953. }
  22954. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  22955. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  22956. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  22957. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  22958. }
  22959. }
  22960. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  22961. this.vaoCache[ key ] = vaoGPU;
  22962. return { vaoGPU, staticVao };
  22963. }
  22964. _getTransformFeedback( transformBuffers ) {
  22965. let key = '';
  22966. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  22967. key += ':' + transformBuffers[ i ].id;
  22968. }
  22969. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  22970. if ( transformFeedbackGPU !== undefined ) {
  22971. return transformFeedbackGPU;
  22972. }
  22973. const { gl } = this;
  22974. transformFeedbackGPU = gl.createTransformFeedback();
  22975. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  22976. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  22977. const attributeData = transformBuffers[ i ];
  22978. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  22979. }
  22980. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  22981. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  22982. return transformFeedbackGPU;
  22983. }
  22984. _setupBindings( bindings, programGPU ) {
  22985. const gl = this.gl;
  22986. for ( const bindGroup of bindings ) {
  22987. for ( const binding of bindGroup.bindings ) {
  22988. const bindingData = this.get( binding );
  22989. const index = bindingData.index;
  22990. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  22991. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  22992. gl.uniformBlockBinding( programGPU, location, index );
  22993. } else if ( binding.isSampledTexture ) {
  22994. const location = gl.getUniformLocation( programGPU, binding.name );
  22995. gl.uniform1i( location, index );
  22996. }
  22997. }
  22998. }
  22999. }
  23000. _bindUniforms( bindings ) {
  23001. const { gl, state } = this;
  23002. for ( const bindGroup of bindings ) {
  23003. for ( const binding of bindGroup.bindings ) {
  23004. const bindingData = this.get( binding );
  23005. const index = bindingData.index;
  23006. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  23007. // TODO USE bindBufferRange to group multiple uniform buffers
  23008. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  23009. } else if ( binding.isSampledTexture ) {
  23010. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  23011. }
  23012. }
  23013. }
  23014. }
  23015. dispose() {
  23016. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  23017. }
  23018. }
  23019. const GPUPrimitiveTopology = {
  23020. PointList: 'point-list',
  23021. LineList: 'line-list',
  23022. LineStrip: 'line-strip',
  23023. TriangleList: 'triangle-list',
  23024. TriangleStrip: 'triangle-strip',
  23025. };
  23026. const GPUCompareFunction = {
  23027. Never: 'never',
  23028. Less: 'less',
  23029. Equal: 'equal',
  23030. LessEqual: 'less-equal',
  23031. Greater: 'greater',
  23032. NotEqual: 'not-equal',
  23033. GreaterEqual: 'greater-equal',
  23034. Always: 'always'
  23035. };
  23036. const GPUStoreOp = {
  23037. Store: 'store',
  23038. Discard: 'discard'
  23039. };
  23040. const GPULoadOp = {
  23041. Load: 'load',
  23042. Clear: 'clear'
  23043. };
  23044. const GPUFrontFace = {
  23045. CCW: 'ccw',
  23046. CW: 'cw'
  23047. };
  23048. const GPUCullMode = {
  23049. None: 'none',
  23050. Front: 'front',
  23051. Back: 'back'
  23052. };
  23053. const GPUIndexFormat = {
  23054. Uint16: 'uint16',
  23055. Uint32: 'uint32'
  23056. };
  23057. const GPUTextureFormat = {
  23058. // 8-bit formats
  23059. R8Unorm: 'r8unorm',
  23060. R8Snorm: 'r8snorm',
  23061. R8Uint: 'r8uint',
  23062. R8Sint: 'r8sint',
  23063. // 16-bit formats
  23064. R16Uint: 'r16uint',
  23065. R16Sint: 'r16sint',
  23066. R16Float: 'r16float',
  23067. RG8Unorm: 'rg8unorm',
  23068. RG8Snorm: 'rg8snorm',
  23069. RG8Uint: 'rg8uint',
  23070. RG8Sint: 'rg8sint',
  23071. // 32-bit formats
  23072. R32Uint: 'r32uint',
  23073. R32Sint: 'r32sint',
  23074. R32Float: 'r32float',
  23075. RG16Uint: 'rg16uint',
  23076. RG16Sint: 'rg16sint',
  23077. RG16Float: 'rg16float',
  23078. RGBA8Unorm: 'rgba8unorm',
  23079. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  23080. RGBA8Snorm: 'rgba8snorm',
  23081. RGBA8Uint: 'rgba8uint',
  23082. RGBA8Sint: 'rgba8sint',
  23083. BGRA8Unorm: 'bgra8unorm',
  23084. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  23085. // Packed 32-bit formats
  23086. RGB9E5UFloat: 'rgb9e5ufloat',
  23087. RGB10A2Unorm: 'rgb10a2unorm',
  23088. RG11B10uFloat: 'rgb10a2unorm',
  23089. // 64-bit formats
  23090. RG32Uint: 'rg32uint',
  23091. RG32Sint: 'rg32sint',
  23092. RG32Float: 'rg32float',
  23093. RGBA16Uint: 'rgba16uint',
  23094. RGBA16Sint: 'rgba16sint',
  23095. RGBA16Float: 'rgba16float',
  23096. // 128-bit formats
  23097. RGBA32Uint: 'rgba32uint',
  23098. RGBA32Sint: 'rgba32sint',
  23099. RGBA32Float: 'rgba32float',
  23100. // Depth and stencil formats
  23101. Stencil8: 'stencil8',
  23102. Depth16Unorm: 'depth16unorm',
  23103. Depth24Plus: 'depth24plus',
  23104. Depth24PlusStencil8: 'depth24plus-stencil8',
  23105. Depth32Float: 'depth32float',
  23106. // 'depth32float-stencil8' extension
  23107. Depth32FloatStencil8: 'depth32float-stencil8',
  23108. // BC compressed formats usable if 'texture-compression-bc' is both
  23109. // supported by the device/user agent and enabled in requestDevice.
  23110. BC1RGBAUnorm: 'bc1-rgba-unorm',
  23111. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  23112. BC2RGBAUnorm: 'bc2-rgba-unorm',
  23113. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  23114. BC3RGBAUnorm: 'bc3-rgba-unorm',
  23115. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  23116. BC4RUnorm: 'bc4-r-unorm',
  23117. BC4RSnorm: 'bc4-r-snorm',
  23118. BC5RGUnorm: 'bc5-rg-unorm',
  23119. BC5RGSnorm: 'bc5-rg-snorm',
  23120. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  23121. BC6HRGBFloat: 'bc6h-rgb-float',
  23122. BC7RGBAUnorm: 'bc7-rgba-unorm',
  23123. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  23124. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  23125. // supported by the device/user agent and enabled in requestDevice.
  23126. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  23127. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  23128. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  23129. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  23130. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  23131. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  23132. EACR11Unorm: 'eac-r11unorm',
  23133. EACR11Snorm: 'eac-r11snorm',
  23134. EACRG11Unorm: 'eac-rg11unorm',
  23135. EACRG11Snorm: 'eac-rg11snorm',
  23136. // ASTC compressed formats usable if 'texture-compression-astc' is both
  23137. // supported by the device/user agent and enabled in requestDevice.
  23138. ASTC4x4Unorm: 'astc-4x4-unorm',
  23139. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  23140. ASTC5x4Unorm: 'astc-5x4-unorm',
  23141. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  23142. ASTC5x5Unorm: 'astc-5x5-unorm',
  23143. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  23144. ASTC6x5Unorm: 'astc-6x5-unorm',
  23145. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  23146. ASTC6x6Unorm: 'astc-6x6-unorm',
  23147. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  23148. ASTC8x5Unorm: 'astc-8x5-unorm',
  23149. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  23150. ASTC8x6Unorm: 'astc-8x6-unorm',
  23151. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  23152. ASTC8x8Unorm: 'astc-8x8-unorm',
  23153. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  23154. ASTC10x5Unorm: 'astc-10x5-unorm',
  23155. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  23156. ASTC10x6Unorm: 'astc-10x6-unorm',
  23157. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  23158. ASTC10x8Unorm: 'astc-10x8-unorm',
  23159. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  23160. ASTC10x10Unorm: 'astc-10x10-unorm',
  23161. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  23162. ASTC12x10Unorm: 'astc-12x10-unorm',
  23163. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  23164. ASTC12x12Unorm: 'astc-12x12-unorm',
  23165. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  23166. };
  23167. const GPUAddressMode = {
  23168. ClampToEdge: 'clamp-to-edge',
  23169. Repeat: 'repeat',
  23170. MirrorRepeat: 'mirror-repeat'
  23171. };
  23172. const GPUFilterMode = {
  23173. Linear: 'linear',
  23174. Nearest: 'nearest'
  23175. };
  23176. const GPUBlendFactor = {
  23177. Zero: 'zero',
  23178. One: 'one',
  23179. Src: 'src',
  23180. OneMinusSrc: 'one-minus-src',
  23181. SrcAlpha: 'src-alpha',
  23182. OneMinusSrcAlpha: 'one-minus-src-alpha',
  23183. Dst: 'dst',
  23184. OneMinusDstColor: 'one-minus-dst',
  23185. DstAlpha: 'dst-alpha',
  23186. OneMinusDstAlpha: 'one-minus-dst-alpha',
  23187. SrcAlphaSaturated: 'src-alpha-saturated',
  23188. Constant: 'constant',
  23189. OneMinusConstant: 'one-minus-constant'
  23190. };
  23191. const GPUBlendOperation = {
  23192. Add: 'add',
  23193. Subtract: 'subtract',
  23194. ReverseSubtract: 'reverse-subtract',
  23195. Min: 'min',
  23196. Max: 'max'
  23197. };
  23198. const GPUColorWriteFlags = {
  23199. None: 0,
  23200. Red: 0x1,
  23201. Green: 0x2,
  23202. Blue: 0x4,
  23203. Alpha: 0x8,
  23204. All: 0xF
  23205. };
  23206. const GPUStencilOperation = {
  23207. Keep: 'keep',
  23208. Zero: 'zero',
  23209. Replace: 'replace',
  23210. Invert: 'invert',
  23211. IncrementClamp: 'increment-clamp',
  23212. DecrementClamp: 'decrement-clamp',
  23213. IncrementWrap: 'increment-wrap',
  23214. DecrementWrap: 'decrement-wrap'
  23215. };
  23216. const GPUBufferBindingType = {
  23217. Uniform: 'uniform',
  23218. Storage: 'storage',
  23219. ReadOnlyStorage: 'read-only-storage'
  23220. };
  23221. const GPUStorageTextureAccess = {
  23222. WriteOnly: 'write-only',
  23223. ReadOnly: 'read-only',
  23224. ReadWrite: 'read-write',
  23225. };
  23226. const GPUTextureSampleType = {
  23227. Float: 'float',
  23228. UnfilterableFloat: 'unfilterable-float',
  23229. Depth: 'depth',
  23230. SInt: 'sint',
  23231. UInt: 'uint'
  23232. };
  23233. const GPUTextureDimension = {
  23234. OneD: '1d',
  23235. TwoD: '2d',
  23236. ThreeD: '3d'
  23237. };
  23238. const GPUTextureViewDimension = {
  23239. OneD: '1d',
  23240. TwoD: '2d',
  23241. TwoDArray: '2d-array',
  23242. Cube: 'cube',
  23243. CubeArray: 'cube-array',
  23244. ThreeD: '3d'
  23245. };
  23246. const GPUTextureAspect = {
  23247. All: 'all',
  23248. StencilOnly: 'stencil-only',
  23249. DepthOnly: 'depth-only'
  23250. };
  23251. const GPUInputStepMode = {
  23252. Vertex: 'vertex',
  23253. Instance: 'instance'
  23254. };
  23255. const GPUFeatureName = {
  23256. DepthClipControl: 'depth-clip-control',
  23257. Depth32FloatStencil8: 'depth32float-stencil8',
  23258. TextureCompressionBC: 'texture-compression-bc',
  23259. TextureCompressionETC2: 'texture-compression-etc2',
  23260. TextureCompressionASTC: 'texture-compression-astc',
  23261. TimestampQuery: 'timestamp-query',
  23262. IndirectFirstInstance: 'indirect-first-instance',
  23263. ShaderF16: 'shader-f16',
  23264. RG11B10UFloat: 'rg11b10ufloat-renderable',
  23265. BGRA8UNormStorage: 'bgra8unorm-storage',
  23266. Float32Filterable: 'float32-filterable',
  23267. ClipDistances: 'clip-distances',
  23268. DualSourceBlending: 'dual-source-blending',
  23269. Subgroups: 'subgroups'
  23270. };
  23271. class Sampler extends Binding {
  23272. constructor( name, texture ) {
  23273. super( name );
  23274. this.texture = texture;
  23275. this.version = texture ? texture.version : 0;
  23276. this.isSampler = true;
  23277. }
  23278. }
  23279. class NodeSampler extends Sampler {
  23280. constructor( name, textureNode, groupNode ) {
  23281. super( name, textureNode ? textureNode.value : null );
  23282. this.textureNode = textureNode;
  23283. this.groupNode = groupNode;
  23284. }
  23285. update() {
  23286. this.texture = this.textureNode.value;
  23287. }
  23288. }
  23289. class StorageBuffer extends Buffer {
  23290. constructor( name, attribute ) {
  23291. super( name, attribute ? attribute.array : null );
  23292. this.attribute = attribute;
  23293. this.isStorageBuffer = true;
  23294. }
  23295. }
  23296. let _id = 0;
  23297. class NodeStorageBuffer extends StorageBuffer {
  23298. constructor( nodeUniform, groupNode ) {
  23299. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  23300. this.nodeUniform = nodeUniform;
  23301. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  23302. this.groupNode = groupNode;
  23303. }
  23304. get buffer() {
  23305. return this.nodeUniform.value;
  23306. }
  23307. }
  23308. class WebGPUTexturePassUtils extends DataMap {
  23309. constructor( device ) {
  23310. super();
  23311. this.device = device;
  23312. const mipmapVertexSource = `
  23313. struct VarysStruct {
  23314. @builtin( position ) Position: vec4<f32>,
  23315. @location( 0 ) vTex : vec2<f32>
  23316. };
  23317. @vertex
  23318. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  23319. var Varys : VarysStruct;
  23320. var pos = array< vec2<f32>, 4 >(
  23321. vec2<f32>( -1.0, 1.0 ),
  23322. vec2<f32>( 1.0, 1.0 ),
  23323. vec2<f32>( -1.0, -1.0 ),
  23324. vec2<f32>( 1.0, -1.0 )
  23325. );
  23326. var tex = array< vec2<f32>, 4 >(
  23327. vec2<f32>( 0.0, 0.0 ),
  23328. vec2<f32>( 1.0, 0.0 ),
  23329. vec2<f32>( 0.0, 1.0 ),
  23330. vec2<f32>( 1.0, 1.0 )
  23331. );
  23332. Varys.vTex = tex[ vertexIndex ];
  23333. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  23334. return Varys;
  23335. }
  23336. `;
  23337. const mipmapFragmentSource = `
  23338. @group( 0 ) @binding( 0 )
  23339. var imgSampler : sampler;
  23340. @group( 0 ) @binding( 1 )
  23341. var img : texture_2d<f32>;
  23342. @fragment
  23343. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  23344. return textureSample( img, imgSampler, vTex );
  23345. }
  23346. `;
  23347. const flipYFragmentSource = `
  23348. @group( 0 ) @binding( 0 )
  23349. var imgSampler : sampler;
  23350. @group( 0 ) @binding( 1 )
  23351. var img : texture_2d<f32>;
  23352. @fragment
  23353. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  23354. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  23355. }
  23356. `;
  23357. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  23358. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  23359. // We'll need a new pipeline for every texture format used.
  23360. this.transferPipelines = {};
  23361. this.flipYPipelines = {};
  23362. this.mipmapVertexShaderModule = device.createShaderModule( {
  23363. label: 'mipmapVertex',
  23364. code: mipmapVertexSource
  23365. } );
  23366. this.mipmapFragmentShaderModule = device.createShaderModule( {
  23367. label: 'mipmapFragment',
  23368. code: mipmapFragmentSource
  23369. } );
  23370. this.flipYFragmentShaderModule = device.createShaderModule( {
  23371. label: 'flipYFragment',
  23372. code: flipYFragmentSource
  23373. } );
  23374. }
  23375. getTransferPipeline( format ) {
  23376. let pipeline = this.transferPipelines[ format ];
  23377. if ( pipeline === undefined ) {
  23378. pipeline = this.device.createRenderPipeline( {
  23379. label: `mipmap-${ format }`,
  23380. vertex: {
  23381. module: this.mipmapVertexShaderModule,
  23382. entryPoint: 'main'
  23383. },
  23384. fragment: {
  23385. module: this.mipmapFragmentShaderModule,
  23386. entryPoint: 'main',
  23387. targets: [ { format } ]
  23388. },
  23389. primitive: {
  23390. topology: GPUPrimitiveTopology.TriangleStrip,
  23391. stripIndexFormat: GPUIndexFormat.Uint32
  23392. },
  23393. layout: 'auto'
  23394. } );
  23395. this.transferPipelines[ format ] = pipeline;
  23396. }
  23397. return pipeline;
  23398. }
  23399. getFlipYPipeline( format ) {
  23400. let pipeline = this.flipYPipelines[ format ];
  23401. if ( pipeline === undefined ) {
  23402. pipeline = this.device.createRenderPipeline( {
  23403. label: `flipY-${ format }`,
  23404. vertex: {
  23405. module: this.mipmapVertexShaderModule,
  23406. entryPoint: 'main'
  23407. },
  23408. fragment: {
  23409. module: this.flipYFragmentShaderModule,
  23410. entryPoint: 'main',
  23411. targets: [ { format } ]
  23412. },
  23413. primitive: {
  23414. topology: GPUPrimitiveTopology.TriangleStrip,
  23415. stripIndexFormat: GPUIndexFormat.Uint32
  23416. },
  23417. layout: 'auto'
  23418. } );
  23419. this.flipYPipelines[ format ] = pipeline;
  23420. }
  23421. return pipeline;
  23422. }
  23423. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  23424. const format = textureGPUDescriptor.format;
  23425. const { width, height } = textureGPUDescriptor.size;
  23426. const transferPipeline = this.getTransferPipeline( format );
  23427. const flipYPipeline = this.getFlipYPipeline( format );
  23428. const tempTexture = this.device.createTexture( {
  23429. size: { width, height, depthOrArrayLayers: 1 },
  23430. format,
  23431. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  23432. } );
  23433. const srcView = textureGPU.createView( {
  23434. baseMipLevel: 0,
  23435. mipLevelCount: 1,
  23436. dimension: GPUTextureViewDimension.TwoD,
  23437. baseArrayLayer
  23438. } );
  23439. const dstView = tempTexture.createView( {
  23440. baseMipLevel: 0,
  23441. mipLevelCount: 1,
  23442. dimension: GPUTextureViewDimension.TwoD,
  23443. baseArrayLayer: 0
  23444. } );
  23445. const commandEncoder = this.device.createCommandEncoder( {} );
  23446. const pass = ( pipeline, sourceView, destinationView ) => {
  23447. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  23448. const bindGroup = this.device.createBindGroup( {
  23449. layout: bindGroupLayout,
  23450. entries: [ {
  23451. binding: 0,
  23452. resource: this.flipYSampler
  23453. }, {
  23454. binding: 1,
  23455. resource: sourceView
  23456. } ]
  23457. } );
  23458. const passEncoder = commandEncoder.beginRenderPass( {
  23459. colorAttachments: [ {
  23460. view: destinationView,
  23461. loadOp: GPULoadOp.Clear,
  23462. storeOp: GPUStoreOp.Store,
  23463. clearValue: [ 0, 0, 0, 0 ]
  23464. } ]
  23465. } );
  23466. passEncoder.setPipeline( pipeline );
  23467. passEncoder.setBindGroup( 0, bindGroup );
  23468. passEncoder.draw( 4, 1, 0, 0 );
  23469. passEncoder.end();
  23470. };
  23471. pass( transferPipeline, srcView, dstView );
  23472. pass( flipYPipeline, dstView, srcView );
  23473. this.device.queue.submit( [ commandEncoder.finish() ] );
  23474. tempTexture.destroy();
  23475. }
  23476. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  23477. const textureData = this.get( textureGPU );
  23478. if ( textureData.useCount === undefined ) {
  23479. textureData.useCount = 0;
  23480. textureData.layers = [];
  23481. }
  23482. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  23483. const commandEncoder = this.device.createCommandEncoder( {} );
  23484. this._mipmapRunBundles( commandEncoder, passes );
  23485. this.device.queue.submit( [ commandEncoder.finish() ] );
  23486. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  23487. textureData.useCount ++;
  23488. }
  23489. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  23490. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  23491. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  23492. let srcView = textureGPU.createView( {
  23493. baseMipLevel: 0,
  23494. mipLevelCount: 1,
  23495. dimension: GPUTextureViewDimension.TwoD,
  23496. baseArrayLayer
  23497. } );
  23498. const passes = [];
  23499. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  23500. const bindGroup = this.device.createBindGroup( {
  23501. layout: bindGroupLayout,
  23502. entries: [ {
  23503. binding: 0,
  23504. resource: this.mipmapSampler
  23505. }, {
  23506. binding: 1,
  23507. resource: srcView
  23508. } ]
  23509. } );
  23510. const dstView = textureGPU.createView( {
  23511. baseMipLevel: i,
  23512. mipLevelCount: 1,
  23513. dimension: GPUTextureViewDimension.TwoD,
  23514. baseArrayLayer
  23515. } );
  23516. const passDescriptor = {
  23517. colorAttachments: [ {
  23518. view: dstView,
  23519. loadOp: GPULoadOp.Clear,
  23520. storeOp: GPUStoreOp.Store,
  23521. clearValue: [ 0, 0, 0, 0 ]
  23522. } ]
  23523. };
  23524. const passEncoder = this.device.createRenderBundleEncoder( {
  23525. colorFormats: [ textureGPUDescriptor.format ]
  23526. } );
  23527. passEncoder.setPipeline( pipeline );
  23528. passEncoder.setBindGroup( 0, bindGroup );
  23529. passEncoder.draw( 4, 1, 0, 0 );
  23530. passes.push( {
  23531. renderBundles: [ passEncoder.finish() ],
  23532. passDescriptor
  23533. } );
  23534. srcView = dstView;
  23535. }
  23536. return passes;
  23537. }
  23538. _mipmapRunBundles( commandEncoder, passes ) {
  23539. const levels = passes.length;
  23540. for ( let i = 0; i < levels; i ++ ) {
  23541. const pass = passes[ i ];
  23542. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  23543. passEncoder.executeBundles( pass.renderBundles );
  23544. passEncoder.end();
  23545. }
  23546. }
  23547. }
  23548. const _compareToWebGPU = {
  23549. [ NeverCompare ]: 'never',
  23550. [ LessCompare ]: 'less',
  23551. [ EqualCompare ]: 'equal',
  23552. [ LessEqualCompare ]: 'less-equal',
  23553. [ GreaterCompare ]: 'greater',
  23554. [ GreaterEqualCompare ]: 'greater-equal',
  23555. [ AlwaysCompare ]: 'always',
  23556. [ NotEqualCompare ]: 'not-equal'
  23557. };
  23558. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  23559. class WebGPUTextureUtils {
  23560. constructor( backend ) {
  23561. this.backend = backend;
  23562. this._passUtils = null;
  23563. this.defaultTexture = {};
  23564. this.defaultCubeTexture = {};
  23565. this.defaultVideoFrame = null;
  23566. this.colorBuffer = null;
  23567. this.depthTexture = new DepthTexture();
  23568. this.depthTexture.name = 'depthBuffer';
  23569. }
  23570. createSampler( texture ) {
  23571. const backend = this.backend;
  23572. const device = backend.device;
  23573. const textureGPU = backend.get( texture );
  23574. const samplerDescriptorGPU = {
  23575. addressModeU: this._convertAddressMode( texture.wrapS ),
  23576. addressModeV: this._convertAddressMode( texture.wrapT ),
  23577. addressModeW: this._convertAddressMode( texture.wrapR ),
  23578. magFilter: this._convertFilterMode( texture.magFilter ),
  23579. minFilter: this._convertFilterMode( texture.minFilter ),
  23580. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  23581. maxAnisotropy: 1
  23582. };
  23583. // anisotropy can only be used when all filter modes are set to linear.
  23584. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  23585. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  23586. }
  23587. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  23588. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  23589. }
  23590. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  23591. }
  23592. createDefaultTexture( texture ) {
  23593. let textureGPU;
  23594. const format = getFormat( texture );
  23595. if ( texture.isCubeTexture ) {
  23596. textureGPU = this._getDefaultCubeTextureGPU( format );
  23597. } else if ( texture.isVideoTexture ) {
  23598. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  23599. } else {
  23600. textureGPU = this._getDefaultTextureGPU( format );
  23601. }
  23602. this.backend.get( texture ).texture = textureGPU;
  23603. }
  23604. createTexture( texture, options = {} ) {
  23605. const backend = this.backend;
  23606. const textureData = backend.get( texture );
  23607. if ( textureData.initialized ) {
  23608. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  23609. }
  23610. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  23611. if ( options.levels === undefined ) options.levels = 1;
  23612. if ( options.depth === undefined ) options.depth = 1;
  23613. const { width, height, depth, levels } = options;
  23614. if ( texture.isFramebufferTexture ) {
  23615. if ( options.renderTarget ) {
  23616. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  23617. } else {
  23618. options.format = this.backend.utils.getPreferredCanvasFormat();
  23619. }
  23620. }
  23621. const dimension = this._getDimension( texture );
  23622. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  23623. textureData.format = format;
  23624. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  23625. sampleCount = backend.utils.getSampleCount( sampleCount );
  23626. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  23627. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  23628. if ( texture.isStorageTexture === true ) {
  23629. usage |= GPUTextureUsage.STORAGE_BINDING;
  23630. }
  23631. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  23632. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  23633. }
  23634. const textureDescriptorGPU = {
  23635. label: texture.name,
  23636. size: {
  23637. width: width,
  23638. height: height,
  23639. depthOrArrayLayers: depth,
  23640. },
  23641. mipLevelCount: levels,
  23642. sampleCount: primarySampleCount,
  23643. dimension: dimension,
  23644. format: format,
  23645. usage: usage
  23646. };
  23647. // texture creation
  23648. if ( texture.isVideoTexture ) {
  23649. const video = texture.source.data;
  23650. const videoFrame = new VideoFrame( video );
  23651. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  23652. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  23653. videoFrame.close();
  23654. textureData.externalTexture = video;
  23655. } else {
  23656. if ( format === undefined ) {
  23657. console.warn( 'WebGPURenderer: Texture format not supported.' );
  23658. return this.createDefaultTexture( texture );
  23659. }
  23660. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  23661. }
  23662. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  23663. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  23664. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  23665. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  23666. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  23667. }
  23668. textureData.initialized = true;
  23669. textureData.textureDescriptorGPU = textureDescriptorGPU;
  23670. }
  23671. destroyTexture( texture ) {
  23672. const backend = this.backend;
  23673. const textureData = backend.get( texture );
  23674. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  23675. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  23676. backend.delete( texture );
  23677. }
  23678. destroySampler( texture ) {
  23679. const backend = this.backend;
  23680. const textureData = backend.get( texture );
  23681. delete textureData.sampler;
  23682. }
  23683. generateMipmaps( texture ) {
  23684. const textureData = this.backend.get( texture );
  23685. if ( texture.isCubeTexture ) {
  23686. for ( let i = 0; i < 6; i ++ ) {
  23687. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  23688. }
  23689. } else {
  23690. const depth = texture.image.depth || 1;
  23691. for ( let i = 0; i < depth; i ++ ) {
  23692. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  23693. }
  23694. }
  23695. }
  23696. getColorBuffer() {
  23697. if ( this.colorBuffer ) this.colorBuffer.destroy();
  23698. const backend = this.backend;
  23699. const { width, height } = backend.getDrawingBufferSize();
  23700. this.colorBuffer = backend.device.createTexture( {
  23701. label: 'colorBuffer',
  23702. size: {
  23703. width: width,
  23704. height: height,
  23705. depthOrArrayLayers: 1
  23706. },
  23707. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  23708. format: backend.utils.getPreferredCanvasFormat(),
  23709. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  23710. } );
  23711. return this.colorBuffer;
  23712. }
  23713. getDepthBuffer( depth = true, stencil = false ) {
  23714. const backend = this.backend;
  23715. const { width, height } = backend.getDrawingBufferSize();
  23716. const depthTexture = this.depthTexture;
  23717. const depthTextureGPU = backend.get( depthTexture ).texture;
  23718. let format, type;
  23719. if ( stencil ) {
  23720. format = DepthStencilFormat;
  23721. type = UnsignedInt248Type;
  23722. } else if ( depth ) {
  23723. format = DepthFormat;
  23724. type = UnsignedIntType;
  23725. }
  23726. if ( depthTextureGPU !== undefined ) {
  23727. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  23728. return depthTextureGPU;
  23729. }
  23730. this.destroyTexture( depthTexture );
  23731. }
  23732. depthTexture.name = 'depthBuffer';
  23733. depthTexture.format = format;
  23734. depthTexture.type = type;
  23735. depthTexture.image.width = width;
  23736. depthTexture.image.height = height;
  23737. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  23738. return backend.get( depthTexture ).texture;
  23739. }
  23740. updateTexture( texture, options ) {
  23741. const textureData = this.backend.get( texture );
  23742. const { textureDescriptorGPU } = textureData;
  23743. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  23744. return;
  23745. // transfer texture data
  23746. if ( texture.isDataTexture ) {
  23747. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  23748. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  23749. for ( let i = 0; i < options.image.depth; i ++ ) {
  23750. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  23751. }
  23752. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  23753. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  23754. } else if ( texture.isCubeTexture ) {
  23755. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  23756. } else if ( texture.isVideoTexture ) {
  23757. const video = texture.source.data;
  23758. textureData.externalTexture = video;
  23759. } else {
  23760. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  23761. }
  23762. //
  23763. textureData.version = texture.version;
  23764. if ( texture.onUpdate ) texture.onUpdate( texture );
  23765. }
  23766. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  23767. const device = this.backend.device;
  23768. const textureData = this.backend.get( texture );
  23769. const textureGPU = textureData.texture;
  23770. const format = textureData.textureDescriptorGPU.format;
  23771. const bytesPerTexel = this._getBytesPerTexel( format );
  23772. let bytesPerRow = width * bytesPerTexel;
  23773. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  23774. const readBuffer = device.createBuffer(
  23775. {
  23776. size: width * height * bytesPerTexel,
  23777. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  23778. }
  23779. );
  23780. const encoder = device.createCommandEncoder();
  23781. encoder.copyTextureToBuffer(
  23782. {
  23783. texture: textureGPU,
  23784. origin: { x, y, z: faceIndex },
  23785. },
  23786. {
  23787. buffer: readBuffer,
  23788. bytesPerRow: bytesPerRow
  23789. },
  23790. {
  23791. width: width,
  23792. height: height
  23793. }
  23794. );
  23795. const typedArrayType = this._getTypedArrayType( format );
  23796. device.queue.submit( [ encoder.finish() ] );
  23797. await readBuffer.mapAsync( GPUMapMode.READ );
  23798. const buffer = readBuffer.getMappedRange();
  23799. return new typedArrayType( buffer );
  23800. }
  23801. _isEnvironmentTexture( texture ) {
  23802. const mapping = texture.mapping;
  23803. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  23804. }
  23805. _getDefaultTextureGPU( format ) {
  23806. let defaultTexture = this.defaultTexture[ format ];
  23807. if ( defaultTexture === undefined ) {
  23808. const texture = new Texture();
  23809. texture.minFilter = NearestFilter;
  23810. texture.magFilter = NearestFilter;
  23811. this.createTexture( texture, { width: 1, height: 1, format } );
  23812. this.defaultTexture[ format ] = defaultTexture = texture;
  23813. }
  23814. return this.backend.get( defaultTexture ).texture;
  23815. }
  23816. _getDefaultCubeTextureGPU( format ) {
  23817. let defaultCubeTexture = this.defaultTexture[ format ];
  23818. if ( defaultCubeTexture === undefined ) {
  23819. const texture = new CubeTexture();
  23820. texture.minFilter = NearestFilter;
  23821. texture.magFilter = NearestFilter;
  23822. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  23823. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  23824. }
  23825. return this.backend.get( defaultCubeTexture ).texture;
  23826. }
  23827. _getDefaultVideoFrame() {
  23828. let defaultVideoFrame = this.defaultVideoFrame;
  23829. if ( defaultVideoFrame === null ) {
  23830. const init = {
  23831. timestamp: 0,
  23832. codedWidth: 1,
  23833. codedHeight: 1,
  23834. format: 'RGBA',
  23835. };
  23836. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  23837. }
  23838. return defaultVideoFrame;
  23839. }
  23840. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  23841. for ( let i = 0; i < 6; i ++ ) {
  23842. const image = images[ i ];
  23843. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  23844. if ( image.isDataTexture ) {
  23845. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  23846. } else {
  23847. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  23848. }
  23849. }
  23850. }
  23851. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  23852. const device = this.backend.device;
  23853. device.queue.copyExternalImageToTexture(
  23854. {
  23855. source: image
  23856. }, {
  23857. texture: textureGPU,
  23858. mipLevel: 0,
  23859. origin: { x: 0, y: 0, z: originDepth }
  23860. }, {
  23861. width: image.width,
  23862. height: image.height,
  23863. depthOrArrayLayers: 1
  23864. }
  23865. );
  23866. if ( flipY === true ) {
  23867. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  23868. }
  23869. }
  23870. _getPassUtils() {
  23871. let passUtils = this._passUtils;
  23872. if ( passUtils === null ) {
  23873. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  23874. }
  23875. return passUtils;
  23876. }
  23877. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  23878. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  23879. }
  23880. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  23881. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  23882. }
  23883. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  23884. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  23885. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  23886. const device = this.backend.device;
  23887. const data = image.data;
  23888. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  23889. const bytesPerRow = image.width * bytesPerTexel;
  23890. device.queue.writeTexture(
  23891. {
  23892. texture: textureGPU,
  23893. mipLevel: 0,
  23894. origin: { x: 0, y: 0, z: originDepth }
  23895. },
  23896. data,
  23897. {
  23898. offset: image.width * image.height * bytesPerTexel * depth,
  23899. bytesPerRow
  23900. },
  23901. {
  23902. width: image.width,
  23903. height: image.height,
  23904. depthOrArrayLayers: 1
  23905. } );
  23906. if ( flipY === true ) {
  23907. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  23908. }
  23909. }
  23910. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  23911. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  23912. const device = this.backend.device;
  23913. const blockData = this._getBlockData( textureDescriptorGPU.format );
  23914. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  23915. for ( let i = 0; i < mipmaps.length; i ++ ) {
  23916. const mipmap = mipmaps[ i ];
  23917. const width = mipmap.width;
  23918. const height = mipmap.height;
  23919. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  23920. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  23921. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  23922. for ( let j = 0; j < depth; j ++ ) {
  23923. device.queue.writeTexture(
  23924. {
  23925. texture: textureGPU,
  23926. mipLevel: i,
  23927. origin: { x: 0, y: 0, z: j }
  23928. },
  23929. mipmap.data,
  23930. {
  23931. offset: j * bytesPerImage,
  23932. bytesPerRow,
  23933. rowsPerImage: Math.ceil( height / blockData.height )
  23934. },
  23935. {
  23936. width: Math.ceil( width / blockData.width ) * blockData.width,
  23937. height: Math.ceil( height / blockData.height ) * blockData.height,
  23938. depthOrArrayLayers: 1
  23939. }
  23940. );
  23941. }
  23942. }
  23943. }
  23944. _getBlockData( format ) {
  23945. // this method is only relevant for compressed texture formats
  23946. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  23947. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  23948. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  23949. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  23950. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  23951. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  23952. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  23953. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  23954. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  23955. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  23956. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  23957. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  23958. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  23959. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  23960. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  23961. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  23962. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  23963. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  23964. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  23965. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  23966. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  23967. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  23968. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  23969. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  23970. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  23971. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  23972. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  23973. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  23974. }
  23975. _convertAddressMode( value ) {
  23976. let addressMode = GPUAddressMode.ClampToEdge;
  23977. if ( value === RepeatWrapping ) {
  23978. addressMode = GPUAddressMode.Repeat;
  23979. } else if ( value === MirroredRepeatWrapping ) {
  23980. addressMode = GPUAddressMode.MirrorRepeat;
  23981. }
  23982. return addressMode;
  23983. }
  23984. _convertFilterMode( value ) {
  23985. let filterMode = GPUFilterMode.Linear;
  23986. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  23987. filterMode = GPUFilterMode.Nearest;
  23988. }
  23989. return filterMode;
  23990. }
  23991. _getBytesPerTexel( format ) {
  23992. // 8-bit formats
  23993. if ( format === GPUTextureFormat.R8Unorm ||
  23994. format === GPUTextureFormat.R8Snorm ||
  23995. format === GPUTextureFormat.R8Uint ||
  23996. format === GPUTextureFormat.R8Sint ) return 1;
  23997. // 16-bit formats
  23998. if ( format === GPUTextureFormat.R16Uint ||
  23999. format === GPUTextureFormat.R16Sint ||
  24000. format === GPUTextureFormat.R16Float ||
  24001. format === GPUTextureFormat.RG8Unorm ||
  24002. format === GPUTextureFormat.RG8Snorm ||
  24003. format === GPUTextureFormat.RG8Uint ||
  24004. format === GPUTextureFormat.RG8Sint ) return 2;
  24005. // 32-bit formats
  24006. if ( format === GPUTextureFormat.R32Uint ||
  24007. format === GPUTextureFormat.R32Sint ||
  24008. format === GPUTextureFormat.R32Float ||
  24009. format === GPUTextureFormat.RG16Uint ||
  24010. format === GPUTextureFormat.RG16Sint ||
  24011. format === GPUTextureFormat.RG16Float ||
  24012. format === GPUTextureFormat.RGBA8Unorm ||
  24013. format === GPUTextureFormat.RGBA8UnormSRGB ||
  24014. format === GPUTextureFormat.RGBA8Snorm ||
  24015. format === GPUTextureFormat.RGBA8Uint ||
  24016. format === GPUTextureFormat.RGBA8Sint ||
  24017. format === GPUTextureFormat.BGRA8Unorm ||
  24018. format === GPUTextureFormat.BGRA8UnormSRGB ||
  24019. // Packed 32-bit formats
  24020. format === GPUTextureFormat.RGB9E5UFloat ||
  24021. format === GPUTextureFormat.RGB10A2Unorm ||
  24022. format === GPUTextureFormat.RG11B10UFloat ||
  24023. format === GPUTextureFormat.Depth32Float ||
  24024. format === GPUTextureFormat.Depth24Plus ||
  24025. format === GPUTextureFormat.Depth24PlusStencil8 ||
  24026. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  24027. // 64-bit formats
  24028. if ( format === GPUTextureFormat.RG32Uint ||
  24029. format === GPUTextureFormat.RG32Sint ||
  24030. format === GPUTextureFormat.RG32Float ||
  24031. format === GPUTextureFormat.RGBA16Uint ||
  24032. format === GPUTextureFormat.RGBA16Sint ||
  24033. format === GPUTextureFormat.RGBA16Float ) return 8;
  24034. // 128-bit formats
  24035. if ( format === GPUTextureFormat.RGBA32Uint ||
  24036. format === GPUTextureFormat.RGBA32Sint ||
  24037. format === GPUTextureFormat.RGBA32Float ) return 16;
  24038. }
  24039. _getTypedArrayType( format ) {
  24040. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  24041. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  24042. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  24043. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  24044. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  24045. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  24046. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  24047. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  24048. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  24049. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  24050. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  24051. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  24052. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  24053. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  24054. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  24055. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  24056. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  24057. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  24058. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  24059. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  24060. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  24061. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  24062. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  24063. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  24064. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  24065. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  24066. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  24067. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  24068. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  24069. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  24070. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  24071. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  24072. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  24073. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  24074. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  24075. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  24076. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  24077. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  24078. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  24079. }
  24080. _getDimension( texture ) {
  24081. let dimension;
  24082. if ( texture.isData3DTexture ) {
  24083. dimension = GPUTextureDimension.ThreeD;
  24084. } else {
  24085. dimension = GPUTextureDimension.TwoD;
  24086. }
  24087. return dimension;
  24088. }
  24089. }
  24090. function getFormat( texture, device = null ) {
  24091. const format = texture.format;
  24092. const type = texture.type;
  24093. const colorSpace = texture.colorSpace;
  24094. let formatGPU;
  24095. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  24096. switch ( format ) {
  24097. case RGBA_S3TC_DXT1_Format:
  24098. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  24099. break;
  24100. case RGBA_S3TC_DXT3_Format:
  24101. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  24102. break;
  24103. case RGBA_S3TC_DXT5_Format:
  24104. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  24105. break;
  24106. case RGB_ETC2_Format:
  24107. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  24108. break;
  24109. case RGBA_ETC2_EAC_Format:
  24110. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  24111. break;
  24112. case RGBA_ASTC_4x4_Format:
  24113. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  24114. break;
  24115. case RGBA_ASTC_5x4_Format:
  24116. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  24117. break;
  24118. case RGBA_ASTC_5x5_Format:
  24119. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  24120. break;
  24121. case RGBA_ASTC_6x5_Format:
  24122. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  24123. break;
  24124. case RGBA_ASTC_6x6_Format:
  24125. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  24126. break;
  24127. case RGBA_ASTC_8x5_Format:
  24128. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  24129. break;
  24130. case RGBA_ASTC_8x6_Format:
  24131. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  24132. break;
  24133. case RGBA_ASTC_8x8_Format:
  24134. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  24135. break;
  24136. case RGBA_ASTC_10x5_Format:
  24137. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  24138. break;
  24139. case RGBA_ASTC_10x6_Format:
  24140. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  24141. break;
  24142. case RGBA_ASTC_10x8_Format:
  24143. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  24144. break;
  24145. case RGBA_ASTC_10x10_Format:
  24146. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  24147. break;
  24148. case RGBA_ASTC_12x10_Format:
  24149. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  24150. break;
  24151. case RGBA_ASTC_12x12_Format:
  24152. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  24153. break;
  24154. case RGBAFormat:
  24155. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  24156. break;
  24157. default:
  24158. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  24159. }
  24160. } else {
  24161. switch ( format ) {
  24162. case RGBAFormat:
  24163. switch ( type ) {
  24164. case ByteType:
  24165. formatGPU = GPUTextureFormat.RGBA8Snorm;
  24166. break;
  24167. case ShortType:
  24168. formatGPU = GPUTextureFormat.RGBA16Sint;
  24169. break;
  24170. case UnsignedShortType:
  24171. formatGPU = GPUTextureFormat.RGBA16Uint;
  24172. break;
  24173. case UnsignedIntType:
  24174. formatGPU = GPUTextureFormat.RGBA32Uint;
  24175. break;
  24176. case IntType:
  24177. formatGPU = GPUTextureFormat.RGBA32Sint;
  24178. break;
  24179. case UnsignedByteType:
  24180. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  24181. break;
  24182. case HalfFloatType:
  24183. formatGPU = GPUTextureFormat.RGBA16Float;
  24184. break;
  24185. case FloatType:
  24186. formatGPU = GPUTextureFormat.RGBA32Float;
  24187. break;
  24188. default:
  24189. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  24190. }
  24191. break;
  24192. case RGBFormat:
  24193. switch ( type ) {
  24194. case UnsignedInt5999Type:
  24195. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  24196. break;
  24197. default:
  24198. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  24199. }
  24200. break;
  24201. case RedFormat:
  24202. switch ( type ) {
  24203. case ByteType:
  24204. formatGPU = GPUTextureFormat.R8Snorm;
  24205. break;
  24206. case ShortType:
  24207. formatGPU = GPUTextureFormat.R16Sint;
  24208. break;
  24209. case UnsignedShortType:
  24210. formatGPU = GPUTextureFormat.R16Uint;
  24211. break;
  24212. case UnsignedIntType:
  24213. formatGPU = GPUTextureFormat.R32Uint;
  24214. break;
  24215. case IntType:
  24216. formatGPU = GPUTextureFormat.R32Sint;
  24217. break;
  24218. case UnsignedByteType:
  24219. formatGPU = GPUTextureFormat.R8Unorm;
  24220. break;
  24221. case HalfFloatType:
  24222. formatGPU = GPUTextureFormat.R16Float;
  24223. break;
  24224. case FloatType:
  24225. formatGPU = GPUTextureFormat.R32Float;
  24226. break;
  24227. default:
  24228. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  24229. }
  24230. break;
  24231. case RGFormat:
  24232. switch ( type ) {
  24233. case ByteType:
  24234. formatGPU = GPUTextureFormat.RG8Snorm;
  24235. break;
  24236. case ShortType:
  24237. formatGPU = GPUTextureFormat.RG16Sint;
  24238. break;
  24239. case UnsignedShortType:
  24240. formatGPU = GPUTextureFormat.RG16Uint;
  24241. break;
  24242. case UnsignedIntType:
  24243. formatGPU = GPUTextureFormat.RG32Uint;
  24244. break;
  24245. case IntType:
  24246. formatGPU = GPUTextureFormat.RG32Sint;
  24247. break;
  24248. case UnsignedByteType:
  24249. formatGPU = GPUTextureFormat.RG8Unorm;
  24250. break;
  24251. case HalfFloatType:
  24252. formatGPU = GPUTextureFormat.RG16Float;
  24253. break;
  24254. case FloatType:
  24255. formatGPU = GPUTextureFormat.RG32Float;
  24256. break;
  24257. default:
  24258. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  24259. }
  24260. break;
  24261. case DepthFormat:
  24262. switch ( type ) {
  24263. case UnsignedShortType:
  24264. formatGPU = GPUTextureFormat.Depth16Unorm;
  24265. break;
  24266. case UnsignedIntType:
  24267. formatGPU = GPUTextureFormat.Depth24Plus;
  24268. break;
  24269. case FloatType:
  24270. formatGPU = GPUTextureFormat.Depth32Float;
  24271. break;
  24272. default:
  24273. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  24274. }
  24275. break;
  24276. case DepthStencilFormat:
  24277. switch ( type ) {
  24278. case UnsignedInt248Type:
  24279. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  24280. break;
  24281. case FloatType:
  24282. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  24283. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  24284. }
  24285. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  24286. break;
  24287. default:
  24288. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  24289. }
  24290. break;
  24291. case RedIntegerFormat:
  24292. switch ( type ) {
  24293. case IntType:
  24294. formatGPU = GPUTextureFormat.R32Sint;
  24295. break;
  24296. case UnsignedIntType:
  24297. formatGPU = GPUTextureFormat.R32Uint;
  24298. break;
  24299. default:
  24300. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  24301. }
  24302. break;
  24303. case RGIntegerFormat:
  24304. switch ( type ) {
  24305. case IntType:
  24306. formatGPU = GPUTextureFormat.RG32Sint;
  24307. break;
  24308. case UnsignedIntType:
  24309. formatGPU = GPUTextureFormat.RG32Uint;
  24310. break;
  24311. default:
  24312. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  24313. }
  24314. break;
  24315. case RGBAIntegerFormat:
  24316. switch ( type ) {
  24317. case IntType:
  24318. formatGPU = GPUTextureFormat.RGBA32Sint;
  24319. break;
  24320. case UnsignedIntType:
  24321. formatGPU = GPUTextureFormat.RGBA32Uint;
  24322. break;
  24323. default:
  24324. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  24325. }
  24326. break;
  24327. default:
  24328. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  24329. }
  24330. }
  24331. return formatGPU;
  24332. }
  24333. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  24334. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  24335. const wgslTypeLib$1 = {
  24336. 'f32': 'float',
  24337. 'i32': 'int',
  24338. 'u32': 'uint',
  24339. 'bool': 'bool',
  24340. 'vec2<f32>': 'vec2',
  24341. 'vec2<i32>': 'ivec2',
  24342. 'vec2<u32>': 'uvec2',
  24343. 'vec2<bool>': 'bvec2',
  24344. 'vec2f': 'vec2',
  24345. 'vec2i': 'ivec2',
  24346. 'vec2u': 'uvec2',
  24347. 'vec2b': 'bvec2',
  24348. 'vec3<f32>': 'vec3',
  24349. 'vec3<i32>': 'ivec3',
  24350. 'vec3<u32>': 'uvec3',
  24351. 'vec3<bool>': 'bvec3',
  24352. 'vec3f': 'vec3',
  24353. 'vec3i': 'ivec3',
  24354. 'vec3u': 'uvec3',
  24355. 'vec3b': 'bvec3',
  24356. 'vec4<f32>': 'vec4',
  24357. 'vec4<i32>': 'ivec4',
  24358. 'vec4<u32>': 'uvec4',
  24359. 'vec4<bool>': 'bvec4',
  24360. 'vec4f': 'vec4',
  24361. 'vec4i': 'ivec4',
  24362. 'vec4u': 'uvec4',
  24363. 'vec4b': 'bvec4',
  24364. 'mat2x2<f32>': 'mat2',
  24365. 'mat2x2f': 'mat2',
  24366. 'mat3x3<f32>': 'mat3',
  24367. 'mat3x3f': 'mat3',
  24368. 'mat4x4<f32>': 'mat4',
  24369. 'mat4x4f': 'mat4',
  24370. 'sampler': 'sampler',
  24371. 'texture_1d': 'texture',
  24372. 'texture_2d': 'texture',
  24373. 'texture_2d_array': 'texture',
  24374. 'texture_multisampled_2d': 'cubeTexture',
  24375. 'texture_depth_2d': 'depthTexture',
  24376. 'texture_3d': 'texture3D',
  24377. 'texture_cube': 'cubeTexture',
  24378. 'texture_cube_array': 'cubeTexture',
  24379. 'texture_storage_1d': 'storageTexture',
  24380. 'texture_storage_2d': 'storageTexture',
  24381. 'texture_storage_2d_array': 'storageTexture',
  24382. 'texture_storage_3d': 'storageTexture'
  24383. };
  24384. const parse = ( source ) => {
  24385. source = source.trim();
  24386. const declaration = source.match( declarationRegexp );
  24387. if ( declaration !== null && declaration.length === 4 ) {
  24388. const inputsCode = declaration[ 2 ];
  24389. const propsMatches = [];
  24390. let match = null;
  24391. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  24392. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  24393. }
  24394. // Process matches to correctly pair names and types
  24395. const inputs = [];
  24396. for ( let i = 0; i < propsMatches.length; i ++ ) {
  24397. const { name, type } = propsMatches[ i ];
  24398. let resolvedType = type;
  24399. if ( resolvedType.startsWith( 'ptr' ) ) {
  24400. resolvedType = 'pointer';
  24401. } else {
  24402. if ( resolvedType.startsWith( 'texture' ) ) {
  24403. resolvedType = type.split( '<' )[ 0 ];
  24404. }
  24405. resolvedType = wgslTypeLib$1[ resolvedType ];
  24406. }
  24407. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  24408. }
  24409. const blockCode = source.substring( declaration[ 0 ].length );
  24410. const outputType = declaration[ 3 ] || 'void';
  24411. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  24412. const type = wgslTypeLib$1[ outputType ] || outputType;
  24413. return {
  24414. type,
  24415. inputs,
  24416. name,
  24417. inputsCode,
  24418. blockCode,
  24419. outputType
  24420. };
  24421. } else {
  24422. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  24423. }
  24424. };
  24425. /**
  24426. * This class represents a WSL node function.
  24427. *
  24428. * @augments NodeFunction
  24429. */
  24430. class WGSLNodeFunction extends NodeFunction {
  24431. /**
  24432. * Constructs a new WGSL node function.
  24433. *
  24434. * @param {String} source - The WGSL source.
  24435. */
  24436. constructor( source ) {
  24437. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  24438. super( type, inputs, name );
  24439. this.inputsCode = inputsCode;
  24440. this.blockCode = blockCode;
  24441. this.outputType = outputType;
  24442. }
  24443. /**
  24444. * This method returns the WGSL code of the node function.
  24445. *
  24446. * @param {String} [name=this.name] - The function's name.
  24447. * @return {String} The shader code.
  24448. */
  24449. getCode( name = this.name ) {
  24450. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  24451. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  24452. }
  24453. }
  24454. /**
  24455. * A WGSL node parser.
  24456. *
  24457. * @augments NodeParser
  24458. */
  24459. class WGSLNodeParser extends NodeParser {
  24460. /**
  24461. * The method parses the given WGSL code an returns a node function.
  24462. *
  24463. * @param {String} source - The WGSL code.
  24464. * @return {WGSLNodeFunction} A node function.
  24465. */
  24466. parseFunction( source ) {
  24467. return new WGSLNodeFunction( source );
  24468. }
  24469. }
  24470. // GPUShaderStage is not defined in browsers not supporting WebGPU
  24471. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  24472. const accessNames = {
  24473. [ NodeAccess.READ_ONLY ]: 'read',
  24474. [ NodeAccess.WRITE_ONLY ]: 'write',
  24475. [ NodeAccess.READ_WRITE ]: 'read_write'
  24476. };
  24477. const wrapNames = {
  24478. [ RepeatWrapping ]: 'repeat',
  24479. [ ClampToEdgeWrapping ]: 'clamp',
  24480. [ MirroredRepeatWrapping ]: 'mirror'
  24481. };
  24482. const gpuShaderStageLib = {
  24483. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  24484. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  24485. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  24486. };
  24487. const supports = {
  24488. instance: true,
  24489. swizzleAssign: false,
  24490. storageBuffer: true
  24491. };
  24492. const wgslFnOpLib = {
  24493. '^^': 'tsl_xor'
  24494. };
  24495. const wgslTypeLib = {
  24496. float: 'f32',
  24497. int: 'i32',
  24498. uint: 'u32',
  24499. bool: 'bool',
  24500. color: 'vec3<f32>',
  24501. vec2: 'vec2<f32>',
  24502. ivec2: 'vec2<i32>',
  24503. uvec2: 'vec2<u32>',
  24504. bvec2: 'vec2<bool>',
  24505. vec3: 'vec3<f32>',
  24506. ivec3: 'vec3<i32>',
  24507. uvec3: 'vec3<u32>',
  24508. bvec3: 'vec3<bool>',
  24509. vec4: 'vec4<f32>',
  24510. ivec4: 'vec4<i32>',
  24511. uvec4: 'vec4<u32>',
  24512. bvec4: 'vec4<bool>',
  24513. mat2: 'mat2x2<f32>',
  24514. mat3: 'mat3x3<f32>',
  24515. mat4: 'mat4x4<f32>'
  24516. };
  24517. const wgslCodeCache = {};
  24518. const wgslPolyfill = {
  24519. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  24520. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  24521. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  24522. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  24523. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  24524. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  24525. equals_bvec2: new CodeNode( 'fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  24526. equals_bvec3: new CodeNode( 'fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  24527. equals_bvec4: new CodeNode( 'fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  24528. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  24529. mirrorWrapping_float: new CodeNode( 'fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }' ),
  24530. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  24531. biquadraticTexture: new CodeNode( /* wgsl */`
  24532. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  24533. let res = vec2f( iRes );
  24534. let uvScaled = coord * res;
  24535. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  24536. // https://www.shadertoy.com/view/WtyXRy
  24537. let uv = uvWrapping - 0.5;
  24538. let iuv = floor( uv );
  24539. let f = fract( uv );
  24540. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  24541. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  24542. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  24543. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  24544. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  24545. }
  24546. ` )
  24547. };
  24548. const wgslMethods = {
  24549. dFdx: 'dpdx',
  24550. dFdy: '- dpdy',
  24551. mod_float: 'tsl_mod_float',
  24552. mod_vec2: 'tsl_mod_vec2',
  24553. mod_vec3: 'tsl_mod_vec3',
  24554. mod_vec4: 'tsl_mod_vec4',
  24555. equals_bool: 'tsl_equals_bool',
  24556. equals_bvec2: 'tsl_equals_bvec2',
  24557. equals_bvec3: 'tsl_equals_bvec3',
  24558. equals_bvec4: 'tsl_equals_bvec4',
  24559. inversesqrt: 'inverseSqrt',
  24560. bitcast: 'bitcast<f32>'
  24561. };
  24562. // WebGPU issue: does not support pow() with negative base on Windows
  24563. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  24564. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  24565. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  24566. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  24567. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  24568. wgslMethods.pow_float = 'tsl_pow_float';
  24569. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  24570. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  24571. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  24572. }
  24573. //
  24574. let diagnostics = '';
  24575. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  24576. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  24577. }
  24578. //
  24579. class WGSLNodeBuilder extends NodeBuilder {
  24580. constructor( object, renderer ) {
  24581. super( object, renderer, new WGSLNodeParser() );
  24582. this.uniformGroups = {};
  24583. this.builtins = {};
  24584. this.directives = {};
  24585. this.scopedArrays = new Map();
  24586. }
  24587. needsToWorkingColorSpace( texture ) {
  24588. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  24589. }
  24590. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24591. if ( shaderStage === 'fragment' ) {
  24592. if ( depthSnippet ) {
  24593. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  24594. } else {
  24595. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  24596. }
  24597. } else if ( this.isFilteredTexture( texture ) ) {
  24598. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  24599. } else {
  24600. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  24601. }
  24602. }
  24603. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  24604. if ( shaderStage === 'fragment' ) {
  24605. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  24606. } else {
  24607. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  24608. }
  24609. }
  24610. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24611. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  24612. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  24613. } else if ( this.isFilteredTexture( texture ) ) {
  24614. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  24615. } else {
  24616. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  24617. }
  24618. }
  24619. generateWrapFunction( texture ) {
  24620. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  24621. let nodeCode = wgslCodeCache[ functionName ];
  24622. if ( nodeCode === undefined ) {
  24623. const includes = [];
  24624. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  24625. const addWrapSnippet = ( wrap, axis ) => {
  24626. if ( wrap === RepeatWrapping ) {
  24627. includes.push( wgslPolyfill.repeatWrapping_float );
  24628. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  24629. } else if ( wrap === ClampToEdgeWrapping ) {
  24630. includes.push( wgslPolyfill.clampWrapping_float );
  24631. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  24632. } else if ( wrap === MirroredRepeatWrapping ) {
  24633. includes.push( wgslPolyfill.mirrorWrapping_float );
  24634. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  24635. } else {
  24636. code += `\t\tcoord.${ axis }`;
  24637. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  24638. }
  24639. };
  24640. addWrapSnippet( texture.wrapS, 'x' );
  24641. code += ',\n';
  24642. addWrapSnippet( texture.wrapT, 'y' );
  24643. code += '\n\t);\n\n}\n';
  24644. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  24645. }
  24646. nodeCode.build( this );
  24647. return functionName;
  24648. }
  24649. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  24650. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  24651. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  24652. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  24653. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  24654. let textureDimensionsParams;
  24655. if ( texture.isMultisampleRenderTargetTexture === true ) {
  24656. textureDimensionsParams = textureProperty;
  24657. } else {
  24658. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  24659. }
  24660. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  24661. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  24662. }
  24663. return textureDimensionNode.build( this );
  24664. }
  24665. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  24666. this._include( 'biquadraticTexture' );
  24667. const wrapFunction = this.generateWrapFunction( texture );
  24668. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  24669. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  24670. }
  24671. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  24672. const wrapFunction = this.generateWrapFunction( texture );
  24673. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  24674. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  24675. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  24676. }
  24677. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  24678. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  24679. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  24680. } else if ( depthSnippet ) {
  24681. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  24682. } else {
  24683. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  24684. }
  24685. }
  24686. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  24687. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  24688. }
  24689. isSampleCompare( texture ) {
  24690. return texture.isDepthTexture === true && texture.compareFunction !== null;
  24691. }
  24692. isUnfilterable( texture ) {
  24693. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  24694. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  24695. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  24696. texture.isMultisampleRenderTargetTexture === true;
  24697. }
  24698. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24699. let snippet = null;
  24700. if ( texture.isVideoTexture === true ) {
  24701. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  24702. } else if ( this.isUnfilterable( texture ) ) {
  24703. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  24704. } else {
  24705. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  24706. }
  24707. return snippet;
  24708. }
  24709. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24710. if ( shaderStage === 'fragment' ) {
  24711. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  24712. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  24713. } else {
  24714. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  24715. }
  24716. }
  24717. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24718. if ( shaderStage === 'fragment' ) {
  24719. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  24720. } else {
  24721. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  24722. }
  24723. }
  24724. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24725. let snippet = null;
  24726. if ( texture.isVideoTexture === true ) {
  24727. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  24728. } else {
  24729. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  24730. }
  24731. return snippet;
  24732. }
  24733. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  24734. if ( shaderStage === 'fragment' ) {
  24735. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  24736. } else {
  24737. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  24738. }
  24739. }
  24740. getPropertyName( node, shaderStage = this.shaderStage ) {
  24741. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  24742. if ( shaderStage === 'vertex' ) {
  24743. return `varyings.${ node.name }`;
  24744. }
  24745. } else if ( node.isNodeUniform === true ) {
  24746. const name = node.name;
  24747. const type = node.type;
  24748. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  24749. return name;
  24750. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  24751. return `NodeBuffer_${ node.id }.${name}`;
  24752. } else {
  24753. return node.groupNode.name + '.' + name;
  24754. }
  24755. }
  24756. return super.getPropertyName( node );
  24757. }
  24758. getOutputStructName() {
  24759. return 'output';
  24760. }
  24761. _getUniformGroupCount( shaderStage ) {
  24762. return Object.keys( this.uniforms[ shaderStage ] ).length;
  24763. }
  24764. getFunctionOperator( op ) {
  24765. const fnOp = wgslFnOpLib[ op ];
  24766. if ( fnOp !== undefined ) {
  24767. this._include( fnOp );
  24768. return fnOp;
  24769. }
  24770. return null;
  24771. }
  24772. getNodeAccess( node, shaderStage ) {
  24773. if ( shaderStage !== 'compute' )
  24774. return NodeAccess.READ_ONLY;
  24775. return node.access;
  24776. }
  24777. getStorageAccess( node, shaderStage ) {
  24778. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  24779. }
  24780. getUniformFromNode( node, type, shaderStage, name = null ) {
  24781. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  24782. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  24783. if ( nodeData.uniformGPU === undefined ) {
  24784. let uniformGPU;
  24785. const group = node.groupNode;
  24786. const groupName = group.name;
  24787. const bindings = this.getBindGroupArray( groupName, shaderStage );
  24788. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  24789. let texture = null;
  24790. const access = this.getNodeAccess( node, shaderStage );
  24791. if ( type === 'texture' || type === 'storageTexture' ) {
  24792. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  24793. } else if ( type === 'cubeTexture' ) {
  24794. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  24795. } else if ( type === 'texture3D' ) {
  24796. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  24797. }
  24798. texture.store = node.isStorageTextureNode === true;
  24799. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24800. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  24801. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  24802. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24803. bindings.push( sampler, texture );
  24804. uniformGPU = [ sampler, texture ];
  24805. } else {
  24806. bindings.push( texture );
  24807. uniformGPU = [ texture ];
  24808. }
  24809. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  24810. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  24811. const buffer = new bufferClass( node, group );
  24812. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24813. bindings.push( buffer );
  24814. uniformGPU = buffer;
  24815. } else {
  24816. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  24817. let uniformsGroup = uniformsStage[ groupName ];
  24818. if ( uniformsGroup === undefined ) {
  24819. uniformsGroup = new NodeUniformsGroup( groupName, group );
  24820. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24821. uniformsStage[ groupName ] = uniformsGroup;
  24822. bindings.push( uniformsGroup );
  24823. }
  24824. uniformGPU = this.getNodeUniform( uniformNode, type );
  24825. uniformsGroup.addUniform( uniformGPU );
  24826. }
  24827. nodeData.uniformGPU = uniformGPU;
  24828. }
  24829. return uniformNode;
  24830. }
  24831. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  24832. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  24833. if ( map.has( name ) === false ) {
  24834. map.set( name, {
  24835. name,
  24836. property,
  24837. type
  24838. } );
  24839. }
  24840. return property;
  24841. }
  24842. hasBuiltin( name, shaderStage = this.shaderStage ) {
  24843. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  24844. }
  24845. getVertexIndex() {
  24846. if ( this.shaderStage === 'vertex' ) {
  24847. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  24848. }
  24849. return 'vertexIndex';
  24850. }
  24851. buildFunctionCode( shaderNode ) {
  24852. const layout = shaderNode.layout;
  24853. const flowData = this.flowShaderNode( shaderNode );
  24854. const parameters = [];
  24855. for ( const input of layout.inputs ) {
  24856. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  24857. }
  24858. //
  24859. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  24860. ${ flowData.vars }
  24861. ${ flowData.code }
  24862. `;
  24863. if ( flowData.result ) {
  24864. code += `\treturn ${ flowData.result };\n`;
  24865. }
  24866. code += '\n}\n';
  24867. //
  24868. return code;
  24869. }
  24870. getInstanceIndex() {
  24871. if ( this.shaderStage === 'vertex' ) {
  24872. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  24873. }
  24874. return 'instanceIndex';
  24875. }
  24876. getInvocationLocalIndex() {
  24877. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  24878. }
  24879. getSubgroupSize() {
  24880. this.enableSubGroups();
  24881. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  24882. }
  24883. getInvocationSubgroupIndex() {
  24884. this.enableSubGroups();
  24885. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  24886. }
  24887. getSubgroupIndex() {
  24888. this.enableSubGroups();
  24889. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  24890. }
  24891. getDrawIndex() {
  24892. return null;
  24893. }
  24894. getFrontFacing() {
  24895. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  24896. }
  24897. getFragCoord() {
  24898. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  24899. }
  24900. getFragDepth() {
  24901. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  24902. }
  24903. getClipDistance() {
  24904. return 'varyings.hw_clip_distances';
  24905. }
  24906. isFlipY() {
  24907. return false;
  24908. }
  24909. enableDirective( name, shaderStage = this.shaderStage ) {
  24910. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  24911. stage.add( name );
  24912. }
  24913. getDirectives( shaderStage ) {
  24914. const snippets = [];
  24915. const directives = this.directives[ shaderStage ];
  24916. if ( directives !== undefined ) {
  24917. for ( const directive of directives ) {
  24918. snippets.push( `enable ${directive};` );
  24919. }
  24920. }
  24921. return snippets.join( '\n' );
  24922. }
  24923. enableSubGroups() {
  24924. this.enableDirective( 'subgroups' );
  24925. }
  24926. enableSubgroupsF16() {
  24927. this.enableDirective( 'subgroups-f16' );
  24928. }
  24929. enableClipDistances() {
  24930. this.enableDirective( 'clip_distances' );
  24931. }
  24932. enableShaderF16() {
  24933. this.enableDirective( 'f16' );
  24934. }
  24935. enableDualSourceBlending() {
  24936. this.enableDirective( 'dual_source_blending' );
  24937. }
  24938. enableHardwareClipping( planeCount ) {
  24939. this.enableClipDistances();
  24940. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  24941. }
  24942. getBuiltins( shaderStage ) {
  24943. const snippets = [];
  24944. const builtins = this.builtins[ shaderStage ];
  24945. if ( builtins !== undefined ) {
  24946. for ( const { name, property, type } of builtins.values() ) {
  24947. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  24948. }
  24949. }
  24950. return snippets.join( ',\n\t' );
  24951. }
  24952. getScopedArray( name, scope, bufferType, bufferCount ) {
  24953. if ( this.scopedArrays.has( name ) === false ) {
  24954. this.scopedArrays.set( name, {
  24955. name,
  24956. scope,
  24957. bufferType,
  24958. bufferCount
  24959. } );
  24960. }
  24961. return name;
  24962. }
  24963. getScopedArrays( shaderStage ) {
  24964. if ( shaderStage !== 'compute' ) {
  24965. return;
  24966. }
  24967. const snippets = [];
  24968. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  24969. const type = this.getType( bufferType );
  24970. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  24971. }
  24972. return snippets.join( '\n' );
  24973. }
  24974. getAttributes( shaderStage ) {
  24975. const snippets = [];
  24976. if ( shaderStage === 'compute' ) {
  24977. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  24978. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  24979. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  24980. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  24981. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  24982. this.enableDirective( 'subgroups', shaderStage );
  24983. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  24984. }
  24985. }
  24986. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  24987. const builtins = this.getBuiltins( 'attribute' );
  24988. if ( builtins ) snippets.push( builtins );
  24989. const attributes = this.getAttributesArray();
  24990. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  24991. const attribute = attributes[ index ];
  24992. const name = attribute.name;
  24993. const type = this.getType( attribute.type );
  24994. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  24995. }
  24996. }
  24997. return snippets.join( ',\n\t' );
  24998. }
  24999. getStructMembers( struct ) {
  25000. const snippets = [];
  25001. const members = struct.getMemberTypes();
  25002. for ( let i = 0; i < members.length; i ++ ) {
  25003. const member = members[ i ];
  25004. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  25005. }
  25006. const builtins = this.getBuiltins( 'output' );
  25007. if ( builtins ) snippets.push( '\t' + builtins );
  25008. return snippets.join( ',\n' );
  25009. }
  25010. getStructs( shaderStage ) {
  25011. const snippets = [];
  25012. const structs = this.structs[ shaderStage ];
  25013. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  25014. const struct = structs[ index ];
  25015. const name = struct.name;
  25016. let snippet = `\struct ${ name } {\n`;
  25017. snippet += this.getStructMembers( struct );
  25018. snippet += '\n}';
  25019. snippets.push( snippet );
  25020. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  25021. }
  25022. return snippets.join( '\n\n' );
  25023. }
  25024. getVar( type, name ) {
  25025. return `var ${ name } : ${ this.getType( type ) }`;
  25026. }
  25027. getVars( shaderStage ) {
  25028. const snippets = [];
  25029. const vars = this.vars[ shaderStage ];
  25030. if ( vars !== undefined ) {
  25031. for ( const variable of vars ) {
  25032. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  25033. }
  25034. }
  25035. return `\n${ snippets.join( '\n' ) }\n`;
  25036. }
  25037. getVaryings( shaderStage ) {
  25038. const snippets = [];
  25039. if ( shaderStage === 'vertex' ) {
  25040. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  25041. }
  25042. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  25043. const varyings = this.varyings;
  25044. const vars = this.vars[ shaderStage ];
  25045. for ( let index = 0; index < varyings.length; index ++ ) {
  25046. const varying = varyings[ index ];
  25047. if ( varying.needsInterpolation ) {
  25048. let attributesSnippet = `@location( ${index} )`;
  25049. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  25050. attributesSnippet += ' @interpolate( flat )';
  25051. }
  25052. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  25053. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  25054. vars.push( varying );
  25055. }
  25056. }
  25057. }
  25058. const builtins = this.getBuiltins( shaderStage );
  25059. if ( builtins ) snippets.push( builtins );
  25060. const code = snippets.join( ',\n\t' );
  25061. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  25062. }
  25063. getUniforms( shaderStage ) {
  25064. const uniforms = this.uniforms[ shaderStage ];
  25065. const bindingSnippets = [];
  25066. const bufferSnippets = [];
  25067. const structSnippets = [];
  25068. const uniformGroups = {};
  25069. for ( const uniform of uniforms ) {
  25070. const groupName = uniform.groupNode.name;
  25071. const uniformIndexes = this.bindingsIndexes[ groupName ];
  25072. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  25073. const texture = uniform.node.value;
  25074. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  25075. if ( this.isSampleCompare( texture ) ) {
  25076. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  25077. } else {
  25078. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  25079. }
  25080. }
  25081. let textureType;
  25082. let multisampled = '';
  25083. if ( texture.isMultisampleRenderTargetTexture === true ) {
  25084. multisampled = '_multisampled';
  25085. }
  25086. if ( texture.isCubeTexture === true ) {
  25087. textureType = 'texture_cube<f32>';
  25088. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  25089. textureType = 'texture_2d_array<f32>';
  25090. } else if ( texture.isDepthTexture === true ) {
  25091. textureType = `texture_depth${multisampled}_2d`;
  25092. } else if ( texture.isVideoTexture === true ) {
  25093. textureType = 'texture_external';
  25094. } else if ( texture.isData3DTexture === true ) {
  25095. textureType = 'texture_3d<f32>';
  25096. } else if ( uniform.node.isStorageTextureNode === true ) {
  25097. const format = getFormat( texture );
  25098. const access = this.getStorageAccess( uniform.node, shaderStage );
  25099. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  25100. } else {
  25101. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  25102. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  25103. }
  25104. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  25105. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  25106. const bufferNode = uniform.node;
  25107. const bufferType = this.getType( bufferNode.bufferType );
  25108. const bufferCount = bufferNode.bufferCount;
  25109. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  25110. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  25111. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  25112. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  25113. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  25114. } else {
  25115. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  25116. const groupName = uniform.groupNode.name;
  25117. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  25118. index: uniformIndexes.binding ++,
  25119. id: uniformIndexes.group,
  25120. snippets: []
  25121. } );
  25122. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  25123. }
  25124. }
  25125. for ( const name in uniformGroups ) {
  25126. const group = uniformGroups[ name ];
  25127. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  25128. }
  25129. let code = bindingSnippets.join( '\n' );
  25130. code += bufferSnippets.join( '\n' );
  25131. code += structSnippets.join( '\n' );
  25132. return code;
  25133. }
  25134. buildCode() {
  25135. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  25136. this.sortBindingGroups();
  25137. for ( const shaderStage in shadersData ) {
  25138. const stageData = shadersData[ shaderStage ];
  25139. stageData.uniforms = this.getUniforms( shaderStage );
  25140. stageData.attributes = this.getAttributes( shaderStage );
  25141. stageData.varyings = this.getVaryings( shaderStage );
  25142. stageData.structs = this.getStructs( shaderStage );
  25143. stageData.vars = this.getVars( shaderStage );
  25144. stageData.codes = this.getCodes( shaderStage );
  25145. stageData.directives = this.getDirectives( shaderStage );
  25146. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  25147. //
  25148. let flow = '// code\n\n';
  25149. flow += this.flowCode[ shaderStage ];
  25150. const flowNodes = this.flowNodes[ shaderStage ];
  25151. const mainNode = flowNodes[ flowNodes.length - 1 ];
  25152. const outputNode = mainNode.outputNode;
  25153. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  25154. for ( const node of flowNodes ) {
  25155. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  25156. const slotName = node.name;
  25157. if ( slotName ) {
  25158. if ( flow.length > 0 ) flow += '\n';
  25159. flow += `\t// flow -> ${ slotName }\n\t`;
  25160. }
  25161. flow += `${ flowSlotData.code }\n\t`;
  25162. if ( node === mainNode && shaderStage !== 'compute' ) {
  25163. flow += '// result\n\n\t';
  25164. if ( shaderStage === 'vertex' ) {
  25165. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  25166. } else if ( shaderStage === 'fragment' ) {
  25167. if ( isOutputStruct ) {
  25168. stageData.returnType = outputNode.nodeType;
  25169. flow += `return ${ flowSlotData.result };`;
  25170. } else {
  25171. let structSnippet = '\t@location(0) color: vec4<f32>';
  25172. const builtins = this.getBuiltins( 'output' );
  25173. if ( builtins ) structSnippet += ',\n\t' + builtins;
  25174. stageData.returnType = 'OutputStruct';
  25175. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  25176. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  25177. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  25178. }
  25179. }
  25180. }
  25181. }
  25182. stageData.flow = flow;
  25183. }
  25184. if ( this.material !== null ) {
  25185. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  25186. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  25187. } else {
  25188. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  25189. }
  25190. }
  25191. getMethod( method, output = null ) {
  25192. let wgslMethod;
  25193. if ( output !== null ) {
  25194. wgslMethod = this._getWGSLMethod( method + '_' + output );
  25195. }
  25196. if ( wgslMethod === undefined ) {
  25197. wgslMethod = this._getWGSLMethod( method );
  25198. }
  25199. return wgslMethod || method;
  25200. }
  25201. getType( type ) {
  25202. return wgslTypeLib[ type ] || type;
  25203. }
  25204. isAvailable( name ) {
  25205. let result = supports[ name ];
  25206. if ( result === undefined ) {
  25207. if ( name === 'float32Filterable' ) {
  25208. result = this.renderer.hasFeature( 'float32-filterable' );
  25209. } else if ( name === 'clipDistance' ) {
  25210. result = this.renderer.hasFeature( 'clip-distances' );
  25211. }
  25212. supports[ name ] = result;
  25213. }
  25214. return result;
  25215. }
  25216. _getWGSLMethod( method ) {
  25217. if ( wgslPolyfill[ method ] !== undefined ) {
  25218. this._include( method );
  25219. }
  25220. return wgslMethods[ method ];
  25221. }
  25222. _include( name ) {
  25223. const codeNode = wgslPolyfill[ name ];
  25224. codeNode.build( this );
  25225. if ( this.currentFunctionNode !== null ) {
  25226. this.currentFunctionNode.includes.push( codeNode );
  25227. }
  25228. return codeNode;
  25229. }
  25230. _getWGSLVertexCode( shaderData ) {
  25231. return `${ this.getSignature() }
  25232. // directives
  25233. ${shaderData.directives}
  25234. // uniforms
  25235. ${shaderData.uniforms}
  25236. // varyings
  25237. ${shaderData.varyings}
  25238. var<private> varyings : VaryingsStruct;
  25239. // codes
  25240. ${shaderData.codes}
  25241. @vertex
  25242. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  25243. // vars
  25244. ${shaderData.vars}
  25245. // flow
  25246. ${shaderData.flow}
  25247. return varyings;
  25248. }
  25249. `;
  25250. }
  25251. _getWGSLFragmentCode( shaderData ) {
  25252. return `${ this.getSignature() }
  25253. // global
  25254. ${ diagnostics }
  25255. // uniforms
  25256. ${shaderData.uniforms}
  25257. // structs
  25258. ${shaderData.structs}
  25259. // codes
  25260. ${shaderData.codes}
  25261. @fragment
  25262. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  25263. // vars
  25264. ${shaderData.vars}
  25265. // flow
  25266. ${shaderData.flow}
  25267. }
  25268. `;
  25269. }
  25270. _getWGSLComputeCode( shaderData, workgroupSize ) {
  25271. return `${ this.getSignature() }
  25272. // directives
  25273. ${shaderData.directives}
  25274. // system
  25275. var<private> instanceIndex : u32;
  25276. // locals
  25277. ${shaderData.scopedArrays}
  25278. // uniforms
  25279. ${shaderData.uniforms}
  25280. // codes
  25281. ${shaderData.codes}
  25282. @compute @workgroup_size( ${workgroupSize} )
  25283. fn main( ${shaderData.attributes} ) {
  25284. // system
  25285. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  25286. // vars
  25287. ${shaderData.vars}
  25288. // flow
  25289. ${shaderData.flow}
  25290. }
  25291. `;
  25292. }
  25293. _getWGSLStruct( name, vars ) {
  25294. return `
  25295. struct ${name} {
  25296. ${vars}
  25297. };`;
  25298. }
  25299. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  25300. const structName = name + 'Struct';
  25301. const structSnippet = this._getWGSLStruct( structName, vars );
  25302. return `${structSnippet}
  25303. @binding( ${binding} ) @group( ${group} )
  25304. var<${access}> ${name} : ${structName};`;
  25305. }
  25306. }
  25307. class WebGPUUtils {
  25308. constructor( backend ) {
  25309. this.backend = backend;
  25310. }
  25311. getCurrentDepthStencilFormat( renderContext ) {
  25312. let format;
  25313. if ( renderContext.depthTexture !== null ) {
  25314. format = this.getTextureFormatGPU( renderContext.depthTexture );
  25315. } else if ( renderContext.depth && renderContext.stencil ) {
  25316. format = GPUTextureFormat.Depth24PlusStencil8;
  25317. } else if ( renderContext.depth ) {
  25318. format = GPUTextureFormat.Depth24Plus;
  25319. }
  25320. return format;
  25321. }
  25322. getTextureFormatGPU( texture ) {
  25323. return this.backend.get( texture ).format;
  25324. }
  25325. getCurrentColorFormat( renderContext ) {
  25326. let format;
  25327. if ( renderContext.textures !== null ) {
  25328. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  25329. } else {
  25330. format = this.getPreferredCanvasFormat(); // default context format
  25331. }
  25332. return format;
  25333. }
  25334. getCurrentColorSpace( renderContext ) {
  25335. if ( renderContext.textures !== null ) {
  25336. return renderContext.textures[ 0 ].colorSpace;
  25337. }
  25338. return this.backend.renderer.outputColorSpace;
  25339. }
  25340. getPrimitiveTopology( object, material ) {
  25341. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  25342. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  25343. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  25344. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  25345. }
  25346. getSampleCount( sampleCount ) {
  25347. let count = 1;
  25348. if ( sampleCount > 1 ) {
  25349. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  25350. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  25351. if ( count === 2 ) {
  25352. count = 4;
  25353. }
  25354. }
  25355. return count;
  25356. }
  25357. getSampleCountRenderContext( renderContext ) {
  25358. if ( renderContext.textures !== null ) {
  25359. return this.getSampleCount( renderContext.sampleCount );
  25360. }
  25361. return this.getSampleCount( this.backend.renderer.samples );
  25362. }
  25363. getPreferredCanvasFormat() {
  25364. // TODO: Remove this check when Quest 34.5 is out
  25365. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  25366. if ( navigator.userAgent.includes( 'Quest' ) ) {
  25367. return GPUTextureFormat.BGRA8Unorm;
  25368. } else {
  25369. return navigator.gpu.getPreferredCanvasFormat();
  25370. }
  25371. }
  25372. }
  25373. const typedArraysToVertexFormatPrefix = new Map( [
  25374. [ Int8Array, [ 'sint8', 'snorm8' ]],
  25375. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  25376. [ Int16Array, [ 'sint16', 'snorm16' ]],
  25377. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  25378. [ Int32Array, [ 'sint32', 'snorm32' ]],
  25379. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  25380. [ Float32Array, [ 'float32', ]],
  25381. ] );
  25382. const typedAttributeToVertexFormatPrefix = new Map( [
  25383. [ Float16BufferAttribute, [ 'float16', ]],
  25384. ] );
  25385. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  25386. [ Int32Array, 'sint32' ],
  25387. [ Int16Array, 'sint32' ], // patch for INT16
  25388. [ Uint32Array, 'uint32' ],
  25389. [ Uint16Array, 'uint32' ], // patch for UINT16
  25390. [ Float32Array, 'float32' ]
  25391. ] );
  25392. class WebGPUAttributeUtils {
  25393. constructor( backend ) {
  25394. this.backend = backend;
  25395. }
  25396. createAttribute( attribute, usage ) {
  25397. const bufferAttribute = this._getBufferAttribute( attribute );
  25398. const backend = this.backend;
  25399. const bufferData = backend.get( bufferAttribute );
  25400. let buffer = bufferData.buffer;
  25401. if ( buffer === undefined ) {
  25402. const device = backend.device;
  25403. let array = bufferAttribute.array;
  25404. // patch for INT16 and UINT16
  25405. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  25406. const tempArray = new Uint32Array( array.length );
  25407. for ( let i = 0; i < array.length; i ++ ) {
  25408. tempArray[ i ] = array[ i ];
  25409. }
  25410. array = tempArray;
  25411. }
  25412. bufferAttribute.array = array;
  25413. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  25414. array = new array.constructor( bufferAttribute.count * 4 );
  25415. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  25416. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  25417. }
  25418. // Update BufferAttribute
  25419. bufferAttribute.itemSize = 4;
  25420. bufferAttribute.array = array;
  25421. }
  25422. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  25423. buffer = device.createBuffer( {
  25424. label: bufferAttribute.name,
  25425. size: size,
  25426. usage: usage,
  25427. mappedAtCreation: true
  25428. } );
  25429. new array.constructor( buffer.getMappedRange() ).set( array );
  25430. buffer.unmap();
  25431. bufferData.buffer = buffer;
  25432. }
  25433. }
  25434. updateAttribute( attribute ) {
  25435. const bufferAttribute = this._getBufferAttribute( attribute );
  25436. const backend = this.backend;
  25437. const device = backend.device;
  25438. const buffer = backend.get( bufferAttribute ).buffer;
  25439. const array = bufferAttribute.array;
  25440. const isTypedArray = this._isTypedArray( array );
  25441. const updateRanges = bufferAttribute.updateRanges;
  25442. if ( updateRanges.length === 0 ) {
  25443. // Not using update ranges
  25444. device.queue.writeBuffer(
  25445. buffer,
  25446. 0,
  25447. array,
  25448. 0
  25449. );
  25450. } else {
  25451. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  25452. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  25453. const range = updateRanges[ i ];
  25454. const dataOffset = range.start * byteOffsetFactor;
  25455. const size = range.count * byteOffsetFactor;
  25456. device.queue.writeBuffer(
  25457. buffer,
  25458. 0,
  25459. array,
  25460. dataOffset,
  25461. size
  25462. );
  25463. }
  25464. bufferAttribute.clearUpdateRanges();
  25465. }
  25466. }
  25467. createShaderVertexBuffers( renderObject ) {
  25468. const attributes = renderObject.getAttributes();
  25469. const vertexBuffers = new Map();
  25470. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  25471. const geometryAttribute = attributes[ slot ];
  25472. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  25473. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  25474. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  25475. if ( vertexBufferLayout === undefined ) {
  25476. let arrayStride, stepMode;
  25477. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  25478. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  25479. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  25480. } else {
  25481. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  25482. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  25483. }
  25484. // patch for INT16 and UINT16
  25485. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  25486. arrayStride = 4;
  25487. }
  25488. vertexBufferLayout = {
  25489. arrayStride,
  25490. attributes: [],
  25491. stepMode
  25492. };
  25493. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  25494. }
  25495. const format = this._getVertexFormat( geometryAttribute );
  25496. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  25497. vertexBufferLayout.attributes.push( {
  25498. shaderLocation: slot,
  25499. offset,
  25500. format
  25501. } );
  25502. }
  25503. return Array.from( vertexBuffers.values() );
  25504. }
  25505. destroyAttribute( attribute ) {
  25506. const backend = this.backend;
  25507. const data = backend.get( this._getBufferAttribute( attribute ) );
  25508. data.buffer.destroy();
  25509. backend.delete( attribute );
  25510. }
  25511. async getArrayBufferAsync( attribute ) {
  25512. const backend = this.backend;
  25513. const device = backend.device;
  25514. const data = backend.get( this._getBufferAttribute( attribute ) );
  25515. const bufferGPU = data.buffer;
  25516. const size = bufferGPU.size;
  25517. const readBufferGPU = device.createBuffer( {
  25518. label: attribute.name,
  25519. size,
  25520. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  25521. } );
  25522. const cmdEncoder = device.createCommandEncoder( {} );
  25523. cmdEncoder.copyBufferToBuffer(
  25524. bufferGPU,
  25525. 0,
  25526. readBufferGPU,
  25527. 0,
  25528. size
  25529. );
  25530. readBufferGPU.unmap();
  25531. const gpuCommands = cmdEncoder.finish();
  25532. device.queue.submit( [ gpuCommands ] );
  25533. await readBufferGPU.mapAsync( GPUMapMode.READ );
  25534. const arrayBuffer = readBufferGPU.getMappedRange();
  25535. return arrayBuffer;
  25536. }
  25537. _getVertexFormat( geometryAttribute ) {
  25538. const { itemSize, normalized } = geometryAttribute;
  25539. const ArrayType = geometryAttribute.array.constructor;
  25540. const AttributeType = geometryAttribute.constructor;
  25541. let format;
  25542. if ( itemSize == 1 ) {
  25543. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  25544. } else {
  25545. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  25546. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  25547. if ( prefix ) {
  25548. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  25549. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  25550. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  25551. if ( paddedItemSize % 1 ) {
  25552. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  25553. }
  25554. format = `${prefix}x${paddedItemSize}`;
  25555. }
  25556. }
  25557. if ( ! format ) {
  25558. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  25559. }
  25560. return format;
  25561. }
  25562. _isTypedArray( array ) {
  25563. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  25564. }
  25565. _getBufferAttribute( attribute ) {
  25566. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  25567. return attribute;
  25568. }
  25569. }
  25570. class WebGPUBindingUtils {
  25571. constructor( backend ) {
  25572. this.backend = backend;
  25573. this.bindGroupLayoutCache = new WeakMap();
  25574. }
  25575. createBindingsLayout( bindGroup ) {
  25576. const backend = this.backend;
  25577. const device = backend.device;
  25578. const entries = [];
  25579. let index = 0;
  25580. for ( const binding of bindGroup.bindings ) {
  25581. const bindingGPU = {
  25582. binding: index ++,
  25583. visibility: binding.visibility
  25584. };
  25585. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  25586. const buffer = {}; // GPUBufferBindingLayout
  25587. if ( binding.isStorageBuffer ) {
  25588. if ( binding.visibility & 4 ) {
  25589. // compute
  25590. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  25591. buffer.type = GPUBufferBindingType.Storage;
  25592. } else {
  25593. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  25594. }
  25595. } else {
  25596. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  25597. }
  25598. }
  25599. bindingGPU.buffer = buffer;
  25600. } else if ( binding.isSampler ) {
  25601. const sampler = {}; // GPUSamplerBindingLayout
  25602. if ( binding.texture.isDepthTexture ) {
  25603. if ( binding.texture.compareFunction !== null ) {
  25604. sampler.type = 'comparison';
  25605. }
  25606. }
  25607. bindingGPU.sampler = sampler;
  25608. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  25609. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  25610. } else if ( binding.isSampledTexture && binding.store ) {
  25611. const storageTexture = {}; // GPUStorageTextureBindingLayout
  25612. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  25613. const access = binding.access;
  25614. if ( access === NodeAccess.READ_WRITE ) {
  25615. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  25616. } else if ( access === NodeAccess.WRITE_ONLY ) {
  25617. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  25618. } else {
  25619. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  25620. }
  25621. bindingGPU.storageTexture = storageTexture;
  25622. } else if ( binding.isSampledTexture ) {
  25623. const texture = {}; // GPUTextureBindingLayout
  25624. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  25625. texture.multisampled = true;
  25626. }
  25627. if ( binding.texture.isDepthTexture ) {
  25628. texture.sampleType = GPUTextureSampleType.Depth;
  25629. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  25630. const type = binding.texture.type;
  25631. if ( type === IntType ) {
  25632. texture.sampleType = GPUTextureSampleType.SInt;
  25633. } else if ( type === UnsignedIntType ) {
  25634. texture.sampleType = GPUTextureSampleType.UInt;
  25635. } else if ( type === FloatType ) {
  25636. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  25637. texture.sampleType = GPUTextureSampleType.Float;
  25638. } else {
  25639. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  25640. }
  25641. }
  25642. }
  25643. if ( binding.isSampledCubeTexture ) {
  25644. texture.viewDimension = GPUTextureViewDimension.Cube;
  25645. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  25646. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  25647. } else if ( binding.isSampledTexture3D ) {
  25648. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  25649. }
  25650. bindingGPU.texture = texture;
  25651. } else {
  25652. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  25653. }
  25654. entries.push( bindingGPU );
  25655. }
  25656. return device.createBindGroupLayout( { entries } );
  25657. }
  25658. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  25659. const { backend, bindGroupLayoutCache } = this;
  25660. const bindingsData = backend.get( bindGroup );
  25661. // setup (static) binding layout and (dynamic) binding group
  25662. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  25663. if ( bindLayoutGPU === undefined ) {
  25664. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  25665. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  25666. }
  25667. let bindGroupGPU;
  25668. if ( cacheIndex > 0 ) {
  25669. if ( bindingsData.groups === undefined ) {
  25670. bindingsData.groups = [];
  25671. bindingsData.versions = [];
  25672. }
  25673. if ( bindingsData.versions[ cacheIndex ] === version ) {
  25674. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  25675. }
  25676. }
  25677. if ( bindGroupGPU === undefined ) {
  25678. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  25679. if ( cacheIndex > 0 ) {
  25680. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  25681. bindingsData.versions[ cacheIndex ] = version;
  25682. }
  25683. }
  25684. bindingsData.group = bindGroupGPU;
  25685. bindingsData.layout = bindLayoutGPU;
  25686. }
  25687. updateBinding( binding ) {
  25688. const backend = this.backend;
  25689. const device = backend.device;
  25690. const buffer = binding.buffer;
  25691. const bufferGPU = backend.get( binding ).buffer;
  25692. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  25693. }
  25694. createBindGroup( bindGroup, layoutGPU ) {
  25695. const backend = this.backend;
  25696. const device = backend.device;
  25697. let bindingPoint = 0;
  25698. const entriesGPU = [];
  25699. for ( const binding of bindGroup.bindings ) {
  25700. if ( binding.isUniformBuffer ) {
  25701. const bindingData = backend.get( binding );
  25702. if ( bindingData.buffer === undefined ) {
  25703. const byteLength = binding.byteLength;
  25704. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  25705. const bufferGPU = device.createBuffer( {
  25706. label: 'bindingBuffer_' + binding.name,
  25707. size: byteLength,
  25708. usage: usage
  25709. } );
  25710. bindingData.buffer = bufferGPU;
  25711. }
  25712. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  25713. } else if ( binding.isStorageBuffer ) {
  25714. const bindingData = backend.get( binding );
  25715. if ( bindingData.buffer === undefined ) {
  25716. const attribute = binding.attribute;
  25717. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  25718. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  25719. bindingData.buffer = backend.get( attribute ).buffer;
  25720. }
  25721. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  25722. } else if ( binding.isSampler ) {
  25723. const textureGPU = backend.get( binding.texture );
  25724. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  25725. } else if ( binding.isSampledTexture ) {
  25726. const textureData = backend.get( binding.texture );
  25727. let resourceGPU;
  25728. if ( textureData.externalTexture !== undefined ) {
  25729. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  25730. } else {
  25731. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  25732. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  25733. resourceGPU = textureData[ propertyName ];
  25734. if ( resourceGPU === undefined ) {
  25735. const aspectGPU = GPUTextureAspect.All;
  25736. let dimensionViewGPU;
  25737. if ( binding.isSampledCubeTexture ) {
  25738. dimensionViewGPU = GPUTextureViewDimension.Cube;
  25739. } else if ( binding.isSampledTexture3D ) {
  25740. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  25741. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  25742. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  25743. } else {
  25744. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  25745. }
  25746. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  25747. }
  25748. }
  25749. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  25750. }
  25751. bindingPoint ++;
  25752. }
  25753. return device.createBindGroup( {
  25754. label: 'bindGroup_' + bindGroup.name,
  25755. layout: layoutGPU,
  25756. entries: entriesGPU
  25757. } );
  25758. }
  25759. }
  25760. class WebGPUPipelineUtils {
  25761. constructor( backend ) {
  25762. this.backend = backend;
  25763. }
  25764. _getSampleCount( renderObjectContext ) {
  25765. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  25766. }
  25767. createRenderPipeline( renderObject, promises ) {
  25768. const { object, material, geometry, pipeline } = renderObject;
  25769. const { vertexProgram, fragmentProgram } = pipeline;
  25770. const backend = this.backend;
  25771. const device = backend.device;
  25772. const utils = backend.utils;
  25773. const pipelineData = backend.get( pipeline );
  25774. // bind group layouts
  25775. const bindGroupLayouts = [];
  25776. for ( const bindGroup of renderObject.getBindings() ) {
  25777. const bindingsData = backend.get( bindGroup );
  25778. bindGroupLayouts.push( bindingsData.layout );
  25779. }
  25780. // vertex buffers
  25781. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  25782. // blending
  25783. let blending;
  25784. if ( material.transparent === true && material.blending !== NoBlending ) {
  25785. blending = this._getBlending( material );
  25786. }
  25787. // stencil
  25788. let stencilFront = {};
  25789. if ( material.stencilWrite === true ) {
  25790. stencilFront = {
  25791. compare: this._getStencilCompare( material ),
  25792. failOp: this._getStencilOperation( material.stencilFail ),
  25793. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  25794. passOp: this._getStencilOperation( material.stencilZPass )
  25795. };
  25796. }
  25797. const colorWriteMask = this._getColorWriteMask( material );
  25798. const targets = [];
  25799. if ( renderObject.context.textures !== null ) {
  25800. const textures = renderObject.context.textures;
  25801. for ( let i = 0; i < textures.length; i ++ ) {
  25802. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  25803. targets.push( {
  25804. format: colorFormat,
  25805. blend: blending,
  25806. writeMask: colorWriteMask
  25807. } );
  25808. }
  25809. } else {
  25810. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  25811. targets.push( {
  25812. format: colorFormat,
  25813. blend: blending,
  25814. writeMask: colorWriteMask
  25815. } );
  25816. }
  25817. const vertexModule = backend.get( vertexProgram ).module;
  25818. const fragmentModule = backend.get( fragmentProgram ).module;
  25819. const primitiveState = this._getPrimitiveState( object, geometry, material );
  25820. const depthCompare = this._getDepthCompare( material );
  25821. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  25822. const sampleCount = this._getSampleCount( renderObject.context );
  25823. const pipelineDescriptor = {
  25824. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  25825. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  25826. fragment: Object.assign( {}, fragmentModule, { targets } ),
  25827. primitive: primitiveState,
  25828. multisample: {
  25829. count: sampleCount,
  25830. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  25831. },
  25832. layout: device.createPipelineLayout( {
  25833. bindGroupLayouts
  25834. } )
  25835. };
  25836. const depthStencil = {};
  25837. const renderDepth = renderObject.context.depth;
  25838. const renderStencil = renderObject.context.stencil;
  25839. if ( renderDepth === true || renderStencil === true ) {
  25840. if ( renderDepth === true ) {
  25841. depthStencil.format = depthStencilFormat;
  25842. depthStencil.depthWriteEnabled = material.depthWrite;
  25843. depthStencil.depthCompare = depthCompare;
  25844. }
  25845. if ( renderStencil === true ) {
  25846. depthStencil.stencilFront = stencilFront;
  25847. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  25848. depthStencil.stencilReadMask = material.stencilFuncMask;
  25849. depthStencil.stencilWriteMask = material.stencilWriteMask;
  25850. }
  25851. pipelineDescriptor.depthStencil = depthStencil;
  25852. }
  25853. if ( promises === null ) {
  25854. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  25855. } else {
  25856. const p = new Promise( ( resolve /*, reject*/ ) => {
  25857. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  25858. pipelineData.pipeline = pipeline;
  25859. resolve();
  25860. } );
  25861. } );
  25862. promises.push( p );
  25863. }
  25864. }
  25865. createBundleEncoder( renderContext ) {
  25866. const backend = this.backend;
  25867. const { utils, device } = backend;
  25868. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  25869. const colorFormat = utils.getCurrentColorFormat( renderContext );
  25870. const sampleCount = this._getSampleCount( renderContext );
  25871. const descriptor = {
  25872. label: 'renderBundleEncoder',
  25873. colorFormats: [ colorFormat ],
  25874. depthStencilFormat,
  25875. sampleCount
  25876. };
  25877. return device.createRenderBundleEncoder( descriptor );
  25878. }
  25879. createComputePipeline( pipeline, bindings ) {
  25880. const backend = this.backend;
  25881. const device = backend.device;
  25882. const computeProgram = backend.get( pipeline.computeProgram ).module;
  25883. const pipelineGPU = backend.get( pipeline );
  25884. // bind group layouts
  25885. const bindGroupLayouts = [];
  25886. for ( const bindingsGroup of bindings ) {
  25887. const bindingsData = backend.get( bindingsGroup );
  25888. bindGroupLayouts.push( bindingsData.layout );
  25889. }
  25890. pipelineGPU.pipeline = device.createComputePipeline( {
  25891. compute: computeProgram,
  25892. layout: device.createPipelineLayout( {
  25893. bindGroupLayouts
  25894. } )
  25895. } );
  25896. }
  25897. _getBlending( material ) {
  25898. let color, alpha;
  25899. const blending = material.blending;
  25900. const blendSrc = material.blendSrc;
  25901. const blendDst = material.blendDst;
  25902. const blendEquation = material.blendEquation;
  25903. if ( blending === CustomBlending ) {
  25904. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  25905. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  25906. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  25907. color = {
  25908. srcFactor: this._getBlendFactor( blendSrc ),
  25909. dstFactor: this._getBlendFactor( blendDst ),
  25910. operation: this._getBlendOperation( blendEquation )
  25911. };
  25912. alpha = {
  25913. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  25914. dstFactor: this._getBlendFactor( blendDstAlpha ),
  25915. operation: this._getBlendOperation( blendEquationAlpha )
  25916. };
  25917. } else {
  25918. const premultipliedAlpha = material.premultipliedAlpha;
  25919. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  25920. color = {
  25921. srcFactor: srcRGB,
  25922. dstFactor: dstRGB,
  25923. operation: GPUBlendOperation.Add
  25924. };
  25925. alpha = {
  25926. srcFactor: srcAlpha,
  25927. dstFactor: dstAlpha,
  25928. operation: GPUBlendOperation.Add
  25929. };
  25930. };
  25931. if ( premultipliedAlpha ) {
  25932. switch ( blending ) {
  25933. case NormalBlending:
  25934. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  25935. break;
  25936. case AdditiveBlending:
  25937. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  25938. break;
  25939. case SubtractiveBlending:
  25940. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  25941. break;
  25942. case MultiplyBlending:
  25943. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  25944. break;
  25945. }
  25946. } else {
  25947. switch ( blending ) {
  25948. case NormalBlending:
  25949. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  25950. break;
  25951. case AdditiveBlending:
  25952. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  25953. break;
  25954. case SubtractiveBlending:
  25955. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  25956. break;
  25957. case MultiplyBlending:
  25958. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  25959. break;
  25960. }
  25961. }
  25962. }
  25963. if ( color !== undefined && alpha !== undefined ) {
  25964. return { color, alpha };
  25965. } else {
  25966. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  25967. }
  25968. }
  25969. _getBlendFactor( blend ) {
  25970. let blendFactor;
  25971. switch ( blend ) {
  25972. case ZeroFactor:
  25973. blendFactor = GPUBlendFactor.Zero;
  25974. break;
  25975. case OneFactor:
  25976. blendFactor = GPUBlendFactor.One;
  25977. break;
  25978. case SrcColorFactor:
  25979. blendFactor = GPUBlendFactor.Src;
  25980. break;
  25981. case OneMinusSrcColorFactor:
  25982. blendFactor = GPUBlendFactor.OneMinusSrc;
  25983. break;
  25984. case SrcAlphaFactor:
  25985. blendFactor = GPUBlendFactor.SrcAlpha;
  25986. break;
  25987. case OneMinusSrcAlphaFactor:
  25988. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  25989. break;
  25990. case DstColorFactor:
  25991. blendFactor = GPUBlendFactor.Dst;
  25992. break;
  25993. case OneMinusDstColorFactor:
  25994. blendFactor = GPUBlendFactor.OneMinusDstColor;
  25995. break;
  25996. case DstAlphaFactor:
  25997. blendFactor = GPUBlendFactor.DstAlpha;
  25998. break;
  25999. case OneMinusDstAlphaFactor:
  26000. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  26001. break;
  26002. case SrcAlphaSaturateFactor:
  26003. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  26004. break;
  26005. case BlendColorFactor:
  26006. blendFactor = GPUBlendFactor.Constant;
  26007. break;
  26008. case OneMinusBlendColorFactor:
  26009. blendFactor = GPUBlendFactor.OneMinusConstant;
  26010. break;
  26011. default:
  26012. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  26013. }
  26014. return blendFactor;
  26015. }
  26016. _getStencilCompare( material ) {
  26017. let stencilCompare;
  26018. const stencilFunc = material.stencilFunc;
  26019. switch ( stencilFunc ) {
  26020. case NeverStencilFunc:
  26021. stencilCompare = GPUCompareFunction.Never;
  26022. break;
  26023. case AlwaysStencilFunc:
  26024. stencilCompare = GPUCompareFunction.Always;
  26025. break;
  26026. case LessStencilFunc:
  26027. stencilCompare = GPUCompareFunction.Less;
  26028. break;
  26029. case LessEqualStencilFunc:
  26030. stencilCompare = GPUCompareFunction.LessEqual;
  26031. break;
  26032. case EqualStencilFunc:
  26033. stencilCompare = GPUCompareFunction.Equal;
  26034. break;
  26035. case GreaterEqualStencilFunc:
  26036. stencilCompare = GPUCompareFunction.GreaterEqual;
  26037. break;
  26038. case GreaterStencilFunc:
  26039. stencilCompare = GPUCompareFunction.Greater;
  26040. break;
  26041. case NotEqualStencilFunc:
  26042. stencilCompare = GPUCompareFunction.NotEqual;
  26043. break;
  26044. default:
  26045. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  26046. }
  26047. return stencilCompare;
  26048. }
  26049. _getStencilOperation( op ) {
  26050. let stencilOperation;
  26051. switch ( op ) {
  26052. case KeepStencilOp:
  26053. stencilOperation = GPUStencilOperation.Keep;
  26054. break;
  26055. case ZeroStencilOp:
  26056. stencilOperation = GPUStencilOperation.Zero;
  26057. break;
  26058. case ReplaceStencilOp:
  26059. stencilOperation = GPUStencilOperation.Replace;
  26060. break;
  26061. case InvertStencilOp:
  26062. stencilOperation = GPUStencilOperation.Invert;
  26063. break;
  26064. case IncrementStencilOp:
  26065. stencilOperation = GPUStencilOperation.IncrementClamp;
  26066. break;
  26067. case DecrementStencilOp:
  26068. stencilOperation = GPUStencilOperation.DecrementClamp;
  26069. break;
  26070. case IncrementWrapStencilOp:
  26071. stencilOperation = GPUStencilOperation.IncrementWrap;
  26072. break;
  26073. case DecrementWrapStencilOp:
  26074. stencilOperation = GPUStencilOperation.DecrementWrap;
  26075. break;
  26076. default:
  26077. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  26078. }
  26079. return stencilOperation;
  26080. }
  26081. _getBlendOperation( blendEquation ) {
  26082. let blendOperation;
  26083. switch ( blendEquation ) {
  26084. case AddEquation:
  26085. blendOperation = GPUBlendOperation.Add;
  26086. break;
  26087. case SubtractEquation:
  26088. blendOperation = GPUBlendOperation.Subtract;
  26089. break;
  26090. case ReverseSubtractEquation:
  26091. blendOperation = GPUBlendOperation.ReverseSubtract;
  26092. break;
  26093. case MinEquation:
  26094. blendOperation = GPUBlendOperation.Min;
  26095. break;
  26096. case MaxEquation:
  26097. blendOperation = GPUBlendOperation.Max;
  26098. break;
  26099. default:
  26100. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  26101. }
  26102. return blendOperation;
  26103. }
  26104. _getPrimitiveState( object, geometry, material ) {
  26105. const descriptor = {};
  26106. const utils = this.backend.utils;
  26107. descriptor.topology = utils.getPrimitiveTopology( object, material );
  26108. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  26109. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  26110. }
  26111. switch ( material.side ) {
  26112. case FrontSide:
  26113. descriptor.frontFace = GPUFrontFace.CCW;
  26114. descriptor.cullMode = GPUCullMode.Back;
  26115. break;
  26116. case BackSide:
  26117. descriptor.frontFace = GPUFrontFace.CCW;
  26118. descriptor.cullMode = GPUCullMode.Front;
  26119. break;
  26120. case DoubleSide:
  26121. descriptor.frontFace = GPUFrontFace.CCW;
  26122. descriptor.cullMode = GPUCullMode.None;
  26123. break;
  26124. default:
  26125. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  26126. break;
  26127. }
  26128. return descriptor;
  26129. }
  26130. _getColorWriteMask( material ) {
  26131. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  26132. }
  26133. _getDepthCompare( material ) {
  26134. let depthCompare;
  26135. if ( material.depthTest === false ) {
  26136. depthCompare = GPUCompareFunction.Always;
  26137. } else {
  26138. const depthFunc = material.depthFunc;
  26139. switch ( depthFunc ) {
  26140. case NeverDepth:
  26141. depthCompare = GPUCompareFunction.Never;
  26142. break;
  26143. case AlwaysDepth:
  26144. depthCompare = GPUCompareFunction.Always;
  26145. break;
  26146. case LessDepth:
  26147. depthCompare = GPUCompareFunction.Less;
  26148. break;
  26149. case LessEqualDepth:
  26150. depthCompare = GPUCompareFunction.LessEqual;
  26151. break;
  26152. case EqualDepth:
  26153. depthCompare = GPUCompareFunction.Equal;
  26154. break;
  26155. case GreaterEqualDepth:
  26156. depthCompare = GPUCompareFunction.GreaterEqual;
  26157. break;
  26158. case GreaterDepth:
  26159. depthCompare = GPUCompareFunction.Greater;
  26160. break;
  26161. case NotEqualDepth:
  26162. depthCompare = GPUCompareFunction.NotEqual;
  26163. break;
  26164. default:
  26165. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  26166. }
  26167. }
  26168. return depthCompare;
  26169. }
  26170. }
  26171. /*// debugger tools
  26172. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  26173. //*/
  26174. //
  26175. class WebGPUBackend extends Backend {
  26176. constructor( parameters = {} ) {
  26177. super( parameters );
  26178. this.isWebGPUBackend = true;
  26179. // some parameters require default values other than "undefined"
  26180. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  26181. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  26182. this.trackTimestamp = ( parameters.trackTimestamp === true );
  26183. this.device = null;
  26184. this.context = null;
  26185. this.colorBuffer = null;
  26186. this.defaultRenderPassdescriptor = null;
  26187. this.utils = new WebGPUUtils( this );
  26188. this.attributeUtils = new WebGPUAttributeUtils( this );
  26189. this.bindingUtils = new WebGPUBindingUtils( this );
  26190. this.pipelineUtils = new WebGPUPipelineUtils( this );
  26191. this.textureUtils = new WebGPUTextureUtils( this );
  26192. this.occludedResolveCache = new Map();
  26193. }
  26194. async init( renderer ) {
  26195. await super.init( renderer );
  26196. //
  26197. const parameters = this.parameters;
  26198. // create the device if it is not passed with parameters
  26199. let device;
  26200. if ( parameters.device === undefined ) {
  26201. const adapterOptions = {
  26202. powerPreference: parameters.powerPreference
  26203. };
  26204. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  26205. if ( adapter === null ) {
  26206. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  26207. }
  26208. // feature support
  26209. const features = Object.values( GPUFeatureName );
  26210. const supportedFeatures = [];
  26211. for ( const name of features ) {
  26212. if ( adapter.features.has( name ) ) {
  26213. supportedFeatures.push( name );
  26214. }
  26215. }
  26216. const deviceDescriptor = {
  26217. requiredFeatures: supportedFeatures,
  26218. requiredLimits: parameters.requiredLimits
  26219. };
  26220. device = await adapter.requestDevice( deviceDescriptor );
  26221. } else {
  26222. device = parameters.device;
  26223. }
  26224. device.lost.then( ( info ) => {
  26225. const deviceLossInfo = {
  26226. api: 'WebGPU',
  26227. message: info.message || 'Unknown reason',
  26228. reason: info.reason || null,
  26229. originalEvent: info
  26230. };
  26231. renderer.onDeviceLost( deviceLossInfo );
  26232. } );
  26233. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  26234. this.device = device;
  26235. this.context = context;
  26236. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  26237. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  26238. this.context.configure( {
  26239. device: this.device,
  26240. format: this.utils.getPreferredCanvasFormat(),
  26241. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  26242. alphaMode: alphaMode
  26243. } );
  26244. this.updateSize();
  26245. }
  26246. get coordinateSystem() {
  26247. return WebGPUCoordinateSystem;
  26248. }
  26249. async getArrayBufferAsync( attribute ) {
  26250. return await this.attributeUtils.getArrayBufferAsync( attribute );
  26251. }
  26252. getContext() {
  26253. return this.context;
  26254. }
  26255. _getDefaultRenderPassDescriptor() {
  26256. let descriptor = this.defaultRenderPassdescriptor;
  26257. if ( descriptor === null ) {
  26258. const renderer = this.renderer;
  26259. descriptor = {
  26260. colorAttachments: [ {
  26261. view: null
  26262. } ],
  26263. };
  26264. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  26265. descriptor.depthStencilAttachment = {
  26266. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  26267. };
  26268. }
  26269. const colorAttachment = descriptor.colorAttachments[ 0 ];
  26270. if ( this.renderer.samples > 0 ) {
  26271. colorAttachment.view = this.colorBuffer.createView();
  26272. } else {
  26273. colorAttachment.resolveTarget = undefined;
  26274. }
  26275. this.defaultRenderPassdescriptor = descriptor;
  26276. }
  26277. const colorAttachment = descriptor.colorAttachments[ 0 ];
  26278. if ( this.renderer.samples > 0 ) {
  26279. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  26280. } else {
  26281. colorAttachment.view = this.context.getCurrentTexture().createView();
  26282. }
  26283. return descriptor;
  26284. }
  26285. _getRenderPassDescriptor( renderContext ) {
  26286. const renderTarget = renderContext.renderTarget;
  26287. const renderTargetData = this.get( renderTarget );
  26288. let descriptors = renderTargetData.descriptors;
  26289. if ( descriptors === undefined ||
  26290. renderTargetData.width !== renderTarget.width ||
  26291. renderTargetData.height !== renderTarget.height ||
  26292. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  26293. renderTargetData.samples !== renderTarget.samples
  26294. ) {
  26295. descriptors = {};
  26296. renderTargetData.descriptors = descriptors;
  26297. // dispose
  26298. const onDispose = () => {
  26299. renderTarget.removeEventListener( 'dispose', onDispose );
  26300. this.delete( renderTarget );
  26301. };
  26302. renderTarget.addEventListener( 'dispose', onDispose );
  26303. }
  26304. const cacheKey = renderContext.getCacheKey();
  26305. let descriptor = descriptors[ cacheKey ];
  26306. if ( descriptor === undefined ) {
  26307. const textures = renderContext.textures;
  26308. const colorAttachments = [];
  26309. for ( let i = 0; i < textures.length; i ++ ) {
  26310. const textureData = this.get( textures[ i ] );
  26311. const textureView = textureData.texture.createView( {
  26312. baseMipLevel: renderContext.activeMipmapLevel,
  26313. mipLevelCount: 1,
  26314. baseArrayLayer: renderContext.activeCubeFace,
  26315. dimension: GPUTextureViewDimension.TwoD
  26316. } );
  26317. let view, resolveTarget;
  26318. if ( textureData.msaaTexture !== undefined ) {
  26319. view = textureData.msaaTexture.createView();
  26320. resolveTarget = textureView;
  26321. } else {
  26322. view = textureView;
  26323. resolveTarget = undefined;
  26324. }
  26325. colorAttachments.push( {
  26326. view,
  26327. resolveTarget,
  26328. loadOp: GPULoadOp.Load,
  26329. storeOp: GPUStoreOp.Store
  26330. } );
  26331. }
  26332. descriptor = {
  26333. colorAttachments,
  26334. };
  26335. if ( renderContext.depth ) {
  26336. const depthTextureData = this.get( renderContext.depthTexture );
  26337. const depthStencilAttachment = {
  26338. view: depthTextureData.texture.createView()
  26339. };
  26340. descriptor.depthStencilAttachment = depthStencilAttachment;
  26341. }
  26342. descriptors[ cacheKey ] = descriptor;
  26343. renderTargetData.width = renderTarget.width;
  26344. renderTargetData.height = renderTarget.height;
  26345. renderTargetData.samples = renderTarget.samples;
  26346. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  26347. }
  26348. return descriptor;
  26349. }
  26350. beginRender( renderContext ) {
  26351. const renderContextData = this.get( renderContext );
  26352. const device = this.device;
  26353. const occlusionQueryCount = renderContext.occlusionQueryCount;
  26354. let occlusionQuerySet;
  26355. if ( occlusionQueryCount > 0 ) {
  26356. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  26357. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  26358. // Get a reference to the array of objects with queries. The renderContextData property
  26359. // can be changed by another render pass before the buffer.mapAsyc() completes.
  26360. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  26361. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  26362. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  26363. //
  26364. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  26365. renderContextData.occlusionQuerySet = occlusionQuerySet;
  26366. renderContextData.occlusionQueryIndex = 0;
  26367. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  26368. renderContextData.lastOcclusionObject = null;
  26369. }
  26370. let descriptor;
  26371. if ( renderContext.textures === null ) {
  26372. descriptor = this._getDefaultRenderPassDescriptor();
  26373. } else {
  26374. descriptor = this._getRenderPassDescriptor( renderContext );
  26375. }
  26376. this.initTimestampQuery( renderContext, descriptor );
  26377. descriptor.occlusionQuerySet = occlusionQuerySet;
  26378. const depthStencilAttachment = descriptor.depthStencilAttachment;
  26379. if ( renderContext.textures !== null ) {
  26380. const colorAttachments = descriptor.colorAttachments;
  26381. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  26382. const colorAttachment = colorAttachments[ i ];
  26383. if ( renderContext.clearColor ) {
  26384. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  26385. colorAttachment.loadOp = GPULoadOp.Clear;
  26386. colorAttachment.storeOp = GPUStoreOp.Store;
  26387. } else {
  26388. colorAttachment.loadOp = GPULoadOp.Load;
  26389. colorAttachment.storeOp = GPUStoreOp.Store;
  26390. }
  26391. }
  26392. } else {
  26393. const colorAttachment = descriptor.colorAttachments[ 0 ];
  26394. if ( renderContext.clearColor ) {
  26395. colorAttachment.clearValue = renderContext.clearColorValue;
  26396. colorAttachment.loadOp = GPULoadOp.Clear;
  26397. colorAttachment.storeOp = GPUStoreOp.Store;
  26398. } else {
  26399. colorAttachment.loadOp = GPULoadOp.Load;
  26400. colorAttachment.storeOp = GPUStoreOp.Store;
  26401. }
  26402. }
  26403. //
  26404. if ( renderContext.depth ) {
  26405. if ( renderContext.clearDepth ) {
  26406. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  26407. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  26408. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  26409. } else {
  26410. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  26411. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  26412. }
  26413. }
  26414. if ( renderContext.stencil ) {
  26415. if ( renderContext.clearStencil ) {
  26416. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  26417. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  26418. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  26419. } else {
  26420. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  26421. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  26422. }
  26423. }
  26424. //
  26425. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  26426. const currentPass = encoder.beginRenderPass( descriptor );
  26427. //
  26428. renderContextData.descriptor = descriptor;
  26429. renderContextData.encoder = encoder;
  26430. renderContextData.currentPass = currentPass;
  26431. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  26432. renderContextData.renderBundles = [];
  26433. //
  26434. if ( renderContext.viewport ) {
  26435. this.updateViewport( renderContext );
  26436. }
  26437. if ( renderContext.scissor ) {
  26438. const { x, y, width, height } = renderContext.scissorValue;
  26439. currentPass.setScissorRect( x, y, width, height );
  26440. }
  26441. }
  26442. finishRender( renderContext ) {
  26443. const renderContextData = this.get( renderContext );
  26444. const occlusionQueryCount = renderContext.occlusionQueryCount;
  26445. if ( renderContextData.renderBundles.length > 0 ) {
  26446. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  26447. }
  26448. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  26449. renderContextData.currentPass.endOcclusionQuery();
  26450. }
  26451. renderContextData.currentPass.end();
  26452. if ( occlusionQueryCount > 0 ) {
  26453. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  26454. //
  26455. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  26456. if ( queryResolveBuffer === undefined ) {
  26457. queryResolveBuffer = this.device.createBuffer(
  26458. {
  26459. size: bufferSize,
  26460. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  26461. }
  26462. );
  26463. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  26464. }
  26465. //
  26466. const readBuffer = this.device.createBuffer(
  26467. {
  26468. size: bufferSize,
  26469. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  26470. }
  26471. );
  26472. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  26473. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  26474. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  26475. renderContextData.occlusionQueryBuffer = readBuffer;
  26476. //
  26477. this.resolveOccludedAsync( renderContext );
  26478. }
  26479. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  26480. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  26481. //
  26482. if ( renderContext.textures !== null ) {
  26483. const textures = renderContext.textures;
  26484. for ( let i = 0; i < textures.length; i ++ ) {
  26485. const texture = textures[ i ];
  26486. if ( texture.generateMipmaps === true ) {
  26487. this.textureUtils.generateMipmaps( texture );
  26488. }
  26489. }
  26490. }
  26491. }
  26492. isOccluded( renderContext, object ) {
  26493. const renderContextData = this.get( renderContext );
  26494. return renderContextData.occluded && renderContextData.occluded.has( object );
  26495. }
  26496. async resolveOccludedAsync( renderContext ) {
  26497. const renderContextData = this.get( renderContext );
  26498. // handle occlusion query results
  26499. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  26500. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  26501. const occluded = new WeakSet();
  26502. renderContextData.currentOcclusionQueryObjects = null;
  26503. renderContextData.currentOcclusionQueryBuffer = null;
  26504. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  26505. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  26506. const results = new BigUint64Array( buffer );
  26507. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  26508. if ( results[ i ] !== BigInt( 0 ) ) {
  26509. occluded.add( currentOcclusionQueryObjects[ i ] );
  26510. }
  26511. }
  26512. currentOcclusionQueryBuffer.destroy();
  26513. renderContextData.occluded = occluded;
  26514. }
  26515. }
  26516. updateViewport( renderContext ) {
  26517. const { currentPass } = this.get( renderContext );
  26518. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  26519. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  26520. }
  26521. clear( color, depth, stencil, renderTargetData = null ) {
  26522. const device = this.device;
  26523. const renderer = this.renderer;
  26524. let colorAttachments = [];
  26525. let depthStencilAttachment;
  26526. let clearValue;
  26527. let supportsDepth;
  26528. let supportsStencil;
  26529. if ( color ) {
  26530. const clearColor = this.getClearColor();
  26531. if ( this.renderer.alpha === true ) {
  26532. // premultiply alpha
  26533. const a = clearColor.a;
  26534. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  26535. } else {
  26536. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  26537. }
  26538. }
  26539. if ( renderTargetData === null ) {
  26540. supportsDepth = renderer.depth;
  26541. supportsStencil = renderer.stencil;
  26542. const descriptor = this._getDefaultRenderPassDescriptor();
  26543. if ( color ) {
  26544. colorAttachments = descriptor.colorAttachments;
  26545. const colorAttachment = colorAttachments[ 0 ];
  26546. colorAttachment.clearValue = clearValue;
  26547. colorAttachment.loadOp = GPULoadOp.Clear;
  26548. colorAttachment.storeOp = GPUStoreOp.Store;
  26549. }
  26550. if ( supportsDepth || supportsStencil ) {
  26551. depthStencilAttachment = descriptor.depthStencilAttachment;
  26552. }
  26553. } else {
  26554. supportsDepth = renderTargetData.depth;
  26555. supportsStencil = renderTargetData.stencil;
  26556. if ( color ) {
  26557. for ( const texture of renderTargetData.textures ) {
  26558. const textureData = this.get( texture );
  26559. const textureView = textureData.texture.createView();
  26560. let view, resolveTarget;
  26561. if ( textureData.msaaTexture !== undefined ) {
  26562. view = textureData.msaaTexture.createView();
  26563. resolveTarget = textureView;
  26564. } else {
  26565. view = textureView;
  26566. resolveTarget = undefined;
  26567. }
  26568. colorAttachments.push( {
  26569. view,
  26570. resolveTarget,
  26571. clearValue,
  26572. loadOp: GPULoadOp.Clear,
  26573. storeOp: GPUStoreOp.Store
  26574. } );
  26575. }
  26576. }
  26577. if ( supportsDepth || supportsStencil ) {
  26578. const depthTextureData = this.get( renderTargetData.depthTexture );
  26579. depthStencilAttachment = {
  26580. view: depthTextureData.texture.createView()
  26581. };
  26582. }
  26583. }
  26584. //
  26585. if ( supportsDepth ) {
  26586. if ( depth ) {
  26587. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  26588. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  26589. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  26590. } else {
  26591. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  26592. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  26593. }
  26594. }
  26595. //
  26596. if ( supportsStencil ) {
  26597. if ( stencil ) {
  26598. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  26599. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  26600. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  26601. } else {
  26602. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  26603. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  26604. }
  26605. }
  26606. //
  26607. const encoder = device.createCommandEncoder( {} );
  26608. const currentPass = encoder.beginRenderPass( {
  26609. colorAttachments,
  26610. depthStencilAttachment
  26611. } );
  26612. currentPass.end();
  26613. device.queue.submit( [ encoder.finish() ] );
  26614. }
  26615. // compute
  26616. beginCompute( computeGroup ) {
  26617. const groupGPU = this.get( computeGroup );
  26618. const descriptor = {};
  26619. this.initTimestampQuery( computeGroup, descriptor );
  26620. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  26621. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  26622. }
  26623. compute( computeGroup, computeNode, bindings, pipeline ) {
  26624. const { passEncoderGPU } = this.get( computeGroup );
  26625. // pipeline
  26626. const pipelineGPU = this.get( pipeline ).pipeline;
  26627. passEncoderGPU.setPipeline( pipelineGPU );
  26628. // bind groups
  26629. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  26630. const bindGroup = bindings[ i ];
  26631. const bindingsData = this.get( bindGroup );
  26632. passEncoderGPU.setBindGroup( i, bindingsData.group );
  26633. }
  26634. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  26635. const computeNodeData = this.get( computeNode );
  26636. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  26637. const { dispatchSize } = computeNodeData;
  26638. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  26639. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  26640. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  26641. } else {
  26642. dispatchSize.x = computeNode.dispatchCount;
  26643. }
  26644. passEncoderGPU.dispatchWorkgroups(
  26645. dispatchSize.x,
  26646. dispatchSize.y,
  26647. dispatchSize.z
  26648. );
  26649. }
  26650. finishCompute( computeGroup ) {
  26651. const groupData = this.get( computeGroup );
  26652. groupData.passEncoderGPU.end();
  26653. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  26654. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  26655. }
  26656. async waitForGPU() {
  26657. await this.device.queue.onSubmittedWorkDone();
  26658. }
  26659. // render object
  26660. draw( renderObject, info ) {
  26661. const { object, context, pipeline } = renderObject;
  26662. const bindings = renderObject.getBindings();
  26663. const renderContextData = this.get( context );
  26664. const pipelineGPU = this.get( pipeline ).pipeline;
  26665. const currentSets = renderContextData.currentSets;
  26666. const passEncoderGPU = renderContextData.currentPass;
  26667. const drawParams = renderObject.getDrawParameters();
  26668. if ( drawParams === null ) return;
  26669. // pipeline
  26670. if ( currentSets.pipeline !== pipelineGPU ) {
  26671. passEncoderGPU.setPipeline( pipelineGPU );
  26672. currentSets.pipeline = pipelineGPU;
  26673. }
  26674. // bind groups
  26675. const currentBindingGroups = currentSets.bindingGroups;
  26676. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  26677. const bindGroup = bindings[ i ];
  26678. const bindingsData = this.get( bindGroup );
  26679. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  26680. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  26681. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  26682. }
  26683. }
  26684. // attributes
  26685. const index = renderObject.getIndex();
  26686. const hasIndex = ( index !== null );
  26687. // index
  26688. if ( hasIndex === true ) {
  26689. if ( currentSets.index !== index ) {
  26690. const buffer = this.get( index ).buffer;
  26691. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  26692. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  26693. currentSets.index = index;
  26694. }
  26695. }
  26696. // vertex buffers
  26697. const vertexBuffers = renderObject.getVertexBuffers();
  26698. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  26699. const vertexBuffer = vertexBuffers[ i ];
  26700. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  26701. const buffer = this.get( vertexBuffer ).buffer;
  26702. passEncoderGPU.setVertexBuffer( i, buffer );
  26703. currentSets.attributes[ i ] = vertexBuffer;
  26704. }
  26705. }
  26706. // occlusion queries - handle multiple consecutive draw calls for an object
  26707. if ( renderContextData.occlusionQuerySet !== undefined ) {
  26708. const lastObject = renderContextData.lastOcclusionObject;
  26709. if ( lastObject !== object ) {
  26710. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  26711. passEncoderGPU.endOcclusionQuery();
  26712. renderContextData.occlusionQueryIndex ++;
  26713. }
  26714. if ( object.occlusionTest === true ) {
  26715. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  26716. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  26717. }
  26718. renderContextData.lastOcclusionObject = object;
  26719. }
  26720. }
  26721. // draw
  26722. if ( object.isBatchedMesh === true ) {
  26723. const starts = object._multiDrawStarts;
  26724. const counts = object._multiDrawCounts;
  26725. const drawCount = object._multiDrawCount;
  26726. const drawInstances = object._multiDrawInstances;
  26727. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  26728. for ( let i = 0; i < drawCount; i ++ ) {
  26729. const count = drawInstances ? drawInstances[ i ] : 1;
  26730. const firstInstance = count > 1 ? 0 : i;
  26731. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  26732. }
  26733. } else if ( hasIndex === true ) {
  26734. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  26735. const indirect = renderObject.getIndirect();
  26736. if ( indirect !== null ) {
  26737. const buffer = this.get( indirect ).buffer;
  26738. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  26739. } else {
  26740. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  26741. }
  26742. info.update( object, indexCount, instanceCount );
  26743. } else {
  26744. const { vertexCount, instanceCount, firstVertex } = drawParams;
  26745. const indirect = renderObject.getIndirect();
  26746. if ( indirect !== null ) {
  26747. const buffer = this.get( indirect ).buffer;
  26748. passEncoderGPU.drawIndirect( buffer, 0 );
  26749. } else {
  26750. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  26751. }
  26752. info.update( object, vertexCount, instanceCount );
  26753. }
  26754. }
  26755. // cache key
  26756. needsRenderUpdate( renderObject ) {
  26757. const data = this.get( renderObject );
  26758. const { object, material } = renderObject;
  26759. const utils = this.utils;
  26760. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  26761. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  26762. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  26763. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  26764. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  26765. let needsUpdate = false;
  26766. if ( data.material !== material || data.materialVersion !== material.version ||
  26767. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  26768. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  26769. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  26770. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  26771. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  26772. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  26773. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  26774. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  26775. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  26776. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  26777. data.primitiveTopology !== primitiveTopology ||
  26778. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  26779. ) {
  26780. data.material = material; data.materialVersion = material.version;
  26781. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  26782. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  26783. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  26784. data.colorWrite = material.colorWrite;
  26785. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  26786. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  26787. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  26788. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  26789. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  26790. data.sampleCount = sampleCount;
  26791. data.colorSpace = colorSpace;
  26792. data.colorFormat = colorFormat;
  26793. data.depthStencilFormat = depthStencilFormat;
  26794. data.primitiveTopology = primitiveTopology;
  26795. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  26796. needsUpdate = true;
  26797. }
  26798. return needsUpdate;
  26799. }
  26800. getRenderCacheKey( renderObject ) {
  26801. const { object, material } = renderObject;
  26802. const utils = this.utils;
  26803. const renderContext = renderObject.context;
  26804. return [
  26805. material.transparent, material.blending, material.premultipliedAlpha,
  26806. material.blendSrc, material.blendDst, material.blendEquation,
  26807. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  26808. material.colorWrite,
  26809. material.depthWrite, material.depthTest, material.depthFunc,
  26810. material.stencilWrite, material.stencilFunc,
  26811. material.stencilFail, material.stencilZFail, material.stencilZPass,
  26812. material.stencilFuncMask, material.stencilWriteMask,
  26813. material.side,
  26814. utils.getSampleCountRenderContext( renderContext ),
  26815. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  26816. utils.getPrimitiveTopology( object, material ),
  26817. renderObject.getGeometryCacheKey(),
  26818. renderObject.clippingContextCacheKey
  26819. ].join();
  26820. }
  26821. // textures
  26822. createSampler( texture ) {
  26823. this.textureUtils.createSampler( texture );
  26824. }
  26825. destroySampler( texture ) {
  26826. this.textureUtils.destroySampler( texture );
  26827. }
  26828. createDefaultTexture( texture ) {
  26829. this.textureUtils.createDefaultTexture( texture );
  26830. }
  26831. createTexture( texture, options ) {
  26832. this.textureUtils.createTexture( texture, options );
  26833. }
  26834. updateTexture( texture, options ) {
  26835. this.textureUtils.updateTexture( texture, options );
  26836. }
  26837. generateMipmaps( texture ) {
  26838. this.textureUtils.generateMipmaps( texture );
  26839. }
  26840. destroyTexture( texture ) {
  26841. this.textureUtils.destroyTexture( texture );
  26842. }
  26843. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  26844. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  26845. }
  26846. initTimestampQuery( renderContext, descriptor ) {
  26847. if ( ! this.trackTimestamp ) return;
  26848. const renderContextData = this.get( renderContext );
  26849. if ( ! renderContextData.timeStampQuerySet ) {
  26850. const type = renderContext.isComputeNode ? 'compute' : 'render';
  26851. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  26852. const timestampWrites = {
  26853. querySet: timeStampQuerySet,
  26854. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  26855. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  26856. };
  26857. Object.assign( descriptor, { timestampWrites } );
  26858. renderContextData.timeStampQuerySet = timeStampQuerySet;
  26859. }
  26860. }
  26861. // timestamp utils
  26862. prepareTimestampBuffer( renderContext, encoder ) {
  26863. if ( ! this.trackTimestamp ) return;
  26864. const renderContextData = this.get( renderContext );
  26865. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  26866. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  26867. renderContextData.currentTimestampQueryBuffers = {
  26868. resolveBuffer: this.device.createBuffer( {
  26869. label: 'timestamp resolve buffer',
  26870. size: size,
  26871. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  26872. } ),
  26873. resultBuffer: this.device.createBuffer( {
  26874. label: 'timestamp result buffer',
  26875. size: size,
  26876. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  26877. } )
  26878. };
  26879. }
  26880. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  26881. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  26882. if ( resultBuffer.mapState === 'unmapped' ) {
  26883. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  26884. }
  26885. }
  26886. async resolveTimestampAsync( renderContext, type = 'render' ) {
  26887. if ( ! this.trackTimestamp ) return;
  26888. const renderContextData = this.get( renderContext );
  26889. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  26890. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  26891. await this.device.queue.onSubmittedWorkDone();
  26892. if ( resultBuffer.mapState === 'unmapped' ) {
  26893. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  26894. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  26895. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  26896. this.renderer.info.updateTimestamp( type, duration );
  26897. resultBuffer.unmap();
  26898. } );
  26899. }
  26900. }
  26901. // node builder
  26902. createNodeBuilder( object, renderer ) {
  26903. return new WGSLNodeBuilder( object, renderer );
  26904. }
  26905. // program
  26906. createProgram( program ) {
  26907. const programGPU = this.get( program );
  26908. programGPU.module = {
  26909. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  26910. entryPoint: 'main'
  26911. };
  26912. }
  26913. destroyProgram( program ) {
  26914. this.delete( program );
  26915. }
  26916. // pipelines
  26917. createRenderPipeline( renderObject, promises ) {
  26918. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  26919. }
  26920. createComputePipeline( computePipeline, bindings ) {
  26921. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  26922. }
  26923. beginBundle( renderContext ) {
  26924. const renderContextData = this.get( renderContext );
  26925. renderContextData._currentPass = renderContextData.currentPass;
  26926. renderContextData._currentSets = renderContextData.currentSets;
  26927. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  26928. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  26929. }
  26930. finishBundle( renderContext, bundle ) {
  26931. const renderContextData = this.get( renderContext );
  26932. const bundleEncoder = renderContextData.currentPass;
  26933. const bundleGPU = bundleEncoder.finish();
  26934. this.get( bundle ).bundleGPU = bundleGPU;
  26935. // restore render pass state
  26936. renderContextData.currentSets = renderContextData._currentSets;
  26937. renderContextData.currentPass = renderContextData._currentPass;
  26938. }
  26939. addBundle( renderContext, bundle ) {
  26940. const renderContextData = this.get( renderContext );
  26941. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  26942. }
  26943. // bindings
  26944. createBindings( bindGroup, bindings, cacheIndex, version ) {
  26945. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  26946. }
  26947. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  26948. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  26949. }
  26950. updateBinding( binding ) {
  26951. this.bindingUtils.updateBinding( binding );
  26952. }
  26953. // attributes
  26954. createIndexAttribute( attribute ) {
  26955. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  26956. }
  26957. createAttribute( attribute ) {
  26958. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  26959. }
  26960. createStorageAttribute( attribute ) {
  26961. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  26962. }
  26963. createIndirectStorageAttribute( attribute ) {
  26964. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  26965. }
  26966. updateAttribute( attribute ) {
  26967. this.attributeUtils.updateAttribute( attribute );
  26968. }
  26969. destroyAttribute( attribute ) {
  26970. this.attributeUtils.destroyAttribute( attribute );
  26971. }
  26972. // canvas
  26973. updateSize() {
  26974. this.colorBuffer = this.textureUtils.getColorBuffer();
  26975. this.defaultRenderPassdescriptor = null;
  26976. }
  26977. // utils public
  26978. getMaxAnisotropy() {
  26979. return 16;
  26980. }
  26981. hasFeature( name ) {
  26982. return this.device.features.has( name );
  26983. }
  26984. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  26985. let dstX = 0;
  26986. let dstY = 0;
  26987. let dstLayer = 0;
  26988. let srcX = 0;
  26989. let srcY = 0;
  26990. let srcLayer = 0;
  26991. let srcWidth = srcTexture.image.width;
  26992. let srcHeight = srcTexture.image.height;
  26993. if ( srcRegion !== null ) {
  26994. srcX = srcRegion.x;
  26995. srcY = srcRegion.y;
  26996. srcLayer = srcRegion.z || 0;
  26997. srcWidth = srcRegion.width;
  26998. srcHeight = srcRegion.height;
  26999. }
  27000. if ( dstPosition !== null ) {
  27001. dstX = dstPosition.x;
  27002. dstY = dstPosition.y;
  27003. dstLayer = dstPosition.z || 0;
  27004. }
  27005. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  27006. const sourceGPU = this.get( srcTexture ).texture;
  27007. const destinationGPU = this.get( dstTexture ).texture;
  27008. encoder.copyTextureToTexture(
  27009. {
  27010. texture: sourceGPU,
  27011. mipLevel: level,
  27012. origin: { x: srcX, y: srcY, z: srcLayer }
  27013. },
  27014. {
  27015. texture: destinationGPU,
  27016. mipLevel: level,
  27017. origin: { x: dstX, y: dstY, z: dstLayer }
  27018. },
  27019. [
  27020. srcWidth,
  27021. srcHeight,
  27022. 1
  27023. ]
  27024. );
  27025. this.device.queue.submit( [ encoder.finish() ] );
  27026. }
  27027. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  27028. const renderContextData = this.get( renderContext );
  27029. let sourceGPU = null;
  27030. if ( renderContext.renderTarget ) {
  27031. if ( texture.isDepthTexture ) {
  27032. sourceGPU = this.get( renderContext.depthTexture ).texture;
  27033. } else {
  27034. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  27035. }
  27036. } else {
  27037. if ( texture.isDepthTexture ) {
  27038. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  27039. } else {
  27040. sourceGPU = this.context.getCurrentTexture();
  27041. }
  27042. }
  27043. const destinationGPU = this.get( texture ).texture;
  27044. if ( sourceGPU.format !== destinationGPU.format ) {
  27045. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  27046. return;
  27047. }
  27048. let encoder;
  27049. if ( renderContextData.currentPass ) {
  27050. renderContextData.currentPass.end();
  27051. encoder = renderContextData.encoder;
  27052. } else {
  27053. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  27054. }
  27055. encoder.copyTextureToTexture(
  27056. {
  27057. texture: sourceGPU,
  27058. origin: [ rectangle.x, rectangle.y, 0 ],
  27059. },
  27060. {
  27061. texture: destinationGPU
  27062. },
  27063. [
  27064. rectangle.z,
  27065. rectangle.w
  27066. ]
  27067. );
  27068. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  27069. if ( renderContextData.currentPass ) {
  27070. const { descriptor } = renderContextData;
  27071. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  27072. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  27073. }
  27074. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  27075. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  27076. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  27077. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  27078. if ( renderContext.viewport ) {
  27079. this.updateViewport( renderContext );
  27080. }
  27081. if ( renderContext.scissor ) {
  27082. const { x, y, width, height } = renderContext.scissorValue;
  27083. renderContextData.currentPass.setScissorRect( x, y, width, height );
  27084. }
  27085. } else {
  27086. this.device.queue.submit( [ encoder.finish() ] );
  27087. }
  27088. }
  27089. }
  27090. class IESSpotLight extends SpotLight {
  27091. constructor( color, intensity, distance, angle, penumbra, decay ) {
  27092. super( color, intensity, distance, angle, penumbra, decay );
  27093. this.iesMap = null;
  27094. }
  27095. copy( source, recursive ) {
  27096. super.copy( source, recursive );
  27097. this.iesMap = source.iesMap;
  27098. return this;
  27099. }
  27100. }
  27101. class BasicNodeLibrary extends NodeLibrary {
  27102. constructor() {
  27103. super();
  27104. this.addLight( PointLightNode, PointLight );
  27105. this.addLight( DirectionalLightNode, DirectionalLight );
  27106. this.addLight( RectAreaLightNode, RectAreaLight );
  27107. this.addLight( SpotLightNode, SpotLight );
  27108. this.addLight( AmbientLightNode, AmbientLight );
  27109. this.addLight( HemisphereLightNode, HemisphereLight );
  27110. this.addLight( LightProbeNode, LightProbe );
  27111. this.addLight( IESSpotLightNode, IESSpotLight );
  27112. this.addToneMapping( linearToneMapping, LinearToneMapping );
  27113. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  27114. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  27115. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  27116. this.addToneMapping( agxToneMapping, AgXToneMapping );
  27117. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  27118. }
  27119. }
  27120. class WebGPURenderer extends Renderer {
  27121. constructor( parameters = {} ) {
  27122. let BackendClass;
  27123. if ( parameters.forceWebGL ) {
  27124. BackendClass = WebGLBackend;
  27125. } else {
  27126. BackendClass = WebGPUBackend;
  27127. parameters.getFallback = () => {
  27128. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  27129. return new WebGLBackend( parameters );
  27130. };
  27131. }
  27132. const backend = new BackendClass( parameters );
  27133. super( backend, parameters );
  27134. this.library = new BasicNodeLibrary();
  27135. this.isWebGPURenderer = true;
  27136. }
  27137. }
  27138. class BundleGroup extends Group {
  27139. constructor() {
  27140. super();
  27141. this.isBundleGroup = true;
  27142. this.type = 'BundleGroup';
  27143. this.static = true;
  27144. this.version = 0;
  27145. }
  27146. set needsUpdate( value ) {
  27147. if ( value === true ) this.version ++;
  27148. }
  27149. }
  27150. const _material = /*@__PURE__*/ new NodeMaterial();
  27151. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  27152. class PostProcessing {
  27153. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  27154. this.renderer = renderer;
  27155. this.outputNode = outputNode;
  27156. this.outputColorTransform = true;
  27157. this.needsUpdate = true;
  27158. _material.name = 'PostProcessing';
  27159. }
  27160. render() {
  27161. this.update();
  27162. const renderer = this.renderer;
  27163. const toneMapping = renderer.toneMapping;
  27164. const outputColorSpace = renderer.outputColorSpace;
  27165. renderer.toneMapping = NoToneMapping;
  27166. renderer.outputColorSpace = LinearSRGBColorSpace;
  27167. //
  27168. _quadMesh.render( renderer );
  27169. //
  27170. renderer.toneMapping = toneMapping;
  27171. renderer.outputColorSpace = outputColorSpace;
  27172. }
  27173. update() {
  27174. if ( this.needsUpdate === true ) {
  27175. const renderer = this.renderer;
  27176. const toneMapping = renderer.toneMapping;
  27177. const outputColorSpace = renderer.outputColorSpace;
  27178. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  27179. _quadMesh.material.needsUpdate = true;
  27180. this.needsUpdate = false;
  27181. }
  27182. }
  27183. async renderAsync() {
  27184. this.update();
  27185. const renderer = this.renderer;
  27186. const toneMapping = renderer.toneMapping;
  27187. const outputColorSpace = renderer.outputColorSpace;
  27188. renderer.toneMapping = NoToneMapping;
  27189. renderer.outputColorSpace = LinearSRGBColorSpace;
  27190. //
  27191. await _quadMesh.renderAsync( renderer );
  27192. //
  27193. renderer.toneMapping = toneMapping;
  27194. renderer.outputColorSpace = outputColorSpace;
  27195. }
  27196. }
  27197. // renderer state
  27198. function saveRendererState( renderer, state = {} ) {
  27199. state.toneMapping = renderer.toneMapping;
  27200. state.toneMappingExposure = renderer.toneMappingExposure;
  27201. state.outputColorSpace = renderer.outputColorSpace;
  27202. state.renderTarget = renderer.getRenderTarget();
  27203. state.activeCubeFace = renderer.getActiveCubeFace();
  27204. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27205. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27206. state.pixelRatio = renderer.getPixelRatio();
  27207. state.mrt = renderer.getMRT();
  27208. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27209. state.clearAlpha = renderer.getClearAlpha();
  27210. state.autoClear = renderer.autoClear;
  27211. state.scissorTest = renderer.getScissorTest();
  27212. return state;
  27213. }
  27214. function resetRendererState( renderer, state ) {
  27215. state = saveRendererState( renderer, state );
  27216. renderer.setMRT( null );
  27217. renderer.setRenderObjectFunction( null );
  27218. renderer.setClearColor( 0x000000, 1 );
  27219. renderer.autoClear = true;
  27220. return state;
  27221. }
  27222. function restoreRendererState( renderer, state ) {
  27223. renderer.toneMapping = state.toneMapping;
  27224. renderer.toneMappingExposure = state.toneMappingExposure;
  27225. renderer.outputColorSpace = state.outputColorSpace;
  27226. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27227. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27228. renderer.setPixelRatio( state.pixelRatio );
  27229. renderer.setMRT( state.mrt );
  27230. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27231. renderer.autoClear = state.autoClear;
  27232. renderer.setScissorTest( state.scissorTest );
  27233. }
  27234. // renderer and scene state
  27235. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  27236. state = saveRendererState( renderer, state );
  27237. state.background = scene.background;
  27238. state.backgroundNode = scene.backgroundNode;
  27239. state.overrideMaterial = scene.overrideMaterial;
  27240. return state;
  27241. }
  27242. function resetRendererAndSceneState( renderer, scene, state ) {
  27243. state = saveRendererAndSceneState( renderer, scene, state );
  27244. scene.background = null;
  27245. scene.backgroundNode = null;
  27246. scene.overrideMaterial = null;
  27247. return state;
  27248. }
  27249. function restoreRendererAndSceneState( renderer, scene, state ) {
  27250. restoreRendererState( renderer, state );
  27251. scene.background = state.background;
  27252. scene.backgroundNode = state.backgroundNode;
  27253. scene.overrideMaterial = state.overrideMaterial;
  27254. }
  27255. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  27256. __proto__: null,
  27257. resetRendererAndSceneState: resetRendererAndSceneState,
  27258. resetRendererState: resetRendererState,
  27259. restoreRendererAndSceneState: restoreRendererAndSceneState,
  27260. restoreRendererState: restoreRendererState,
  27261. saveRendererAndSceneState: saveRendererAndSceneState,
  27262. saveRendererState: saveRendererState
  27263. });
  27264. class StorageTexture extends Texture {
  27265. constructor( width = 1, height = 1 ) {
  27266. super();
  27267. this.image = { width, height };
  27268. this.magFilter = LinearFilter;
  27269. this.minFilter = LinearFilter;
  27270. this.isStorageTexture = true;
  27271. }
  27272. }
  27273. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  27274. constructor( array, itemSize ) {
  27275. super( array, itemSize, Uint32Array );
  27276. this.isIndirectStorageBufferAttribute = true;
  27277. }
  27278. }
  27279. class NodeLoader extends Loader {
  27280. constructor( manager ) {
  27281. super( manager );
  27282. this.textures = {};
  27283. this.nodes = {};
  27284. }
  27285. load( url, onLoad, onProgress, onError ) {
  27286. const loader = new FileLoader( this.manager );
  27287. loader.setPath( this.path );
  27288. loader.setRequestHeader( this.requestHeader );
  27289. loader.setWithCredentials( this.withCredentials );
  27290. loader.load( url, ( text ) => {
  27291. try {
  27292. onLoad( this.parse( JSON.parse( text ) ) );
  27293. } catch ( e ) {
  27294. if ( onError ) {
  27295. onError( e );
  27296. } else {
  27297. console.error( e );
  27298. }
  27299. this.manager.itemError( url );
  27300. }
  27301. }, onProgress, onError );
  27302. }
  27303. parseNodes( json ) {
  27304. const nodes = {};
  27305. if ( json !== undefined ) {
  27306. for ( const nodeJSON of json ) {
  27307. const { uuid, type } = nodeJSON;
  27308. nodes[ uuid ] = this.createNodeFromType( type );
  27309. nodes[ uuid ].uuid = uuid;
  27310. }
  27311. const meta = { nodes, textures: this.textures };
  27312. for ( const nodeJSON of json ) {
  27313. nodeJSON.meta = meta;
  27314. const node = nodes[ nodeJSON.uuid ];
  27315. node.deserialize( nodeJSON );
  27316. delete nodeJSON.meta;
  27317. }
  27318. }
  27319. return nodes;
  27320. }
  27321. parse( json ) {
  27322. const node = this.createNodeFromType( json.type );
  27323. node.uuid = json.uuid;
  27324. const nodes = this.parseNodes( json.nodes );
  27325. const meta = { nodes, textures: this.textures };
  27326. json.meta = meta;
  27327. node.deserialize( json );
  27328. delete json.meta;
  27329. return node;
  27330. }
  27331. setTextures( value ) {
  27332. this.textures = value;
  27333. return this;
  27334. }
  27335. setNodes( value ) {
  27336. this.nodes = value;
  27337. return this;
  27338. }
  27339. createNodeFromType( type ) {
  27340. if ( this.nodes[ type ] === undefined ) {
  27341. console.error( 'THREE.NodeLoader: Node type not found:', type );
  27342. return float();
  27343. }
  27344. return nodeObject( new this.nodes[ type ]() );
  27345. }
  27346. }
  27347. class NodeMaterialLoader extends MaterialLoader {
  27348. constructor( manager ) {
  27349. super( manager );
  27350. this.nodes = {};
  27351. this.nodeMaterials = {};
  27352. }
  27353. parse( json ) {
  27354. const material = super.parse( json );
  27355. const nodes = this.nodes;
  27356. const inputNodes = json.inputNodes;
  27357. for ( const property in inputNodes ) {
  27358. const uuid = inputNodes[ property ];
  27359. material[ property ] = nodes[ uuid ];
  27360. }
  27361. return material;
  27362. }
  27363. setNodes( value ) {
  27364. this.nodes = value;
  27365. return this;
  27366. }
  27367. setNodeMaterials( value ) {
  27368. this.nodeMaterials = value;
  27369. return this;
  27370. }
  27371. createMaterialFromType( type ) {
  27372. const materialClass = this.nodeMaterials[ type ];
  27373. if ( materialClass !== undefined ) {
  27374. return new materialClass();
  27375. }
  27376. return super.createMaterialFromType( type );
  27377. }
  27378. }
  27379. class NodeObjectLoader extends ObjectLoader {
  27380. constructor( manager ) {
  27381. super( manager );
  27382. this.nodes = {};
  27383. this.nodeMaterials = {};
  27384. this._nodesJSON = null;
  27385. }
  27386. setNodes( value ) {
  27387. this.nodes = value;
  27388. return this;
  27389. }
  27390. setNodeMaterials( value ) {
  27391. this.nodeMaterials = value;
  27392. return this;
  27393. }
  27394. parse( json, onLoad ) {
  27395. this._nodesJSON = json.nodes;
  27396. const data = super.parse( json, onLoad );
  27397. this._nodesJSON = null; // dispose
  27398. return data;
  27399. }
  27400. parseNodes( json, textures ) {
  27401. if ( json !== undefined ) {
  27402. const loader = new NodeLoader();
  27403. loader.setNodes( this.nodes );
  27404. loader.setTextures( textures );
  27405. return loader.parseNodes( json );
  27406. }
  27407. return {};
  27408. }
  27409. parseMaterials( json, textures ) {
  27410. const materials = {};
  27411. if ( json !== undefined ) {
  27412. const nodes = this.parseNodes( this._nodesJSON, textures );
  27413. const loader = new NodeMaterialLoader();
  27414. loader.setTextures( textures );
  27415. loader.setNodes( nodes );
  27416. loader.setNodeMaterials( this.nodeMaterials );
  27417. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27418. const data = json[ i ];
  27419. materials[ data.uuid ] = loader.parse( data );
  27420. }
  27421. }
  27422. return materials;
  27423. }
  27424. }
  27425. class ClippingGroup extends Group {
  27426. constructor() {
  27427. super();
  27428. this.isClippingGroup = true;
  27429. this.clippingPlanes = [];
  27430. this.enabled = true;
  27431. this.clipIntersection = false;
  27432. this.clipShadows = false;
  27433. }
  27434. }
  27435. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, InstancedPointsNodeMaterial, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号