three.webgpu.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648
  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 = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  817. this._cacheKeyVersion = this.version;
  818. }
  819. return this._cacheKey;
  820. }
  821. /**
  822. * Generate a custom cache key for this node.
  823. *
  824. * @return {Number} The cache key of the node.
  825. * @default 0
  826. */
  827. customCacheKey() {
  828. return 0;
  829. }
  830. /**
  831. * Returns the references to this node which is by default `this`.
  832. *
  833. * @return {Node} A reference to this node.
  834. */
  835. getScope() {
  836. return this;
  837. }
  838. /**
  839. * Returns the hash of the node which is used to identify the node. By default it's
  840. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  841. * depending on their implementation.
  842. *
  843. * @param {NodeBuilder} builder - The current node builder.
  844. * @return {String} The hash.
  845. */
  846. getHash( /*builder*/ ) {
  847. return this.uuid;
  848. }
  849. /**
  850. * Returns the update type of {@link Node#update}.
  851. *
  852. * @return {NodeUpdateType} The update type.
  853. */
  854. getUpdateType() {
  855. return this.updateType;
  856. }
  857. /**
  858. * Returns the update type of {@link Node#updateBefore}.
  859. *
  860. * @return {NodeUpdateType} The update type.
  861. */
  862. getUpdateBeforeType() {
  863. return this.updateBeforeType;
  864. }
  865. /**
  866. * Returns the update type of {@link Node#updateAfter}.
  867. *
  868. * @return {NodeUpdateType} The update type.
  869. */
  870. getUpdateAfterType() {
  871. return this.updateAfterType;
  872. }
  873. /**
  874. * Certain types are composed of multiple elements. For example a `vec3`
  875. * is composed of three `float` values. This method returns the type of
  876. * these elements.
  877. *
  878. * @param {NodeBuilder} builder - The current node builder.
  879. * @return {String} The type of the node.
  880. */
  881. getElementType( builder ) {
  882. const type = this.getNodeType( builder );
  883. const elementType = builder.getElementType( type );
  884. return elementType;
  885. }
  886. /**
  887. * Returns the node's type.
  888. *
  889. * @param {NodeBuilder} builder - The current node builder.
  890. * @return {String} The type of the node.
  891. */
  892. getNodeType( builder ) {
  893. const nodeProperties = builder.getNodeProperties( this );
  894. if ( nodeProperties.outputNode ) {
  895. return nodeProperties.outputNode.getNodeType( builder );
  896. }
  897. return this.nodeType;
  898. }
  899. /**
  900. * This method is used during the build process of a node and ensures
  901. * equal nodes are not built multiple times but just once. For example if
  902. * `attribute( 'uv' )` is used multiple times by the user, the build
  903. * process makes sure to process just the first node.
  904. *
  905. * @param {NodeBuilder} builder - The current node builder.
  906. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  907. */
  908. getShared( builder ) {
  909. const hash = this.getHash( builder );
  910. const nodeFromHash = builder.getNodeFromHash( hash );
  911. return nodeFromHash || this;
  912. }
  913. /**
  914. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  915. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  916. * The output node must be returned in the `return` statement.
  917. *
  918. * @param {NodeBuilder} builder - The current node builder.
  919. * @return {Node?} The output node.
  920. */
  921. setup( builder ) {
  922. const nodeProperties = builder.getNodeProperties( this );
  923. let index = 0;
  924. for ( const childNode of this.getChildren() ) {
  925. nodeProperties[ 'node' + index ++ ] = childNode;
  926. }
  927. // return a outputNode if exists
  928. return null;
  929. }
  930. /**
  931. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  932. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  933. *
  934. * @param {NodeBuilder} builder - The current node builder.
  935. */
  936. analyze( builder ) {
  937. const usageCount = builder.increaseUsage( this );
  938. if ( usageCount === 1 ) {
  939. // node flow children
  940. const nodeProperties = builder.getNodeProperties( this );
  941. for ( const childNode of Object.values( nodeProperties ) ) {
  942. if ( childNode && childNode.isNode === true ) {
  943. childNode.build( builder );
  944. }
  945. }
  946. }
  947. }
  948. /**
  949. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  950. * This state builds the output node and returns the resulting shader string.
  951. *
  952. * @param {NodeBuilder} builder - The current node builder.
  953. * @param {String?} output - Can be used to define the output type.
  954. * @return {String?} The generated shader string.
  955. */
  956. generate( builder, output ) {
  957. const { outputNode } = builder.getNodeProperties( this );
  958. if ( outputNode && outputNode.isNode === true ) {
  959. return outputNode.build( builder, output );
  960. }
  961. }
  962. /**
  963. * The method can be implemented to update the node's internal state before it is used to render an object.
  964. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  965. *
  966. * @param {NodeFrame} frame - A reference to the current node frame.
  967. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  968. */
  969. updateBefore( /*frame*/ ) {
  970. console.warn( 'Abstract function.' );
  971. }
  972. /**
  973. * The method can be implemented to update the node's internal state after it was used to render an object.
  974. * The {@link Node#updateAfterType} property defines how often the update is executed.
  975. *
  976. * @param {NodeFrame} frame - A reference to the current node frame.
  977. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  978. */
  979. updateAfter( /*frame*/ ) {
  980. console.warn( 'Abstract function.' );
  981. }
  982. /**
  983. * The method can be implemented to update the node's internal state when it is used to render an object.
  984. * The {@link Node#updateType} property defines how often the update is executed.
  985. *
  986. * @param {NodeFrame} frame - A reference to the current node frame.
  987. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  988. */
  989. update( /*frame*/ ) {
  990. console.warn( 'Abstract function.' );
  991. }
  992. /**
  993. * This method performs the build of a node. The behavior of this method as well as its return value depend
  994. * on the current build stage (setup, analyze or generate).
  995. *
  996. * @param {NodeBuilder} builder - The current node builder.
  997. * @param {String?} output - Can be used to define the output type.
  998. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  999. */
  1000. build( builder, output = null ) {
  1001. const refNode = this.getShared( builder );
  1002. if ( this !== refNode ) {
  1003. return refNode.build( builder, output );
  1004. }
  1005. builder.addNode( this );
  1006. builder.addChain( this );
  1007. /* Build stages expected results:
  1008. - "setup" -> Node
  1009. - "analyze" -> null
  1010. - "generate" -> String
  1011. */
  1012. let result = null;
  1013. const buildStage = builder.getBuildStage();
  1014. if ( buildStage === 'setup' ) {
  1015. this.updateReference( builder );
  1016. const properties = builder.getNodeProperties( this );
  1017. if ( properties.initialized !== true ) {
  1018. const stackNodesBeforeSetup = builder.stack.nodes.length;
  1019. properties.initialized = true;
  1020. properties.outputNode = this.setup( builder );
  1021. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  1022. for ( const childNode of Object.values( properties ) ) {
  1023. if ( childNode && childNode.isNode === true ) {
  1024. childNode.build( builder );
  1025. }
  1026. }
  1027. }
  1028. } else if ( buildStage === 'analyze' ) {
  1029. this.analyze( builder );
  1030. } else if ( buildStage === 'generate' ) {
  1031. const isGenerateOnce = this.generate.length === 1;
  1032. if ( isGenerateOnce ) {
  1033. const type = this.getNodeType( builder );
  1034. const nodeData = builder.getDataFromNode( this );
  1035. result = nodeData.snippet;
  1036. if ( result === undefined ) {
  1037. result = this.generate( builder ) || '';
  1038. nodeData.snippet = result;
  1039. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1040. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1041. }
  1042. result = builder.format( result, type, output );
  1043. } else {
  1044. result = this.generate( builder, output ) || '';
  1045. }
  1046. }
  1047. builder.removeChain( this );
  1048. builder.addSequentialNode( this );
  1049. return result;
  1050. }
  1051. /**
  1052. * Returns the child nodes as a JSON object.
  1053. *
  1054. * @return {Object} The serialized child objects as JSON.
  1055. */
  1056. getSerializeChildren() {
  1057. return getNodeChildren( this );
  1058. }
  1059. /**
  1060. * Serializes the node to JSON.
  1061. *
  1062. * @param {Object} json - The output JSON object.
  1063. */
  1064. serialize( json ) {
  1065. const nodeChildren = this.getSerializeChildren();
  1066. const inputNodes = {};
  1067. for ( const { property, index, childNode } of nodeChildren ) {
  1068. if ( index !== undefined ) {
  1069. if ( inputNodes[ property ] === undefined ) {
  1070. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1071. }
  1072. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1073. } else {
  1074. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1075. }
  1076. }
  1077. if ( Object.keys( inputNodes ).length > 0 ) {
  1078. json.inputNodes = inputNodes;
  1079. }
  1080. }
  1081. /**
  1082. * Deserializes the node from the given JSON.
  1083. *
  1084. * @param {Object} json - The JSON object.
  1085. */
  1086. deserialize( json ) {
  1087. if ( json.inputNodes !== undefined ) {
  1088. const nodes = json.meta.nodes;
  1089. for ( const property in json.inputNodes ) {
  1090. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1091. const inputArray = [];
  1092. for ( const uuid of json.inputNodes[ property ] ) {
  1093. inputArray.push( nodes[ uuid ] );
  1094. }
  1095. this[ property ] = inputArray;
  1096. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1097. const inputObject = {};
  1098. for ( const subProperty in json.inputNodes[ property ] ) {
  1099. const uuid = json.inputNodes[ property ][ subProperty ];
  1100. inputObject[ subProperty ] = nodes[ uuid ];
  1101. }
  1102. this[ property ] = inputObject;
  1103. } else {
  1104. const uuid = json.inputNodes[ property ];
  1105. this[ property ] = nodes[ uuid ];
  1106. }
  1107. }
  1108. }
  1109. }
  1110. /**
  1111. * Serializes the node into the three.js JSON Object/Scene format.
  1112. *
  1113. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1114. * @return {Object} The serialized node.
  1115. */
  1116. toJSON( meta ) {
  1117. const { uuid, type } = this;
  1118. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1119. if ( isRoot ) {
  1120. meta = {
  1121. textures: {},
  1122. images: {},
  1123. nodes: {}
  1124. };
  1125. }
  1126. // serialize
  1127. let data = meta.nodes[ uuid ];
  1128. if ( data === undefined ) {
  1129. data = {
  1130. uuid,
  1131. type,
  1132. meta,
  1133. metadata: {
  1134. version: 4.6,
  1135. type: 'Node',
  1136. generator: 'Node.toJSON'
  1137. }
  1138. };
  1139. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1140. this.serialize( data );
  1141. delete data.meta;
  1142. }
  1143. // TODO: Copied from Object3D.toJSON
  1144. function extractFromCache( cache ) {
  1145. const values = [];
  1146. for ( const key in cache ) {
  1147. const data = cache[ key ];
  1148. delete data.metadata;
  1149. values.push( data );
  1150. }
  1151. return values;
  1152. }
  1153. if ( isRoot ) {
  1154. const textures = extractFromCache( meta.textures );
  1155. const images = extractFromCache( meta.images );
  1156. const nodes = extractFromCache( meta.nodes );
  1157. if ( textures.length > 0 ) data.textures = textures;
  1158. if ( images.length > 0 ) data.images = images;
  1159. if ( nodes.length > 0 ) data.nodes = nodes;
  1160. }
  1161. return data;
  1162. }
  1163. }
  1164. /**
  1165. * Base class for representing element access on an array-like
  1166. * node data structures.
  1167. *
  1168. * @augments Node
  1169. */
  1170. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1171. static get type() {
  1172. return 'ArrayElementNode';
  1173. }
  1174. /**
  1175. * Constructs array element node.
  1176. *
  1177. * @param {Node} node - The array-like node.
  1178. * @param {Node} indexNode - The index node that defines the element access.
  1179. */
  1180. constructor( node, indexNode ) {
  1181. super();
  1182. /**
  1183. * The array-like node.
  1184. *
  1185. * @type {Node}
  1186. */
  1187. this.node = node;
  1188. /**
  1189. * The index node that defines the element access.
  1190. *
  1191. * @type {Node}
  1192. */
  1193. this.indexNode = indexNode;
  1194. /**
  1195. * This flag can be used for type testing.
  1196. *
  1197. * @type {Boolean}
  1198. * @readonly
  1199. * @default true
  1200. */
  1201. this.isArrayElementNode = true;
  1202. }
  1203. /**
  1204. * This method is overwritten since the node type is inferred from the array-like node.
  1205. *
  1206. * @param {NodeBuilder} builder - The current node builder.
  1207. * @return {String} The node type.
  1208. */
  1209. getNodeType( builder ) {
  1210. return this.node.getElementType( builder );
  1211. }
  1212. generate( builder ) {
  1213. const nodeSnippet = this.node.build( builder );
  1214. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1215. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1216. }
  1217. }
  1218. /**
  1219. * This module is part of the TSL core and usually not used in app level code.
  1220. * It represents a convert operation during the shader generation process
  1221. * meaning it converts the data type of a node to a target data type.
  1222. *
  1223. * @augments Node
  1224. */
  1225. class ConvertNode extends Node {
  1226. static get type() {
  1227. return 'ConvertNode';
  1228. }
  1229. /**
  1230. * Constructs a new convert node.
  1231. *
  1232. * @param {Node} node - The node which type should be converted.
  1233. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1234. */
  1235. constructor( node, convertTo ) {
  1236. super();
  1237. /**
  1238. * The node which type should be converted.
  1239. *
  1240. * @type {Node}
  1241. */
  1242. this.node = node;
  1243. /**
  1244. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1245. *
  1246. * @type {String}
  1247. */
  1248. this.convertTo = convertTo;
  1249. }
  1250. /**
  1251. * This method is overwritten since the implementation tries to infer the best
  1252. * matching type from the {@link ConvertNode#convertTo} property.
  1253. *
  1254. * @param {NodeBuilder} builder - The current node builder.
  1255. * @return {String} The node type.
  1256. */
  1257. getNodeType( builder ) {
  1258. const requestType = this.node.getNodeType( builder );
  1259. let convertTo = null;
  1260. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1261. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1262. convertTo = overloadingType;
  1263. }
  1264. }
  1265. return convertTo;
  1266. }
  1267. serialize( data ) {
  1268. super.serialize( data );
  1269. data.convertTo = this.convertTo;
  1270. }
  1271. deserialize( data ) {
  1272. super.deserialize( data );
  1273. this.convertTo = data.convertTo;
  1274. }
  1275. generate( builder, output ) {
  1276. const node = this.node;
  1277. const type = this.getNodeType( builder );
  1278. const snippet = node.build( builder, type );
  1279. return builder.format( snippet, type, output );
  1280. }
  1281. }
  1282. /**
  1283. * This module uses cache management to create temporary variables
  1284. * if the node is used more than once to prevent duplicate calculations.
  1285. *
  1286. * The class acts as a base class for many other nodes types.
  1287. *
  1288. * @augments Node
  1289. */
  1290. class TempNode extends Node {
  1291. static get type() {
  1292. return 'TempNode';
  1293. }
  1294. /**
  1295. * Constructs a temp node.
  1296. *
  1297. * @param {String} nodeType - The node type.
  1298. */
  1299. constructor( type ) {
  1300. super( type );
  1301. /**
  1302. * This flag can be used for type testing.
  1303. *
  1304. * @type {Boolean}
  1305. * @readonly
  1306. * @default true
  1307. */
  1308. this.isTempNode = true;
  1309. }
  1310. /**
  1311. * Whether this node is used more than once in context of other nodes.
  1312. *
  1313. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1314. */
  1315. hasDependencies( builder ) {
  1316. return builder.getDataFromNode( this ).usageCount > 1;
  1317. }
  1318. build( builder, output ) {
  1319. const buildStage = builder.getBuildStage();
  1320. if ( buildStage === 'generate' ) {
  1321. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1322. const nodeData = builder.getDataFromNode( this );
  1323. if ( nodeData.propertyName !== undefined ) {
  1324. return builder.format( nodeData.propertyName, type, output );
  1325. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1326. const snippet = super.build( builder, type );
  1327. const nodeVar = builder.getVarFromNode( this, null, type );
  1328. const propertyName = builder.getPropertyName( nodeVar );
  1329. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1330. nodeData.snippet = snippet;
  1331. nodeData.propertyName = propertyName;
  1332. return builder.format( nodeData.propertyName, type, output );
  1333. }
  1334. }
  1335. return super.build( builder, output );
  1336. }
  1337. }
  1338. /**
  1339. * This module is part of the TSL core and usually not used in app level code.
  1340. * It represents a join operation during the shader generation process.
  1341. * For example in can compose/join two single floats into a `vec2` type.
  1342. *
  1343. * @augments TempNode
  1344. */
  1345. class JoinNode extends TempNode {
  1346. static get type() {
  1347. return 'JoinNode';
  1348. }
  1349. /**
  1350. * Constructs a new join node.
  1351. *
  1352. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1353. * @param {String?} [nodeType=null] - The node type.
  1354. */
  1355. constructor( nodes = [], nodeType = null ) {
  1356. super( nodeType );
  1357. /**
  1358. * An array of nodes that should be joined.
  1359. *
  1360. * @type {Array<Node>}
  1361. */
  1362. this.nodes = nodes;
  1363. }
  1364. /**
  1365. * This method is overwritten since the node type must be inferred from the
  1366. * joined data length if not explicitly defined.
  1367. *
  1368. * @param {NodeBuilder} builder - The current node builder.
  1369. * @return {String} The node type.
  1370. */
  1371. getNodeType( builder ) {
  1372. if ( this.nodeType !== null ) {
  1373. return builder.getVectorType( this.nodeType );
  1374. }
  1375. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1376. }
  1377. generate( builder, output ) {
  1378. const type = this.getNodeType( builder );
  1379. const nodes = this.nodes;
  1380. const primitiveType = builder.getComponentType( type );
  1381. const snippetValues = [];
  1382. for ( const input of nodes ) {
  1383. let inputSnippet = input.build( builder );
  1384. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1385. if ( inputPrimitiveType !== primitiveType ) {
  1386. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1387. }
  1388. snippetValues.push( inputSnippet );
  1389. }
  1390. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1391. return builder.format( snippet, type, output );
  1392. }
  1393. }
  1394. const _stringVectorComponents = vectorComponents.join( '' );
  1395. /**
  1396. * This module is part of the TSL core and usually not used in app level code.
  1397. * `SplitNode` represents a property access operation which means it is
  1398. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1399. * For example:
  1400. * ```js
  1401. * const redValue = color.r;
  1402. * ```
  1403. *
  1404. * @augments Node
  1405. */
  1406. class SplitNode extends Node {
  1407. static get type() {
  1408. return 'SplitNode';
  1409. }
  1410. /**
  1411. * Constructs a new split node.
  1412. *
  1413. * @param {Node} node - The node that should be accessed.
  1414. * @param {String} [components='x'] - The components that should be accessed.
  1415. */
  1416. constructor( node, components = 'x' ) {
  1417. super();
  1418. /**
  1419. * The node that should be accessed.
  1420. *
  1421. * @type {Node}
  1422. */
  1423. this.node = node;
  1424. /**
  1425. * The components that should be accessed.
  1426. *
  1427. * @type {Node}
  1428. */
  1429. this.components = components;
  1430. /**
  1431. * This flag can be used for type testing.
  1432. *
  1433. * @type {Boolean}
  1434. * @readonly
  1435. * @default true
  1436. */
  1437. this.isSplitNode = true;
  1438. }
  1439. /**
  1440. * Returns the vector length which is computed based on the requested components.
  1441. *
  1442. * @return {Number} The vector length.
  1443. */
  1444. getVectorLength() {
  1445. let vectorLength = this.components.length;
  1446. for ( const c of this.components ) {
  1447. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1448. }
  1449. return vectorLength;
  1450. }
  1451. /**
  1452. * Returns the component type of the node's type.
  1453. *
  1454. * @param {NodeBuilder} builder - The current node builder.
  1455. * @return {String} The component type.
  1456. */
  1457. getComponentType( builder ) {
  1458. return builder.getComponentType( this.node.getNodeType( builder ) );
  1459. }
  1460. /**
  1461. * This method is overwritten since the node type is inferred from requested components.
  1462. *
  1463. * @param {NodeBuilder} builder - The current node builder.
  1464. * @return {String} The node type.
  1465. */
  1466. getNodeType( builder ) {
  1467. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1468. }
  1469. generate( builder, output ) {
  1470. const node = this.node;
  1471. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1472. let snippet = null;
  1473. if ( nodeTypeLength > 1 ) {
  1474. let type = null;
  1475. const componentsLength = this.getVectorLength();
  1476. if ( componentsLength >= nodeTypeLength ) {
  1477. // needed expand the input node
  1478. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1479. }
  1480. const nodeSnippet = node.build( builder, type );
  1481. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1482. // unnecessary swizzle
  1483. snippet = builder.format( nodeSnippet, type, output );
  1484. } else {
  1485. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1486. }
  1487. } else {
  1488. // ignore .components if .node returns float/integer
  1489. snippet = node.build( builder, output );
  1490. }
  1491. return snippet;
  1492. }
  1493. serialize( data ) {
  1494. super.serialize( data );
  1495. data.components = this.components;
  1496. }
  1497. deserialize( data ) {
  1498. super.deserialize( data );
  1499. this.components = data.components;
  1500. }
  1501. }
  1502. /**
  1503. * This module is part of the TSL core and usually not used in app level code.
  1504. * `SetNode` represents a set operation which means it is used to implement any
  1505. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1506. * For example:
  1507. * ```js
  1508. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1509. * ```
  1510. *
  1511. * @augments TempNode
  1512. */
  1513. class SetNode extends TempNode {
  1514. static get type() {
  1515. return 'SetNode';
  1516. }
  1517. /**
  1518. * Constructs a new set node.
  1519. *
  1520. * @param {Node} sourceNode - The node that should be updated.
  1521. * @param {String} components - The components that should be updated.
  1522. * @param {Node} targetNode - The value node.
  1523. */
  1524. constructor( sourceNode, components, targetNode ) {
  1525. super();
  1526. /**
  1527. * The node that should be updated.
  1528. *
  1529. * @type {Node}
  1530. */
  1531. this.sourceNode = sourceNode;
  1532. /**
  1533. * The components that should be updated.
  1534. *
  1535. * @type {String}
  1536. */
  1537. this.components = components;
  1538. /**
  1539. * The value node.
  1540. *
  1541. * @type {Node}
  1542. */
  1543. this.targetNode = targetNode;
  1544. }
  1545. /**
  1546. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1547. *
  1548. * @param {NodeBuilder} builder - The current node builder.
  1549. * @return {String} The node type.
  1550. */
  1551. getNodeType( builder ) {
  1552. return this.sourceNode.getNodeType( builder );
  1553. }
  1554. generate( builder ) {
  1555. const { sourceNode, components, targetNode } = this;
  1556. const sourceType = this.getNodeType( builder );
  1557. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1558. const targetType = builder.getTypeFromLength( components.length, componentType );
  1559. const targetSnippet = targetNode.build( builder, targetType );
  1560. const sourceSnippet = sourceNode.build( builder, sourceType );
  1561. const length = builder.getTypeLength( sourceType );
  1562. const snippetValues = [];
  1563. for ( let i = 0; i < length; i ++ ) {
  1564. const component = vectorComponents[ i ];
  1565. if ( component === components[ 0 ] ) {
  1566. snippetValues.push( targetSnippet );
  1567. i += components.length - 1;
  1568. } else {
  1569. snippetValues.push( sourceSnippet + '.' + component );
  1570. }
  1571. }
  1572. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1573. }
  1574. }
  1575. /**
  1576. * This module is part of the TSL core and usually not used in app level code.
  1577. * It represents a flip operation during the shader generation process
  1578. * meaning it flips normalized values with the following formula:
  1579. * ```
  1580. * x = 1 - x;
  1581. * ```
  1582. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1583. * `flipSTPQ()` method invocations on node objects. For example:
  1584. * ```js
  1585. * uvNode = uvNode.flipY();
  1586. * ```
  1587. *
  1588. * @augments TempNode
  1589. */
  1590. class FlipNode extends TempNode {
  1591. static get type() {
  1592. return 'FlipNode';
  1593. }
  1594. /**
  1595. * Constructs a new flip node.
  1596. *
  1597. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1598. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1599. */
  1600. constructor( sourceNode, components ) {
  1601. super();
  1602. /**
  1603. * The node which component(s) should be flipped.
  1604. *
  1605. * @type {Node}
  1606. */
  1607. this.sourceNode = sourceNode;
  1608. /**
  1609. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1610. *
  1611. * @type {String}
  1612. */
  1613. this.components = components;
  1614. }
  1615. /**
  1616. * This method is overwritten since the node type is inferred from the source node.
  1617. *
  1618. * @param {NodeBuilder} builder - The current node builder.
  1619. * @return {String} The node type.
  1620. */
  1621. getNodeType( builder ) {
  1622. return this.sourceNode.getNodeType( builder );
  1623. }
  1624. generate( builder ) {
  1625. const { components, sourceNode } = this;
  1626. const sourceType = this.getNodeType( builder );
  1627. const sourceSnippet = sourceNode.build( builder );
  1628. const sourceCache = builder.getVarFromNode( this );
  1629. const sourceProperty = builder.getPropertyName( sourceCache );
  1630. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1631. const length = builder.getTypeLength( sourceType );
  1632. const snippetValues = [];
  1633. let componentIndex = 0;
  1634. for ( let i = 0; i < length; i ++ ) {
  1635. const component = vectorComponents[ i ];
  1636. if ( component === components[ componentIndex ] ) {
  1637. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1638. componentIndex ++;
  1639. } else {
  1640. snippetValues.push( sourceProperty + '.' + component );
  1641. }
  1642. }
  1643. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1644. }
  1645. }
  1646. /**
  1647. * Base class for representing data input nodes.
  1648. *
  1649. * @augments Node
  1650. */
  1651. class InputNode extends Node {
  1652. static get type() {
  1653. return 'InputNode';
  1654. }
  1655. /**
  1656. * Constructs a new input node.
  1657. *
  1658. * @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).
  1659. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1660. */
  1661. constructor( value, nodeType = null ) {
  1662. super( nodeType );
  1663. /**
  1664. * This flag can be used for type testing.
  1665. *
  1666. * @type {Boolean}
  1667. * @readonly
  1668. * @default true
  1669. */
  1670. this.isInputNode = true;
  1671. /**
  1672. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1673. *
  1674. * @type {Any}
  1675. */
  1676. this.value = value;
  1677. /**
  1678. * The precision of the value in the shader.
  1679. *
  1680. * @type {('low'|'medium'|'high')?}
  1681. * @default null
  1682. */
  1683. this.precision = null;
  1684. }
  1685. getNodeType( /*builder*/ ) {
  1686. if ( this.nodeType === null ) {
  1687. return getValueType( this.value );
  1688. }
  1689. return this.nodeType;
  1690. }
  1691. /**
  1692. * Returns the input type of the node which is by default the node type. Derived modules
  1693. * might overwrite this method and use a fixed type or compute one analytically.
  1694. *
  1695. * A typical example for different input and node types are textures. The input type of a
  1696. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1697. *
  1698. * @param {NodeBuilder} builder - The current node builder.
  1699. * @return {String} The input type.
  1700. */
  1701. getInputType( builder ) {
  1702. return this.getNodeType( builder );
  1703. }
  1704. /**
  1705. * Sets the precision to the given value. The method can be
  1706. * overwritten in derived classes if the final precision must be computed
  1707. * analytically.
  1708. *
  1709. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1710. * @return {InputNode} A reference to this node.
  1711. */
  1712. setPrecision( precision ) {
  1713. this.precision = precision;
  1714. return this;
  1715. }
  1716. serialize( data ) {
  1717. super.serialize( data );
  1718. data.value = this.value;
  1719. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1720. data.valueType = getValueType( this.value );
  1721. data.nodeType = this.nodeType;
  1722. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1723. data.precision = this.precision;
  1724. }
  1725. deserialize( data ) {
  1726. super.deserialize( data );
  1727. this.nodeType = data.nodeType;
  1728. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1729. this.precision = data.precision || null;
  1730. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1731. }
  1732. generate( /*builder, output*/ ) {
  1733. console.warn( 'Abstract function.' );
  1734. }
  1735. }
  1736. /**
  1737. * Class for representing a constant value in the shader.
  1738. *
  1739. * @augments InputNode
  1740. */
  1741. class ConstNode extends InputNode {
  1742. static get type() {
  1743. return 'ConstNode';
  1744. }
  1745. /**
  1746. * Constructs a new input node.
  1747. *
  1748. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1749. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1750. */
  1751. constructor( value, nodeType = null ) {
  1752. super( value, nodeType );
  1753. /**
  1754. * This flag can be used for type testing.
  1755. *
  1756. * @type {Boolean}
  1757. * @readonly
  1758. * @default true
  1759. */
  1760. this.isConstNode = true;
  1761. }
  1762. /**
  1763. * Generates the shader string of the value with the current node builder.
  1764. *
  1765. * @param {NodeBuilder} builder - The current node builder.
  1766. * @return {String} The generated value as a shader string.
  1767. */
  1768. generateConst( builder ) {
  1769. return builder.generateConst( this.getNodeType( builder ), this.value );
  1770. }
  1771. generate( builder, output ) {
  1772. const type = this.getNodeType( builder );
  1773. return builder.format( this.generateConst( builder ), type, output );
  1774. }
  1775. }
  1776. //
  1777. let currentStack = null;
  1778. const NodeElements = new Map();
  1779. function addMethodChaining( name, nodeElement ) {
  1780. if ( NodeElements.has( name ) ) {
  1781. console.warn( `Redefinition of method chaining ${ name }` );
  1782. return;
  1783. }
  1784. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1785. NodeElements.set( name, nodeElement );
  1786. }
  1787. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1788. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1789. const shaderNodeHandler = {
  1790. setup( NodeClosure, params ) {
  1791. const inputs = params.shift();
  1792. return NodeClosure( nodeObjects( inputs ), ...params );
  1793. },
  1794. get( node, prop, nodeObj ) {
  1795. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1796. if ( node.isStackNode !== true && prop === 'assign' ) {
  1797. return ( ...params ) => {
  1798. currentStack.assign( nodeObj, ...params );
  1799. return nodeObj;
  1800. };
  1801. } else if ( NodeElements.has( prop ) ) {
  1802. const nodeElement = NodeElements.get( prop );
  1803. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1804. } else if ( prop === 'self' ) {
  1805. return node;
  1806. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1807. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1808. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1809. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1810. // accessing properties ( swizzle )
  1811. prop = parseSwizzle( prop );
  1812. return nodeObject( new SplitNode( nodeObj, prop ) );
  1813. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1814. // set properties ( swizzle ) and sort to xyzw sequence
  1815. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1816. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1817. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1818. // set properties ( swizzle ) and sort to xyzw sequence
  1819. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1820. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1821. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1822. // accessing property
  1823. if ( prop === 'width' ) prop = 'x';
  1824. else if ( prop === 'height' ) prop = 'y';
  1825. else if ( prop === 'depth' ) prop = 'z';
  1826. return nodeObject( new SplitNode( node, prop ) );
  1827. } else if ( /^\d+$/.test( prop ) === true ) {
  1828. // accessing array
  1829. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1830. }
  1831. }
  1832. return Reflect.get( node, prop, nodeObj );
  1833. },
  1834. set( node, prop, value, nodeObj ) {
  1835. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1836. // setting properties
  1837. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1838. nodeObj[ prop ].assign( value );
  1839. return true;
  1840. }
  1841. }
  1842. return Reflect.set( node, prop, value, nodeObj );
  1843. }
  1844. };
  1845. const nodeObjectsCacheMap = new WeakMap();
  1846. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1847. const ShaderNodeObject = function ( obj, altType = null ) {
  1848. const type = getValueType( obj );
  1849. if ( type === 'node' ) {
  1850. let nodeObject = nodeObjectsCacheMap.get( obj );
  1851. if ( nodeObject === undefined ) {
  1852. nodeObject = new Proxy( obj, shaderNodeHandler );
  1853. nodeObjectsCacheMap.set( obj, nodeObject );
  1854. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1855. }
  1856. return nodeObject;
  1857. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1858. return nodeObject( getConstNode( obj, altType ) );
  1859. } else if ( type === 'shader' ) {
  1860. return Fn( obj );
  1861. }
  1862. return obj;
  1863. };
  1864. const ShaderNodeObjects = function ( objects, altType = null ) {
  1865. for ( const name in objects ) {
  1866. objects[ name ] = nodeObject( objects[ name ], altType );
  1867. }
  1868. return objects;
  1869. };
  1870. const ShaderNodeArray = function ( array, altType = null ) {
  1871. const len = array.length;
  1872. for ( let i = 0; i < len; i ++ ) {
  1873. array[ i ] = nodeObject( array[ i ], altType );
  1874. }
  1875. return array;
  1876. };
  1877. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1878. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1879. if ( scope === null ) {
  1880. return ( ...params ) => {
  1881. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1882. };
  1883. } else if ( factor !== null ) {
  1884. factor = nodeObject( factor );
  1885. return ( ...params ) => {
  1886. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1887. };
  1888. } else {
  1889. return ( ...params ) => {
  1890. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1891. };
  1892. }
  1893. };
  1894. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1895. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1896. };
  1897. class ShaderCallNodeInternal extends Node {
  1898. constructor( shaderNode, inputNodes ) {
  1899. super();
  1900. this.shaderNode = shaderNode;
  1901. this.inputNodes = inputNodes;
  1902. }
  1903. getNodeType( builder ) {
  1904. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1905. }
  1906. call( builder ) {
  1907. const { shaderNode, inputNodes } = this;
  1908. const properties = builder.getNodeProperties( shaderNode );
  1909. if ( properties.onceOutput ) return properties.onceOutput;
  1910. //
  1911. let result = null;
  1912. if ( shaderNode.layout ) {
  1913. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1914. if ( functionNodesCacheMap === undefined ) {
  1915. functionNodesCacheMap = new WeakMap();
  1916. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1917. }
  1918. let functionNode = functionNodesCacheMap.get( shaderNode );
  1919. if ( functionNode === undefined ) {
  1920. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1921. functionNodesCacheMap.set( shaderNode, functionNode );
  1922. }
  1923. if ( builder.currentFunctionNode !== null ) {
  1924. builder.currentFunctionNode.includes.push( functionNode );
  1925. }
  1926. result = nodeObject( functionNode.call( inputNodes ) );
  1927. } else {
  1928. const jsFunc = shaderNode.jsFunc;
  1929. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1930. result = nodeObject( outputNode );
  1931. }
  1932. if ( shaderNode.once ) {
  1933. properties.onceOutput = result;
  1934. }
  1935. return result;
  1936. }
  1937. getOutputNode( builder ) {
  1938. const properties = builder.getNodeProperties( this );
  1939. if ( properties.outputNode === null ) {
  1940. properties.outputNode = this.setupOutput( builder );
  1941. }
  1942. return properties.outputNode;
  1943. }
  1944. setup( builder ) {
  1945. return this.getOutputNode( builder );
  1946. }
  1947. setupOutput( builder ) {
  1948. builder.addStack();
  1949. builder.stack.outputNode = this.call( builder );
  1950. return builder.removeStack();
  1951. }
  1952. generate( builder, output ) {
  1953. const outputNode = this.getOutputNode( builder );
  1954. return outputNode.build( builder, output );
  1955. }
  1956. }
  1957. class ShaderNodeInternal extends Node {
  1958. constructor( jsFunc, nodeType ) {
  1959. super( nodeType );
  1960. this.jsFunc = jsFunc;
  1961. this.layout = null;
  1962. this.global = true;
  1963. this.once = false;
  1964. }
  1965. setLayout( layout ) {
  1966. this.layout = layout;
  1967. return this;
  1968. }
  1969. call( inputs = null ) {
  1970. nodeObjects( inputs );
  1971. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1972. }
  1973. setup() {
  1974. return this.call();
  1975. }
  1976. }
  1977. const bools = [ false, true ];
  1978. const uints = [ 0, 1, 2, 3 ];
  1979. const ints = [ - 1, - 2 ];
  1980. 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 ];
  1981. const boolsCacheMap = new Map();
  1982. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1983. const uintsCacheMap = new Map();
  1984. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1985. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1986. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1987. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1988. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1989. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1990. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1991. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1992. const getConstNode = ( value, type ) => {
  1993. if ( constNodesCacheMap.has( value ) ) {
  1994. return constNodesCacheMap.get( value );
  1995. } else if ( value.isNode === true ) {
  1996. return value;
  1997. } else {
  1998. return new ConstNode( value, type );
  1999. }
  2000. };
  2001. const safeGetNodeType = ( node ) => {
  2002. try {
  2003. return node.getNodeType();
  2004. } catch ( _ ) {
  2005. return undefined;
  2006. }
  2007. };
  2008. const ConvertType = function ( type, cacheMap = null ) {
  2009. return ( ...params ) => {
  2010. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2011. params = [ getValueFromType( type, ...params ) ];
  2012. }
  2013. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2014. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2015. }
  2016. if ( params.length === 1 ) {
  2017. const node = getConstNode( params[ 0 ], type );
  2018. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2019. return nodeObject( new ConvertNode( node, type ) );
  2020. }
  2021. const nodes = params.map( param => getConstNode( param ) );
  2022. return nodeObject( new JoinNode( nodes, type ) );
  2023. };
  2024. };
  2025. // exports
  2026. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2027. // utils
  2028. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2029. // shader node base
  2030. function ShaderNode( jsFunc, nodeType ) {
  2031. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2032. }
  2033. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2034. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2035. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2036. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2037. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2038. const Fn = ( jsFunc, nodeType ) => {
  2039. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2040. const fn = ( ...params ) => {
  2041. let inputs;
  2042. nodeObjects( params );
  2043. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2044. inputs = [ ...params ];
  2045. } else {
  2046. inputs = params[ 0 ];
  2047. }
  2048. return shaderNode.call( inputs );
  2049. };
  2050. fn.shaderNode = shaderNode;
  2051. fn.setLayout = ( layout ) => {
  2052. shaderNode.setLayout( layout );
  2053. return fn;
  2054. };
  2055. fn.once = () => {
  2056. shaderNode.once = true;
  2057. return fn;
  2058. };
  2059. return fn;
  2060. };
  2061. const tslFn = ( ...params ) => { // @deprecated, r168
  2062. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2063. return Fn( ...params );
  2064. };
  2065. //
  2066. addMethodChaining( 'toGlobal', ( node ) => {
  2067. node.global = true;
  2068. return node;
  2069. } );
  2070. //
  2071. const setCurrentStack = ( stack ) => {
  2072. currentStack = stack;
  2073. };
  2074. const getCurrentStack = () => currentStack;
  2075. const If = ( ...params ) => currentStack.If( ...params );
  2076. function append( node ) {
  2077. if ( currentStack ) currentStack.add( node );
  2078. return node;
  2079. }
  2080. addMethodChaining( 'append', append );
  2081. // types
  2082. const color = new ConvertType( 'color' );
  2083. const float = new ConvertType( 'float', cacheMaps.float );
  2084. const int = new ConvertType( 'int', cacheMaps.ints );
  2085. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2086. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2087. const vec2 = new ConvertType( 'vec2' );
  2088. const ivec2 = new ConvertType( 'ivec2' );
  2089. const uvec2 = new ConvertType( 'uvec2' );
  2090. const bvec2 = new ConvertType( 'bvec2' );
  2091. const vec3 = new ConvertType( 'vec3' );
  2092. const ivec3 = new ConvertType( 'ivec3' );
  2093. const uvec3 = new ConvertType( 'uvec3' );
  2094. const bvec3 = new ConvertType( 'bvec3' );
  2095. const vec4 = new ConvertType( 'vec4' );
  2096. const ivec4 = new ConvertType( 'ivec4' );
  2097. const uvec4 = new ConvertType( 'uvec4' );
  2098. const bvec4 = new ConvertType( 'bvec4' );
  2099. const mat2 = new ConvertType( 'mat2' );
  2100. const mat3 = new ConvertType( 'mat3' );
  2101. const mat4 = new ConvertType( 'mat4' );
  2102. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2103. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2104. addMethodChaining( 'toColor', color );
  2105. addMethodChaining( 'toFloat', float );
  2106. addMethodChaining( 'toInt', int );
  2107. addMethodChaining( 'toUint', uint );
  2108. addMethodChaining( 'toBool', bool );
  2109. addMethodChaining( 'toVec2', vec2 );
  2110. addMethodChaining( 'toIVec2', ivec2 );
  2111. addMethodChaining( 'toUVec2', uvec2 );
  2112. addMethodChaining( 'toBVec2', bvec2 );
  2113. addMethodChaining( 'toVec3', vec3 );
  2114. addMethodChaining( 'toIVec3', ivec3 );
  2115. addMethodChaining( 'toUVec3', uvec3 );
  2116. addMethodChaining( 'toBVec3', bvec3 );
  2117. addMethodChaining( 'toVec4', vec4 );
  2118. addMethodChaining( 'toIVec4', ivec4 );
  2119. addMethodChaining( 'toUVec4', uvec4 );
  2120. addMethodChaining( 'toBVec4', bvec4 );
  2121. addMethodChaining( 'toMat2', mat2 );
  2122. addMethodChaining( 'toMat3', mat3 );
  2123. addMethodChaining( 'toMat4', mat4 );
  2124. // basic nodes
  2125. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2126. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2127. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2128. addMethodChaining( 'element', element );
  2129. addMethodChaining( 'convert', convert );
  2130. /**
  2131. * This node can be used to group single instances of {@link UniformNode}
  2132. * and manage them as a uniform buffer.
  2133. *
  2134. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2135. * will be used when defining the {@link UniformNode#groupNode} property.
  2136. *
  2137. * - `objectGroup`: Uniform buffer per object.
  2138. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2139. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2140. *
  2141. * @augments Node
  2142. */
  2143. class UniformGroupNode extends Node {
  2144. static get type() {
  2145. return 'UniformGroupNode';
  2146. }
  2147. /**
  2148. * Constructs a new uniform group node.
  2149. *
  2150. * @param {String} name - The name of the uniform group node.
  2151. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2152. * @param {Number} [order=1] - Influences the internal sorting.
  2153. */
  2154. constructor( name, shared = false, order = 1 ) {
  2155. super( 'string' );
  2156. /**
  2157. * The name of the uniform group node.
  2158. *
  2159. * @type {String}
  2160. */
  2161. this.name = name;
  2162. /**
  2163. * Whether this uniform group node is shared or not.
  2164. *
  2165. * @type {Boolean}
  2166. * @default false
  2167. */
  2168. this.shared = shared;
  2169. /**
  2170. * Influences the internal sorting.
  2171. * TODO: Add details when this property should be changed.
  2172. *
  2173. * @type {Number}
  2174. * @default 1
  2175. */
  2176. this.order = order;
  2177. /**
  2178. * This flag can be used for type testing.
  2179. *
  2180. * @type {Boolean}
  2181. * @readonly
  2182. * @default true
  2183. */
  2184. this.isUniformGroup = true;
  2185. }
  2186. serialize( data ) {
  2187. super.serialize( data );
  2188. data.name = this.name;
  2189. data.version = this.version;
  2190. data.shared = this.shared;
  2191. }
  2192. deserialize( data ) {
  2193. super.deserialize( data );
  2194. this.name = data.name;
  2195. this.version = data.version;
  2196. this.shared = data.shared;
  2197. }
  2198. }
  2199. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2200. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2201. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2202. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2203. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2204. /**
  2205. * Class for representing a uniform.
  2206. *
  2207. * @augments InputNode
  2208. */
  2209. class UniformNode extends InputNode {
  2210. static get type() {
  2211. return 'UniformNode';
  2212. }
  2213. /**
  2214. * Constructs a new uniform node.
  2215. *
  2216. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2217. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2218. */
  2219. constructor( value, nodeType = null ) {
  2220. super( value, nodeType );
  2221. /**
  2222. * This flag can be used for type testing.
  2223. *
  2224. * @type {Boolean}
  2225. * @readonly
  2226. * @default true
  2227. */
  2228. this.isUniformNode = true;
  2229. /**
  2230. * The name or label of the uniform.
  2231. *
  2232. * @type {String}
  2233. * @default ''
  2234. */
  2235. this.name = '';
  2236. /**
  2237. * The uniform group of this uniform. By default, uniforms are
  2238. * managed per object but they might belong to a shared group
  2239. * which is updated per frame or render call.
  2240. *
  2241. * @type {UniformGroupNode}
  2242. */
  2243. this.groupNode = objectGroup;
  2244. }
  2245. /**
  2246. * Sets the {@link UniformNode#name} property.
  2247. *
  2248. * @param {String} name - The name of the uniform.
  2249. * @return {UniformNode} A reference to this node.
  2250. */
  2251. label( name ) {
  2252. this.name = name;
  2253. return this;
  2254. }
  2255. /**
  2256. * Sets the {@link UniformNode#groupNode} property.
  2257. *
  2258. * @param {UniformGroupNode} group - The uniform group.
  2259. * @return {UniformNode} A reference to this node.
  2260. */
  2261. setGroup( group ) {
  2262. this.groupNode = group;
  2263. return this;
  2264. }
  2265. /**
  2266. * Returns the {@link UniformNode#groupNode}.
  2267. *
  2268. * @return {UniformGroupNode} The uniform group.
  2269. */
  2270. getGroup() {
  2271. return this.groupNode;
  2272. }
  2273. /**
  2274. * By default, this method returns the result of {@link Node#getHash} but derived
  2275. * classes might overwrite this method with a different implementation.
  2276. *
  2277. * @param {NodeBuilder} builder - The current node builder.
  2278. * @return {String} The uniform hash.
  2279. */
  2280. getUniformHash( builder ) {
  2281. return this.getHash( builder );
  2282. }
  2283. onUpdate( callback, updateType ) {
  2284. const self = this.getSelf();
  2285. callback = callback.bind( self );
  2286. return super.onUpdate( ( frame ) => {
  2287. const value = callback( frame, self );
  2288. if ( value !== undefined ) {
  2289. this.value = value;
  2290. }
  2291. }, updateType );
  2292. }
  2293. generate( builder, output ) {
  2294. const type = this.getNodeType( builder );
  2295. const hash = this.getUniformHash( builder );
  2296. let sharedNode = builder.getNodeFromHash( hash );
  2297. if ( sharedNode === undefined ) {
  2298. builder.setHashNode( this, hash );
  2299. sharedNode = this;
  2300. }
  2301. const sharedNodeType = sharedNode.getInputType( builder );
  2302. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2303. const propertyName = builder.getPropertyName( nodeUniform );
  2304. if ( builder.context.label !== undefined ) delete builder.context.label;
  2305. return builder.format( propertyName, type, output );
  2306. }
  2307. }
  2308. const uniform = ( arg1, arg2 ) => {
  2309. const nodeType = getConstNodeType( arg2 || arg1 );
  2310. // @TODO: get ConstNode from .traverse() in the future
  2311. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2312. return nodeObject( new UniformNode( value, nodeType ) );
  2313. };
  2314. /**
  2315. * This class represents a shader property. It can be used on
  2316. * to explicitly define a property and assign a value to it.
  2317. *
  2318. * ```js
  2319. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2320. *```
  2321. * `PropertyNode` is used by the engine to predefined common material properties
  2322. * for TSL code.
  2323. *
  2324. * @augments Node
  2325. */
  2326. class PropertyNode extends Node {
  2327. static get type() {
  2328. return 'PropertyNode';
  2329. }
  2330. /**
  2331. * Constructs a new property node.
  2332. *
  2333. * @param {String} nodeType - The type of the node.
  2334. * @param {String?} [name=null] - The name of the property in the shader.
  2335. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2336. */
  2337. constructor( nodeType, name = null, varying = false ) {
  2338. super( nodeType );
  2339. /**
  2340. * The name of the property in the shader. If no name is defined,
  2341. * the node system auto-generates one.
  2342. *
  2343. * @type {String?}
  2344. * @default null
  2345. */
  2346. this.name = name;
  2347. /**
  2348. * Whether this property is a varying or not.
  2349. *
  2350. * @type {Boolean}
  2351. * @default false
  2352. */
  2353. this.varying = varying;
  2354. /**
  2355. * This flag can be used for type testing.
  2356. *
  2357. * @type {Boolean}
  2358. * @readonly
  2359. * @default true
  2360. */
  2361. this.isPropertyNode = true;
  2362. }
  2363. getHash( builder ) {
  2364. return this.name || super.getHash( builder );
  2365. }
  2366. /**
  2367. * The method is overwritten so it always returns `true`.
  2368. *
  2369. * @param {NodeBuilder} builder - The current node builder.
  2370. * @return {Boolean} Whether this node is global or not.
  2371. */
  2372. isGlobal( /*builder*/ ) {
  2373. return true;
  2374. }
  2375. generate( builder ) {
  2376. let nodeVar;
  2377. if ( this.varying === true ) {
  2378. nodeVar = builder.getVaryingFromNode( this, this.name );
  2379. nodeVar.needsInterpolation = true;
  2380. } else {
  2381. nodeVar = builder.getVarFromNode( this, this.name );
  2382. }
  2383. return builder.getPropertyName( nodeVar );
  2384. }
  2385. }
  2386. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2387. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2388. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2389. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2390. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2391. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2392. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2393. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2394. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2395. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2396. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2397. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2398. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2399. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2400. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2401. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2402. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2403. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2404. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2405. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2406. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2407. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2408. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2409. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2410. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2411. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2412. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2413. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2414. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2415. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2416. /**
  2417. * These node represents an assign operation. Meaning a node is assigned
  2418. * to another node.
  2419. *
  2420. * @augments TempNode
  2421. */
  2422. class AssignNode extends TempNode {
  2423. static get type() {
  2424. return 'AssignNode';
  2425. }
  2426. /**
  2427. * Constructs a new assign node.
  2428. *
  2429. * @param {Node} targetNode - The target node.
  2430. * @param {Node} sourceNode - The source type.
  2431. */
  2432. constructor( targetNode, sourceNode ) {
  2433. super();
  2434. /**
  2435. * The target node.
  2436. *
  2437. * @type {Node}
  2438. */
  2439. this.targetNode = targetNode;
  2440. /**
  2441. * The source node.
  2442. *
  2443. * @type {Node}
  2444. */
  2445. this.sourceNode = sourceNode;
  2446. }
  2447. /**
  2448. * Whether this node is used more than once in context of other nodes. This method
  2449. * is overwritten since it always returns `false` (assigns are unique).
  2450. *
  2451. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2452. */
  2453. hasDependencies() {
  2454. return false;
  2455. }
  2456. getNodeType( builder, output ) {
  2457. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2458. }
  2459. /**
  2460. * Whether a split is required when assigning source to target. This can happen when the component length of
  2461. * target and source data type does not match.
  2462. *
  2463. * @param {NodeBuilder} builder - The current node builder.
  2464. * @return {Boolean} Whether a split is required when assigning source to target.
  2465. */
  2466. needsSplitAssign( builder ) {
  2467. const { targetNode } = this;
  2468. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2469. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2470. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2471. return assignDifferentVector;
  2472. }
  2473. return false;
  2474. }
  2475. generate( builder, output ) {
  2476. const { targetNode, sourceNode } = this;
  2477. const needsSplitAssign = this.needsSplitAssign( builder );
  2478. const targetType = targetNode.getNodeType( builder );
  2479. const target = targetNode.context( { assign: true } ).build( builder );
  2480. const source = sourceNode.build( builder, targetType );
  2481. const sourceType = sourceNode.getNodeType( builder );
  2482. const nodeData = builder.getDataFromNode( this );
  2483. //
  2484. let snippet;
  2485. if ( nodeData.initialized === true ) {
  2486. if ( output !== 'void' ) {
  2487. snippet = target;
  2488. }
  2489. } else if ( needsSplitAssign ) {
  2490. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2491. const sourceProperty = builder.getPropertyName( sourceVar );
  2492. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2493. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2494. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2495. const component = targetNode.components[ i ];
  2496. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2497. }
  2498. if ( output !== 'void' ) {
  2499. snippet = target;
  2500. }
  2501. } else {
  2502. snippet = `${ target } = ${ source }`;
  2503. if ( output === 'void' || sourceType === 'void' ) {
  2504. builder.addLineFlowCode( snippet, this );
  2505. if ( output !== 'void' ) {
  2506. snippet = target;
  2507. }
  2508. }
  2509. }
  2510. nodeData.initialized = true;
  2511. return builder.format( snippet, targetType, output );
  2512. }
  2513. }
  2514. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2515. addMethodChaining( 'assign', assign );
  2516. /**
  2517. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2518. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2519. * this logic.
  2520. *
  2521. * @augments TempNode
  2522. */
  2523. class FunctionCallNode extends TempNode {
  2524. static get type() {
  2525. return 'FunctionCallNode';
  2526. }
  2527. /**
  2528. * Constructs a new function call node.
  2529. *
  2530. * @param {FunctionNode?} functionNode - The function node.
  2531. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2532. */
  2533. constructor( functionNode = null, parameters = {} ) {
  2534. super();
  2535. /**
  2536. * The function node.
  2537. *
  2538. * @type {FunctionNode}
  2539. * @default null
  2540. */
  2541. this.functionNode = functionNode;
  2542. /**
  2543. * The parameters of the function call.
  2544. *
  2545. * @type {Object<String, Node>}
  2546. * @default {}
  2547. */
  2548. this.parameters = parameters;
  2549. }
  2550. /**
  2551. * Sets the parameters of the function call node.
  2552. *
  2553. * @param {Object<String, Node>} parameters - The parameters to set.
  2554. * @return {FunctionCallNode} A reference to this node.
  2555. */
  2556. setParameters( parameters ) {
  2557. this.parameters = parameters;
  2558. return this;
  2559. }
  2560. /**
  2561. * Returns the parameters of the function call node.
  2562. *
  2563. * @return {Object<String, Node>} The parameters of this node.
  2564. */
  2565. getParameters() {
  2566. return this.parameters;
  2567. }
  2568. getNodeType( builder ) {
  2569. return this.functionNode.getNodeType( builder );
  2570. }
  2571. generate( builder ) {
  2572. const params = [];
  2573. const functionNode = this.functionNode;
  2574. const inputs = functionNode.getInputs( builder );
  2575. const parameters = this.parameters;
  2576. const generateInput = ( node, inputNode ) => {
  2577. const type = inputNode.type;
  2578. const pointer = type === 'pointer';
  2579. let output;
  2580. if ( pointer ) output = '&' + node.build( builder );
  2581. else output = node.build( builder, type );
  2582. return output;
  2583. };
  2584. if ( Array.isArray( parameters ) ) {
  2585. for ( let i = 0; i < parameters.length; i ++ ) {
  2586. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2587. }
  2588. } else {
  2589. for ( const inputNode of inputs ) {
  2590. const node = parameters[ inputNode.name ];
  2591. if ( node !== undefined ) {
  2592. params.push( generateInput( node, inputNode ) );
  2593. } else {
  2594. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2595. }
  2596. }
  2597. }
  2598. const functionName = functionNode.build( builder, 'property' );
  2599. return `${functionName}( ${params.join( ', ' )} )`;
  2600. }
  2601. }
  2602. const call = ( func, ...params ) => {
  2603. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2604. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2605. };
  2606. addMethodChaining( 'call', call );
  2607. class OperatorNode extends TempNode {
  2608. static get type() {
  2609. return 'OperatorNode';
  2610. }
  2611. constructor( op, aNode, bNode, ...params ) {
  2612. super();
  2613. if ( params.length > 0 ) {
  2614. let finalOp = new OperatorNode( op, aNode, bNode );
  2615. for ( let i = 0; i < params.length - 1; i ++ ) {
  2616. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2617. }
  2618. aNode = finalOp;
  2619. bNode = params[ params.length - 1 ];
  2620. }
  2621. this.op = op;
  2622. this.aNode = aNode;
  2623. this.bNode = bNode;
  2624. }
  2625. getNodeType( builder, output ) {
  2626. const op = this.op;
  2627. const aNode = this.aNode;
  2628. const bNode = this.bNode;
  2629. const typeA = aNode.getNodeType( builder );
  2630. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2631. if ( typeA === 'void' || typeB === 'void' ) {
  2632. return 'void';
  2633. } else if ( op === '%' ) {
  2634. return typeA;
  2635. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  2636. return builder.getIntegerType( typeA );
  2637. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  2638. return 'bool';
  2639. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  2640. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  2641. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  2642. } else {
  2643. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  2644. return typeB;
  2645. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2646. // matrix x vector
  2647. return builder.getVectorFromMatrix( typeA );
  2648. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2649. // vector x matrix
  2650. return builder.getVectorFromMatrix( typeB );
  2651. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  2652. // anytype x anytype: use the greater length vector
  2653. return typeB;
  2654. }
  2655. return typeA;
  2656. }
  2657. }
  2658. generate( builder, output ) {
  2659. const op = this.op;
  2660. const aNode = this.aNode;
  2661. const bNode = this.bNode;
  2662. const type = this.getNodeType( builder, output );
  2663. let typeA = null;
  2664. let typeB = null;
  2665. if ( type !== 'void' ) {
  2666. typeA = aNode.getNodeType( builder );
  2667. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2668. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  2669. if ( builder.isVector( typeA ) ) {
  2670. typeB = typeA;
  2671. } else if ( typeA !== typeB ) {
  2672. typeA = typeB = 'float';
  2673. }
  2674. } else if ( op === '>>' || op === '<<' ) {
  2675. typeA = type;
  2676. typeB = builder.changeComponentType( typeB, 'uint' );
  2677. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2678. // matrix x vector
  2679. typeB = builder.getVectorFromMatrix( typeA );
  2680. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2681. // vector x matrix
  2682. typeA = builder.getVectorFromMatrix( typeB );
  2683. } else {
  2684. // anytype x anytype
  2685. typeA = typeB = type;
  2686. }
  2687. } else {
  2688. typeA = typeB = type;
  2689. }
  2690. const a = aNode.build( builder, typeA );
  2691. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  2692. const outputLength = builder.getTypeLength( output );
  2693. const fnOpSnippet = builder.getFunctionOperator( op );
  2694. if ( output !== 'void' ) {
  2695. if ( op === '<' && outputLength > 1 ) {
  2696. if ( builder.useComparisonMethod ) {
  2697. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  2698. } else {
  2699. return builder.format( `( ${ a } < ${ b } )`, type, output );
  2700. }
  2701. } else if ( op === '<=' && outputLength > 1 ) {
  2702. if ( builder.useComparisonMethod ) {
  2703. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2704. } else {
  2705. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  2706. }
  2707. } else if ( op === '>' && outputLength > 1 ) {
  2708. if ( builder.useComparisonMethod ) {
  2709. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  2710. } else {
  2711. return builder.format( `( ${ a } > ${ b } )`, type, output );
  2712. }
  2713. } else if ( op === '>=' && outputLength > 1 ) {
  2714. if ( builder.useComparisonMethod ) {
  2715. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2716. } else {
  2717. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  2718. }
  2719. } else if ( op === '!' || op === '~' ) {
  2720. return builder.format( `(${op}${a})`, typeA, output );
  2721. } else if ( fnOpSnippet ) {
  2722. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2723. } else {
  2724. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  2725. }
  2726. } else if ( typeA !== 'void' ) {
  2727. if ( fnOpSnippet ) {
  2728. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2729. } else {
  2730. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  2731. }
  2732. }
  2733. }
  2734. serialize( data ) {
  2735. super.serialize( data );
  2736. data.op = this.op;
  2737. }
  2738. deserialize( data ) {
  2739. super.deserialize( data );
  2740. this.op = data.op;
  2741. }
  2742. }
  2743. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  2744. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  2745. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  2746. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  2747. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  2748. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  2749. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  2750. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  2751. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  2752. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  2753. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  2754. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  2755. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  2756. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  2757. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  2758. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  2759. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  2760. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  2761. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  2762. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  2763. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  2764. addMethodChaining( 'add', add );
  2765. addMethodChaining( 'sub', sub );
  2766. addMethodChaining( 'mul', mul );
  2767. addMethodChaining( 'div', div );
  2768. addMethodChaining( 'modInt', modInt );
  2769. addMethodChaining( 'equal', equal );
  2770. addMethodChaining( 'notEqual', notEqual );
  2771. addMethodChaining( 'lessThan', lessThan );
  2772. addMethodChaining( 'greaterThan', greaterThan );
  2773. addMethodChaining( 'lessThanEqual', lessThanEqual );
  2774. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  2775. addMethodChaining( 'and', and );
  2776. addMethodChaining( 'or', or );
  2777. addMethodChaining( 'not', not );
  2778. addMethodChaining( 'xor', xor );
  2779. addMethodChaining( 'bitAnd', bitAnd );
  2780. addMethodChaining( 'bitNot', bitNot );
  2781. addMethodChaining( 'bitOr', bitOr );
  2782. addMethodChaining( 'bitXor', bitXor );
  2783. addMethodChaining( 'shiftLeft', shiftLeft );
  2784. addMethodChaining( 'shiftRight', shiftRight );
  2785. const remainder = ( ...params ) => { // @deprecated, r168
  2786. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  2787. return modInt( ...params );
  2788. };
  2789. addMethodChaining( 'remainder', remainder );
  2790. class MathNode extends TempNode {
  2791. static get type() {
  2792. return 'MathNode';
  2793. }
  2794. constructor( method, aNode, bNode = null, cNode = null ) {
  2795. super();
  2796. this.method = method;
  2797. this.aNode = aNode;
  2798. this.bNode = bNode;
  2799. this.cNode = cNode;
  2800. }
  2801. getInputType( builder ) {
  2802. const aType = this.aNode.getNodeType( builder );
  2803. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  2804. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  2805. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  2806. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  2807. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  2808. if ( aLen > bLen && aLen > cLen ) {
  2809. return aType;
  2810. } else if ( bLen > cLen ) {
  2811. return bType;
  2812. } else if ( cLen > aLen ) {
  2813. return cType;
  2814. }
  2815. return aType;
  2816. }
  2817. getNodeType( builder ) {
  2818. const method = this.method;
  2819. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  2820. return 'float';
  2821. } else if ( method === MathNode.CROSS ) {
  2822. return 'vec3';
  2823. } else if ( method === MathNode.ALL ) {
  2824. return 'bool';
  2825. } else if ( method === MathNode.EQUALS ) {
  2826. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  2827. } else if ( method === MathNode.MOD ) {
  2828. return this.aNode.getNodeType( builder );
  2829. } else {
  2830. return this.getInputType( builder );
  2831. }
  2832. }
  2833. generate( builder, output ) {
  2834. const method = this.method;
  2835. const type = this.getNodeType( builder );
  2836. const inputType = this.getInputType( builder );
  2837. const a = this.aNode;
  2838. const b = this.bNode;
  2839. const c = this.cNode;
  2840. const isWebGL = builder.renderer.isWebGLRenderer === true;
  2841. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  2842. // dir can be either a direction vector or a normal vector
  2843. // upper-left 3x3 of matrix is assumed to be orthogonal
  2844. let tA = a;
  2845. let tB = b;
  2846. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  2847. tB = vec4( vec3( tB ), 0.0 );
  2848. } else {
  2849. tA = vec4( vec3( tA ), 0.0 );
  2850. }
  2851. const mulNode = mul( tA, tB ).xyz;
  2852. return normalize( mulNode ).build( builder, output );
  2853. } else if ( method === MathNode.NEGATE ) {
  2854. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  2855. } else if ( method === MathNode.ONE_MINUS ) {
  2856. return sub( 1.0, a ).build( builder, output );
  2857. } else if ( method === MathNode.RECIPROCAL ) {
  2858. return div( 1.0, a ).build( builder, output );
  2859. } else if ( method === MathNode.DIFFERENCE ) {
  2860. return abs( sub( a, b ) ).build( builder, output );
  2861. } else {
  2862. const params = [];
  2863. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  2864. params.push(
  2865. a.build( builder, type ),
  2866. b.build( builder, type )
  2867. );
  2868. } else if ( isWebGL && method === MathNode.STEP ) {
  2869. params.push(
  2870. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  2871. b.build( builder, inputType )
  2872. );
  2873. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  2874. params.push(
  2875. a.build( builder, inputType ),
  2876. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2877. );
  2878. } else if ( method === MathNode.REFRACT ) {
  2879. params.push(
  2880. a.build( builder, inputType ),
  2881. b.build( builder, inputType ),
  2882. c.build( builder, 'float' )
  2883. );
  2884. } else if ( method === MathNode.MIX ) {
  2885. params.push(
  2886. a.build( builder, inputType ),
  2887. b.build( builder, inputType ),
  2888. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2889. );
  2890. } else {
  2891. params.push( a.build( builder, inputType ) );
  2892. if ( b !== null ) params.push( b.build( builder, inputType ) );
  2893. if ( c !== null ) params.push( c.build( builder, inputType ) );
  2894. }
  2895. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  2896. }
  2897. }
  2898. serialize( data ) {
  2899. super.serialize( data );
  2900. data.method = this.method;
  2901. }
  2902. deserialize( data ) {
  2903. super.deserialize( data );
  2904. this.method = data.method;
  2905. }
  2906. }
  2907. // 1 input
  2908. MathNode.ALL = 'all';
  2909. MathNode.ANY = 'any';
  2910. MathNode.EQUALS = 'equals';
  2911. MathNode.RADIANS = 'radians';
  2912. MathNode.DEGREES = 'degrees';
  2913. MathNode.EXP = 'exp';
  2914. MathNode.EXP2 = 'exp2';
  2915. MathNode.LOG = 'log';
  2916. MathNode.LOG2 = 'log2';
  2917. MathNode.SQRT = 'sqrt';
  2918. MathNode.INVERSE_SQRT = 'inversesqrt';
  2919. MathNode.FLOOR = 'floor';
  2920. MathNode.CEIL = 'ceil';
  2921. MathNode.NORMALIZE = 'normalize';
  2922. MathNode.FRACT = 'fract';
  2923. MathNode.SIN = 'sin';
  2924. MathNode.COS = 'cos';
  2925. MathNode.TAN = 'tan';
  2926. MathNode.ASIN = 'asin';
  2927. MathNode.ACOS = 'acos';
  2928. MathNode.ATAN = 'atan';
  2929. MathNode.ABS = 'abs';
  2930. MathNode.SIGN = 'sign';
  2931. MathNode.LENGTH = 'length';
  2932. MathNode.NEGATE = 'negate';
  2933. MathNode.ONE_MINUS = 'oneMinus';
  2934. MathNode.DFDX = 'dFdx';
  2935. MathNode.DFDY = 'dFdy';
  2936. MathNode.ROUND = 'round';
  2937. MathNode.RECIPROCAL = 'reciprocal';
  2938. MathNode.TRUNC = 'trunc';
  2939. MathNode.FWIDTH = 'fwidth';
  2940. MathNode.BITCAST = 'bitcast';
  2941. MathNode.TRANSPOSE = 'transpose';
  2942. // 2 inputs
  2943. MathNode.ATAN2 = 'atan2';
  2944. MathNode.MIN = 'min';
  2945. MathNode.MAX = 'max';
  2946. MathNode.MOD = 'mod';
  2947. MathNode.STEP = 'step';
  2948. MathNode.REFLECT = 'reflect';
  2949. MathNode.DISTANCE = 'distance';
  2950. MathNode.DIFFERENCE = 'difference';
  2951. MathNode.DOT = 'dot';
  2952. MathNode.CROSS = 'cross';
  2953. MathNode.POW = 'pow';
  2954. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  2955. // 3 inputs
  2956. MathNode.MIX = 'mix';
  2957. MathNode.CLAMP = 'clamp';
  2958. MathNode.REFRACT = 'refract';
  2959. MathNode.SMOOTHSTEP = 'smoothstep';
  2960. MathNode.FACEFORWARD = 'faceforward';
  2961. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  2962. const INFINITY = /*@__PURE__*/ float( 1e6 );
  2963. const PI = /*@__PURE__*/ float( Math.PI );
  2964. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  2965. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  2966. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  2967. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  2968. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  2969. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  2970. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  2971. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2972. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2973. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2974. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2975. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2976. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2977. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2978. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2979. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2980. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2981. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2982. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2983. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2984. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2985. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2986. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2987. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2988. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2989. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2990. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2991. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2992. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2993. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2994. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2995. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2996. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2997. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2998. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2999. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  3000. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3001. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3002. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3003. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3004. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3005. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3006. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3007. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3008. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3009. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3010. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  3011. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  3012. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  3013. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  3014. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  3015. const lengthSq = ( a ) => dot( a, a );
  3016. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  3017. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  3018. const saturate = ( value ) => clamp( value );
  3019. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  3020. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  3021. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  3022. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  3023. const a = 12.9898, b = 78.233, c = 43758.5453;
  3024. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  3025. return fract( sin( sn ).mul( c ) );
  3026. } );
  3027. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  3028. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  3029. addMethodChaining( 'all', all );
  3030. addMethodChaining( 'any', any );
  3031. addMethodChaining( 'equals', equals );
  3032. addMethodChaining( 'radians', radians );
  3033. addMethodChaining( 'degrees', degrees );
  3034. addMethodChaining( 'exp', exp );
  3035. addMethodChaining( 'exp2', exp2 );
  3036. addMethodChaining( 'log', log );
  3037. addMethodChaining( 'log2', log2 );
  3038. addMethodChaining( 'sqrt', sqrt );
  3039. addMethodChaining( 'inverseSqrt', inverseSqrt );
  3040. addMethodChaining( 'floor', floor );
  3041. addMethodChaining( 'ceil', ceil );
  3042. addMethodChaining( 'normalize', normalize );
  3043. addMethodChaining( 'fract', fract );
  3044. addMethodChaining( 'sin', sin );
  3045. addMethodChaining( 'cos', cos );
  3046. addMethodChaining( 'tan', tan );
  3047. addMethodChaining( 'asin', asin );
  3048. addMethodChaining( 'acos', acos );
  3049. addMethodChaining( 'atan', atan );
  3050. addMethodChaining( 'abs', abs );
  3051. addMethodChaining( 'sign', sign );
  3052. addMethodChaining( 'length', length );
  3053. addMethodChaining( 'lengthSq', lengthSq );
  3054. addMethodChaining( 'negate', negate );
  3055. addMethodChaining( 'oneMinus', oneMinus );
  3056. addMethodChaining( 'dFdx', dFdx );
  3057. addMethodChaining( 'dFdy', dFdy );
  3058. addMethodChaining( 'round', round );
  3059. addMethodChaining( 'reciprocal', reciprocal );
  3060. addMethodChaining( 'trunc', trunc );
  3061. addMethodChaining( 'fwidth', fwidth );
  3062. addMethodChaining( 'atan2', atan2 );
  3063. addMethodChaining( 'min', min$1 );
  3064. addMethodChaining( 'max', max$1 );
  3065. addMethodChaining( 'mod', mod );
  3066. addMethodChaining( 'step', step );
  3067. addMethodChaining( 'reflect', reflect );
  3068. addMethodChaining( 'distance', distance );
  3069. addMethodChaining( 'dot', dot );
  3070. addMethodChaining( 'cross', cross );
  3071. addMethodChaining( 'pow', pow );
  3072. addMethodChaining( 'pow2', pow2 );
  3073. addMethodChaining( 'pow3', pow3 );
  3074. addMethodChaining( 'pow4', pow4 );
  3075. addMethodChaining( 'transformDirection', transformDirection );
  3076. addMethodChaining( 'mix', mixElement );
  3077. addMethodChaining( 'clamp', clamp );
  3078. addMethodChaining( 'refract', refract );
  3079. addMethodChaining( 'smoothstep', smoothstepElement );
  3080. addMethodChaining( 'faceForward', faceForward );
  3081. addMethodChaining( 'difference', difference );
  3082. addMethodChaining( 'saturate', saturate );
  3083. addMethodChaining( 'cbrt', cbrt );
  3084. addMethodChaining( 'transpose', transpose );
  3085. addMethodChaining( 'rand', rand );
  3086. class ConditionalNode extends Node {
  3087. static get type() {
  3088. return 'ConditionalNode';
  3089. }
  3090. constructor( condNode, ifNode, elseNode = null ) {
  3091. super();
  3092. this.condNode = condNode;
  3093. this.ifNode = ifNode;
  3094. this.elseNode = elseNode;
  3095. }
  3096. getNodeType( builder ) {
  3097. const ifType = this.ifNode.getNodeType( builder );
  3098. if ( this.elseNode !== null ) {
  3099. const elseType = this.elseNode.getNodeType( builder );
  3100. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  3101. return elseType;
  3102. }
  3103. }
  3104. return ifType;
  3105. }
  3106. setup( builder ) {
  3107. const condNode = this.condNode.cache();
  3108. const ifNode = this.ifNode.cache();
  3109. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  3110. //
  3111. const currentNodeBlock = builder.context.nodeBlock;
  3112. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  3113. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  3114. //
  3115. const properties = builder.getNodeProperties( this );
  3116. properties.condNode = condNode;
  3117. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  3118. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  3119. }
  3120. generate( builder, output ) {
  3121. const type = this.getNodeType( builder );
  3122. const nodeData = builder.getDataFromNode( this );
  3123. if ( nodeData.nodeProperty !== undefined ) {
  3124. return nodeData.nodeProperty;
  3125. }
  3126. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  3127. const needsOutput = output !== 'void';
  3128. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  3129. nodeData.nodeProperty = nodeProperty;
  3130. const nodeSnippet = condNode.build( builder, 'bool' );
  3131. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  3132. let ifSnippet = ifNode.build( builder, type );
  3133. if ( ifSnippet ) {
  3134. if ( needsOutput ) {
  3135. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  3136. } else {
  3137. ifSnippet = 'return ' + ifSnippet + ';';
  3138. }
  3139. }
  3140. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  3141. if ( elseNode !== null ) {
  3142. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  3143. let elseSnippet = elseNode.build( builder, type );
  3144. if ( elseSnippet ) {
  3145. if ( needsOutput ) {
  3146. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  3147. } else {
  3148. elseSnippet = 'return ' + elseSnippet + ';';
  3149. }
  3150. }
  3151. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  3152. } else {
  3153. builder.addFlowCode( '\n\n' );
  3154. }
  3155. return builder.format( nodeProperty, type, output );
  3156. }
  3157. }
  3158. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  3159. addMethodChaining( 'select', select );
  3160. //
  3161. const cond = ( ...params ) => { // @deprecated, r168
  3162. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  3163. return select( ...params );
  3164. };
  3165. addMethodChaining( 'cond', cond );
  3166. /**
  3167. * This node can be used as a context management component for another node.
  3168. * {@link NodeBuilder} performs its node building process in a specific context and
  3169. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  3170. *
  3171. * ```js
  3172. *node.context( { getUV: () => customCoord } );
  3173. *```
  3174. * @augments Node
  3175. */
  3176. class ContextNode extends Node {
  3177. static get type() {
  3178. return 'ContextNode';
  3179. }
  3180. /**
  3181. * Constructs a new context node.
  3182. *
  3183. * @param {Node} node - The node whose context should be modified.
  3184. * @param {Object} [value={}] - The modified context data.
  3185. */
  3186. constructor( node, value = {} ) {
  3187. super();
  3188. /**
  3189. * This flag can be used for type testing.
  3190. *
  3191. * @type {Boolean}
  3192. * @readonly
  3193. * @default true
  3194. */
  3195. this.isContextNode = true;
  3196. /**
  3197. * The node whose context should be modified.
  3198. *
  3199. * @type {Node}
  3200. */
  3201. this.node = node;
  3202. /**
  3203. * The modified context data.
  3204. *
  3205. * @type {Object}
  3206. * @default {}
  3207. */
  3208. this.value = value;
  3209. }
  3210. /**
  3211. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  3212. *
  3213. * @return {Node} A reference to {@link ContextNode#node}.
  3214. */
  3215. getScope() {
  3216. return this.node.getScope();
  3217. }
  3218. /**
  3219. * This method is overwritten to ensure it returns the type to {@link ContextNode#node}.
  3220. *
  3221. * @param {NodeBuilder} builder - The current node builder.
  3222. * @return {String} The type of {@link ContextNode#node}.
  3223. */
  3224. getNodeType( builder ) {
  3225. return this.node.getNodeType( builder );
  3226. }
  3227. analyze( builder ) {
  3228. this.node.build( builder );
  3229. }
  3230. setup( builder ) {
  3231. const previousContext = builder.getContext();
  3232. builder.setContext( { ...builder.context, ...this.value } );
  3233. const node = this.node.build( builder );
  3234. builder.setContext( previousContext );
  3235. return node;
  3236. }
  3237. generate( builder, output ) {
  3238. const previousContext = builder.getContext();
  3239. builder.setContext( { ...builder.context, ...this.value } );
  3240. const snippet = this.node.build( builder, output );
  3241. builder.setContext( previousContext );
  3242. return snippet;
  3243. }
  3244. }
  3245. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  3246. const label = ( node, name ) => context( node, { label: name } );
  3247. addMethodChaining( 'context', context );
  3248. addMethodChaining( 'label', label );
  3249. /**
  3250. * Class for representing shader variables as nodes. Variables are created from
  3251. * existing nodes like the following:
  3252. *
  3253. * ```js
  3254. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  3255. * ```
  3256. *
  3257. * @augments Node
  3258. */
  3259. class VarNode extends Node {
  3260. static get type() {
  3261. return 'VarNode';
  3262. }
  3263. /**
  3264. * Constructs a new variable node.
  3265. *
  3266. * @param {Node} node - The node for which a variable should be created.
  3267. * @param {String?} name - The name of the variable in the shader.
  3268. */
  3269. constructor( node, name = null ) {
  3270. super();
  3271. /**
  3272. * The node for which a variable should be created.
  3273. *
  3274. * @type {Node}
  3275. */
  3276. this.node = node;
  3277. /**
  3278. * The name of the variable in the shader. If no name is defined,
  3279. * the node system auto-generates one.
  3280. *
  3281. * @type {String?}
  3282. * @default null
  3283. */
  3284. this.name = name;
  3285. /**
  3286. * `VarNode` sets this property to `true` by default.
  3287. *
  3288. * @type {Boolean}
  3289. * @default true
  3290. */
  3291. this.global = true;
  3292. /**
  3293. * This flag can be used for type testing.
  3294. *
  3295. * @type {Boolean}
  3296. * @readonly
  3297. * @default true
  3298. */
  3299. this.isVarNode = true;
  3300. }
  3301. getHash( builder ) {
  3302. return this.name || super.getHash( builder );
  3303. }
  3304. getNodeType( builder ) {
  3305. return this.node.getNodeType( builder );
  3306. }
  3307. generate( builder ) {
  3308. const { node, name } = this;
  3309. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  3310. const propertyName = builder.getPropertyName( nodeVar );
  3311. const snippet = node.build( builder, nodeVar.type );
  3312. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3313. return propertyName;
  3314. }
  3315. }
  3316. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  3317. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  3318. // Deprecated
  3319. const temp = ( node ) => { // @deprecated, r170
  3320. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  3321. return createVar( node );
  3322. };
  3323. addMethodChaining( 'temp', temp );
  3324. /**
  3325. * Class for representing shader varyings as nodes. Varyings are create from
  3326. * existing nodes like the following:
  3327. *
  3328. * ```js
  3329. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  3330. * ```
  3331. *
  3332. * @augments Node
  3333. */
  3334. class VaryingNode extends Node {
  3335. static get type() {
  3336. return 'VaryingNode';
  3337. }
  3338. /**
  3339. * Constructs a new varying node.
  3340. *
  3341. * @param {Node} node - The node for which a varying should be created.
  3342. * @param {String?} name - The name of the varying in the shader.
  3343. */
  3344. constructor( node, name = null ) {
  3345. super();
  3346. /**
  3347. * The node for which a varying should be created.
  3348. *
  3349. * @type {Node}
  3350. */
  3351. this.node = node;
  3352. /**
  3353. * The name of the varying in the shader. If no name is defined,
  3354. * the node system auto-generates one.
  3355. *
  3356. * @type {String?}
  3357. * @default null
  3358. */
  3359. this.name = name;
  3360. /**
  3361. * This flag can be used for type testing.
  3362. *
  3363. * @type {Boolean}
  3364. * @readonly
  3365. * @default true
  3366. */
  3367. this.isVaryingNode = true;
  3368. }
  3369. /**
  3370. * The method is overwritten so it always returns `true`.
  3371. *
  3372. * @param {NodeBuilder} builder - The current node builder.
  3373. * @return {Boolean} Whether this node is global or not.
  3374. */
  3375. isGlobal( /*builder*/ ) {
  3376. return true;
  3377. }
  3378. getHash( builder ) {
  3379. return this.name || super.getHash( builder );
  3380. }
  3381. getNodeType( builder ) {
  3382. // VaryingNode is auto type
  3383. return this.node.getNodeType( builder );
  3384. }
  3385. /**
  3386. * This method performs the setup of a varying node with the current node builder.
  3387. *
  3388. * @param {NodeBuilder} builder - The current node builder.
  3389. * @return {NodeVarying} The node varying from the node builder.
  3390. */
  3391. setupVarying( builder ) {
  3392. const properties = builder.getNodeProperties( this );
  3393. let varying = properties.varying;
  3394. if ( varying === undefined ) {
  3395. const name = this.name;
  3396. const type = this.getNodeType( builder );
  3397. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  3398. properties.node = this.node;
  3399. }
  3400. // this property can be used to check if the varying can be optimized for a variable
  3401. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  3402. return varying;
  3403. }
  3404. setup( builder ) {
  3405. this.setupVarying( builder );
  3406. }
  3407. analyze( builder ) {
  3408. this.setupVarying( builder );
  3409. return this.node.analyze( builder );
  3410. }
  3411. generate( builder ) {
  3412. const properties = builder.getNodeProperties( this );
  3413. const varying = this.setupVarying( builder );
  3414. if ( properties.propertyName === undefined ) {
  3415. const type = this.getNodeType( builder );
  3416. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  3417. // force node run in vertex stage
  3418. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  3419. properties.propertyName = propertyName;
  3420. }
  3421. return builder.getPropertyName( varying );
  3422. }
  3423. }
  3424. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  3425. addMethodChaining( 'varying', varying );
  3426. /** @module ColorSpaceFunctions **/
  3427. /**
  3428. * Converts the given color value from sRGB to linear-sRGB color space.
  3429. *
  3430. * @method
  3431. * @param {vec3} color - The sRGB color.
  3432. * @return {vec3} The linear-sRGB color.
  3433. */
  3434. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3435. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  3436. const b = color.mul( 0.0773993808 );
  3437. const factor = color.lessThanEqual( 0.04045 );
  3438. const rgbResult = mix( a, b, factor );
  3439. return rgbResult;
  3440. } ).setLayout( {
  3441. name: 'sRGBTransferEOTF',
  3442. type: 'vec3',
  3443. inputs: [
  3444. { name: 'color', type: 'vec3' }
  3445. ]
  3446. } );
  3447. /**
  3448. * Converts the given color value from linear-sRGB to sRGB color space.
  3449. *
  3450. * @method
  3451. * @param {vec3} color - The linear-sRGB color.
  3452. * @return {vec3} The sRGB color.
  3453. */
  3454. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3455. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  3456. const b = color.mul( 12.92 );
  3457. const factor = color.lessThanEqual( 0.0031308 );
  3458. const rgbResult = mix( a, b, factor );
  3459. return rgbResult;
  3460. } ).setLayout( {
  3461. name: 'sRGBTransferOETF',
  3462. type: 'vec3',
  3463. inputs: [
  3464. { name: 'color', type: 'vec3' }
  3465. ]
  3466. } );
  3467. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  3468. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  3469. /**
  3470. * This node represents a color space conversion. Meaning it converts
  3471. * a color value from a source to a target color space.
  3472. *
  3473. * @augments TempNode
  3474. */
  3475. class ColorSpaceNode extends TempNode {
  3476. static get type() {
  3477. return 'ColorSpaceNode';
  3478. }
  3479. /**
  3480. * Constructs a new color space node.
  3481. *
  3482. * @param {Node} colorNode - Represents the color to convert.
  3483. * @param {String} source - The source color space.
  3484. * @param {String} target - The target color space.
  3485. */
  3486. constructor( colorNode, source, target ) {
  3487. super( 'vec4' );
  3488. /**
  3489. * Represents the color to convert.
  3490. *
  3491. * @type {Node}
  3492. */
  3493. this.colorNode = colorNode;
  3494. /**
  3495. * The source color space.
  3496. *
  3497. * @type {Node}
  3498. */
  3499. this.source = source;
  3500. /**
  3501. * The target color space.
  3502. *
  3503. * @type {Node}
  3504. */
  3505. this.target = target;
  3506. }
  3507. /**
  3508. * This method resolves the constants `WORKING_COLOR_SPACE` and
  3509. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  3510. * color management and renderer.
  3511. *
  3512. * @param {NodeBuilder} builder - The current node builder.
  3513. * @param {String} colorSpace - The color space to resolve.
  3514. * @return {String} The resolved color space.
  3515. */
  3516. resolveColorSpace( builder, colorSpace ) {
  3517. if ( colorSpace === WORKING_COLOR_SPACE ) {
  3518. return ColorManagement.workingColorSpace;
  3519. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  3520. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  3521. }
  3522. return colorSpace;
  3523. }
  3524. setup( builder ) {
  3525. const { colorNode } = this;
  3526. const source = this.resolveColorSpace( builder, this.source );
  3527. const target = this.resolveColorSpace( builder, this.target );
  3528. let outputNode = colorNode;
  3529. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  3530. return outputNode;
  3531. }
  3532. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  3533. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  3534. }
  3535. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  3536. outputNode = vec4(
  3537. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  3538. outputNode.a
  3539. );
  3540. }
  3541. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  3542. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  3543. }
  3544. return outputNode;
  3545. }
  3546. }
  3547. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  3548. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  3549. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  3550. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  3551. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  3552. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  3553. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  3554. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  3555. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  3556. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  3557. static get type() {
  3558. return 'ReferenceElementNode';
  3559. }
  3560. constructor( referenceNode, indexNode ) {
  3561. super( referenceNode, indexNode );
  3562. this.referenceNode = referenceNode;
  3563. this.isReferenceElementNode = true;
  3564. }
  3565. getNodeType() {
  3566. return this.referenceNode.uniformType;
  3567. }
  3568. generate( builder ) {
  3569. const snippet = super.generate( builder );
  3570. const arrayType = this.referenceNode.getNodeType();
  3571. const elementType = this.getNodeType();
  3572. return builder.format( snippet, arrayType, elementType );
  3573. }
  3574. };
  3575. class ReferenceBaseNode extends Node {
  3576. static get type() {
  3577. return 'ReferenceBaseNode';
  3578. }
  3579. constructor( property, uniformType, object = null, count = null ) {
  3580. super();
  3581. this.property = property;
  3582. this.uniformType = uniformType;
  3583. this.object = object;
  3584. this.count = count;
  3585. this.properties = property.split( '.' );
  3586. this.reference = object;
  3587. this.node = null;
  3588. this.group = null;
  3589. this.updateType = NodeUpdateType.OBJECT;
  3590. }
  3591. setGroup( group ) {
  3592. this.group = group;
  3593. return this;
  3594. }
  3595. element( indexNode ) {
  3596. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  3597. }
  3598. setNodeType( uniformType ) {
  3599. const node = uniform( null, uniformType ).getSelf();
  3600. if ( this.group !== null ) {
  3601. node.setGroup( this.group );
  3602. }
  3603. this.node = node;
  3604. }
  3605. getNodeType( builder ) {
  3606. if ( this.node === null ) {
  3607. this.updateReference( builder );
  3608. this.updateValue();
  3609. }
  3610. return this.node.getNodeType( builder );
  3611. }
  3612. getValueFromReference( object = this.reference ) {
  3613. const { properties } = this;
  3614. let value = object[ properties[ 0 ] ];
  3615. for ( let i = 1; i < properties.length; i ++ ) {
  3616. value = value[ properties[ i ] ];
  3617. }
  3618. return value;
  3619. }
  3620. updateReference( state ) {
  3621. this.reference = this.object !== null ? this.object : state.object;
  3622. return this.reference;
  3623. }
  3624. setup() {
  3625. this.updateValue();
  3626. return this.node;
  3627. }
  3628. update( /*frame*/ ) {
  3629. this.updateValue();
  3630. }
  3631. updateValue() {
  3632. if ( this.node === null ) this.setNodeType( this.uniformType );
  3633. const value = this.getValueFromReference();
  3634. if ( Array.isArray( value ) ) {
  3635. this.node.array = value;
  3636. } else {
  3637. this.node.value = value;
  3638. }
  3639. }
  3640. }
  3641. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  3642. class RendererReferenceNode extends ReferenceBaseNode {
  3643. static get type() {
  3644. return 'RendererReferenceNode';
  3645. }
  3646. constructor( property, inputType, renderer = null ) {
  3647. super( property, inputType, renderer );
  3648. this.renderer = renderer;
  3649. this.setGroup( renderGroup );
  3650. }
  3651. updateReference( state ) {
  3652. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  3653. return this.reference;
  3654. }
  3655. }
  3656. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  3657. /**
  3658. * This node represents a tone mapping operation.
  3659. *
  3660. * @augments TempNode
  3661. */
  3662. class ToneMappingNode extends TempNode {
  3663. static get type() {
  3664. return 'ToneMappingNode';
  3665. }
  3666. /**
  3667. * Constructs a new tone mapping node.
  3668. *
  3669. * @param {Number} toneMapping - The tone mapping type.
  3670. * @param {Node} exposureNode - The tone mapping exposure.
  3671. * @param {Node} [colorNode=null] - The color node to process.
  3672. */
  3673. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  3674. super( 'vec3' );
  3675. /**
  3676. * The tone mapping type.
  3677. *
  3678. * @type {Number}
  3679. */
  3680. this.toneMapping = toneMapping;
  3681. /**
  3682. * The tone mapping exposure.
  3683. *
  3684. * @type {Node}
  3685. * @default null
  3686. */
  3687. this.exposureNode = exposureNode;
  3688. /**
  3689. * Represents the color to process.
  3690. *
  3691. * @type {Node}
  3692. * @default null
  3693. */
  3694. this.colorNode = colorNode;
  3695. }
  3696. /**
  3697. * Overwrites the default `customCacheKey()` implementation by including the tone
  3698. * mapping type into the cache key.
  3699. *
  3700. * @return {Number} The hash.
  3701. */
  3702. customCacheKey() {
  3703. return hash$1( this.toneMapping );
  3704. }
  3705. setup( builder ) {
  3706. const colorNode = this.colorNode || builder.context.color;
  3707. const toneMapping = this.toneMapping;
  3708. if ( toneMapping === NoToneMapping ) return colorNode;
  3709. let outputNode = null;
  3710. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  3711. if ( toneMappingFn !== null ) {
  3712. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  3713. } else {
  3714. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  3715. outputNode = colorNode;
  3716. }
  3717. return outputNode;
  3718. }
  3719. }
  3720. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  3721. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  3722. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  3723. class BufferAttributeNode extends InputNode {
  3724. static get type() {
  3725. return 'BufferAttributeNode';
  3726. }
  3727. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  3728. super( value, bufferType );
  3729. this.isBufferNode = true;
  3730. this.bufferType = bufferType;
  3731. this.bufferStride = bufferStride;
  3732. this.bufferOffset = bufferOffset;
  3733. this.usage = StaticDrawUsage;
  3734. this.instanced = false;
  3735. this.attribute = null;
  3736. this.global = true;
  3737. if ( value && value.isBufferAttribute === true ) {
  3738. this.attribute = value;
  3739. this.usage = value.usage;
  3740. this.instanced = value.isInstancedBufferAttribute;
  3741. }
  3742. }
  3743. getHash( builder ) {
  3744. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  3745. let bufferData = builder.globalCache.getData( this.value );
  3746. if ( bufferData === undefined ) {
  3747. bufferData = {
  3748. node: this
  3749. };
  3750. builder.globalCache.setData( this.value, bufferData );
  3751. }
  3752. return bufferData.node.uuid;
  3753. }
  3754. return this.uuid;
  3755. }
  3756. getNodeType( builder ) {
  3757. if ( this.bufferType === null ) {
  3758. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  3759. }
  3760. return this.bufferType;
  3761. }
  3762. setup( builder ) {
  3763. if ( this.attribute !== null ) return;
  3764. const type = this.getNodeType( builder );
  3765. const array = this.value;
  3766. const itemSize = builder.getTypeLength( type );
  3767. const stride = this.bufferStride || itemSize;
  3768. const offset = this.bufferOffset;
  3769. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  3770. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  3771. buffer.setUsage( this.usage );
  3772. this.attribute = bufferAttribute;
  3773. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  3774. }
  3775. generate( builder ) {
  3776. const nodeType = this.getNodeType( builder );
  3777. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  3778. const propertyName = builder.getPropertyName( nodeAttribute );
  3779. let output = null;
  3780. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  3781. this.name = propertyName;
  3782. output = propertyName;
  3783. } else {
  3784. const nodeVarying = varying( this );
  3785. output = nodeVarying.build( builder, nodeType );
  3786. }
  3787. return output;
  3788. }
  3789. getInputType( /*builder*/ ) {
  3790. return 'bufferAttribute';
  3791. }
  3792. setUsage( value ) {
  3793. this.usage = value;
  3794. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  3795. this.attribute.usage = value;
  3796. }
  3797. return this;
  3798. }
  3799. setInstanced( value ) {
  3800. this.instanced = value;
  3801. return this;
  3802. }
  3803. }
  3804. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  3805. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  3806. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  3807. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  3808. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  3809. class ComputeNode extends Node {
  3810. static get type() {
  3811. return 'ComputeNode';
  3812. }
  3813. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  3814. super( 'void' );
  3815. this.isComputeNode = true;
  3816. this.computeNode = computeNode;
  3817. this.count = count;
  3818. this.workgroupSize = workgroupSize;
  3819. this.dispatchCount = 0;
  3820. this.version = 1;
  3821. this.updateBeforeType = NodeUpdateType.OBJECT;
  3822. this.onInitFunction = null;
  3823. this.updateDispatchCount();
  3824. }
  3825. dispose() {
  3826. this.dispatchEvent( { type: 'dispose' } );
  3827. }
  3828. set needsUpdate( value ) {
  3829. if ( value === true ) this.version ++;
  3830. }
  3831. updateDispatchCount() {
  3832. const { count, workgroupSize } = this;
  3833. let size = workgroupSize[ 0 ];
  3834. for ( let i = 1; i < workgroupSize.length; i ++ )
  3835. size *= workgroupSize[ i ];
  3836. this.dispatchCount = Math.ceil( count / size );
  3837. }
  3838. onInit( callback ) {
  3839. this.onInitFunction = callback;
  3840. return this;
  3841. }
  3842. updateBefore( { renderer } ) {
  3843. renderer.compute( this );
  3844. }
  3845. generate( builder ) {
  3846. const { shaderStage } = builder;
  3847. if ( shaderStage === 'compute' ) {
  3848. const snippet = this.computeNode.build( builder, 'void' );
  3849. if ( snippet !== '' ) {
  3850. builder.addLineFlowCode( snippet, this );
  3851. }
  3852. }
  3853. }
  3854. }
  3855. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  3856. addMethodChaining( 'compute', compute );
  3857. /**
  3858. * This node can be used as a cache management component for another node.
  3859. * Caching is in general used by default in {@link NodeBuilder} but this node
  3860. * allows the usage of a shared parent cache during the build process.
  3861. *
  3862. * @augments Node
  3863. */
  3864. class CacheNode extends Node {
  3865. static get type() {
  3866. return 'CacheNode';
  3867. }
  3868. /**
  3869. * Constructs a new cache node.
  3870. *
  3871. * @param {Node} node - The node that should be cached.
  3872. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  3873. */
  3874. constructor( node, parent = true ) {
  3875. super();
  3876. /**
  3877. * The node that should be cached.
  3878. *
  3879. * @type {Node}
  3880. */
  3881. this.node = node;
  3882. /**
  3883. * Whether this node refers to a shared parent cache or not.
  3884. *
  3885. * @type {Boolean}
  3886. * @default true
  3887. */
  3888. this.parent = parent;
  3889. /**
  3890. * This flag can be used for type testing.
  3891. *
  3892. * @type {Boolean}
  3893. * @readonly
  3894. * @default true
  3895. */
  3896. this.isCacheNode = true;
  3897. }
  3898. getNodeType( builder ) {
  3899. return this.node.getNodeType( builder );
  3900. }
  3901. build( builder, ...params ) {
  3902. const previousCache = builder.getCache();
  3903. const cache = builder.getCacheFromNode( this, this.parent );
  3904. builder.setCache( cache );
  3905. const data = this.node.build( builder, ...params );
  3906. builder.setCache( previousCache );
  3907. return data;
  3908. }
  3909. }
  3910. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  3911. addMethodChaining( 'cache', cache );
  3912. /**
  3913. * The class generates the code of a given node but returns another node in the output.
  3914. * This can be used to call a method or node that does not return a value, i.e.
  3915. * type `void` on an input where returning a value is required. Example:
  3916. *
  3917. * ```js
  3918. * material.colorNode = myColor.bypass( runVoidFn() )
  3919. *```
  3920. *
  3921. * @augments Node
  3922. */
  3923. class BypassNode extends Node {
  3924. static get type() {
  3925. return 'BypassNode';
  3926. }
  3927. /**
  3928. * Constructs a new bypass node.
  3929. *
  3930. * @param {Node} outputNode - The output node.
  3931. * @param {Node} callNode - The call node.
  3932. */
  3933. constructor( outputNode, callNode ) {
  3934. super();
  3935. /**
  3936. * This flag can be used for type testing.
  3937. *
  3938. * @type {Boolean}
  3939. * @readonly
  3940. * @default true
  3941. */
  3942. this.isBypassNode = true;
  3943. /**
  3944. * The output node.
  3945. *
  3946. * @type {Node}
  3947. */
  3948. this.outputNode = outputNode;
  3949. /**
  3950. * The call node.
  3951. *
  3952. * @type {Node}
  3953. */
  3954. this.callNode = callNode;
  3955. }
  3956. getNodeType( builder ) {
  3957. return this.outputNode.getNodeType( builder );
  3958. }
  3959. generate( builder ) {
  3960. const snippet = this.callNode.build( builder, 'void' );
  3961. if ( snippet !== '' ) {
  3962. builder.addLineFlowCode( snippet, this );
  3963. }
  3964. return this.outputNode.build( builder );
  3965. }
  3966. }
  3967. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  3968. addMethodChaining( 'bypass', bypass );
  3969. /**
  3970. * This node allows to remap a node value from one range into another. E.g a value of
  3971. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  3972. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  3973. *
  3974. * @augments Node
  3975. */
  3976. class RemapNode extends Node {
  3977. static get type() {
  3978. return 'RemapNode';
  3979. }
  3980. /**
  3981. * Constructs a new remap node.
  3982. *
  3983. * @param {Node} node - The node that should be remapped.
  3984. * @param {Node} inLowNode - The source or current lower bound of the range.
  3985. * @param {Node} inLowNode - The source or current upper bound of the range.
  3986. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  3987. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  3988. */
  3989. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  3990. super();
  3991. /**
  3992. * The node that should be remapped.
  3993. *
  3994. * @type {Node}
  3995. */
  3996. this.node = node;
  3997. /**
  3998. * The source or current lower bound of the range.
  3999. *
  4000. * @type {Node}
  4001. */
  4002. this.inLowNode = inLowNode;
  4003. /**
  4004. * The source or current upper bound of the range.
  4005. *
  4006. * @type {Node}
  4007. */
  4008. this.inHighNode = inHighNode;
  4009. /**
  4010. * The target lower bound of the range.
  4011. *
  4012. * @type {Node}
  4013. * @default float(0)
  4014. */
  4015. this.outLowNode = outLowNode;
  4016. /**
  4017. * The target upper bound of the range.
  4018. *
  4019. * @type {Node}
  4020. * @default float(1)
  4021. */
  4022. this.outHighNode = outHighNode;
  4023. /**
  4024. * Whether the node value should be clamped before
  4025. * remapping it to the target range.
  4026. *
  4027. * @type {Boolean}
  4028. * @default true
  4029. */
  4030. this.doClamp = true;
  4031. }
  4032. setup() {
  4033. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  4034. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  4035. if ( doClamp === true ) t = t.clamp();
  4036. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  4037. }
  4038. }
  4039. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  4040. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  4041. addMethodChaining( 'remap', remap );
  4042. addMethodChaining( 'remapClamp', remapClamp );
  4043. /**
  4044. * This class can be used to implement basic expressions in shader code.
  4045. * Basic examples for that are `return`, `continue` or `discard` statements.
  4046. *
  4047. * @augments Node
  4048. */
  4049. class ExpressionNode extends Node {
  4050. static get type() {
  4051. return 'ExpressionNode';
  4052. }
  4053. /**
  4054. * Constructs a new expression node.
  4055. *
  4056. * @param {String} [snippet=''] - The native code snippet.
  4057. * @param {String} [includes='void'] - The node type.
  4058. */
  4059. constructor( snippet = '', nodeType = 'void' ) {
  4060. super( nodeType );
  4061. /**
  4062. * The native code snippet.
  4063. *
  4064. * @type {String}
  4065. * @default ''
  4066. */
  4067. this.snippet = snippet;
  4068. }
  4069. generate( builder, output ) {
  4070. const type = this.getNodeType( builder );
  4071. const snippet = this.snippet;
  4072. if ( type === 'void' ) {
  4073. builder.addLineFlowCode( snippet, this );
  4074. } else {
  4075. return builder.format( `( ${ snippet } )`, type, output );
  4076. }
  4077. }
  4078. }
  4079. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  4080. /** @module Discard **/
  4081. /**
  4082. * Represents a `discard` shader operation in TSL.
  4083. *
  4084. * @method
  4085. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  4086. * @return {Node} The `discard` expression.
  4087. */
  4088. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  4089. /**
  4090. * Represents a `return` shader operation in TSL.
  4091. *
  4092. * @method
  4093. * @return {ExpressionNode} The `return` expression.
  4094. */
  4095. const Return = () => expression( 'return' ).append();
  4096. addMethodChaining( 'discard', Discard );
  4097. /**
  4098. * Normally, tone mapping and color conversion happens automatically
  4099. * before outputting pixel too the default (screen) framebuffer. In certain
  4100. * post processing setups this happens to late because certain effects
  4101. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  4102. * to apply tone mapping and color space conversion at an arbitrary point
  4103. * in the effect chain.
  4104. *
  4105. * When applying tone mapping and color space conversion manually with this node,
  4106. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  4107. *
  4108. * ```js
  4109. * const postProcessing = new PostProcessing( renderer );
  4110. * postProcessing.outputColorTransform = false;
  4111. *
  4112. * const scenePass = pass( scene, camera );
  4113. * const outputPass = renderOutput( scenePass );
  4114. *
  4115. * postProcessing.outputNode = outputPass;
  4116. * ```
  4117. *
  4118. * @augments TempNode
  4119. */
  4120. class RenderOutputNode extends TempNode {
  4121. static get type() {
  4122. return 'RenderOutputNode';
  4123. }
  4124. /**
  4125. * Constructs a new render output node.
  4126. *
  4127. * @param {Node} colorNode - The color node to process.
  4128. * @param {String} toneMapping - The tone mapping type.
  4129. * @param {String} outputColorSpace - The output color space.
  4130. */
  4131. constructor( colorNode, toneMapping, outputColorSpace ) {
  4132. super( 'vec4' );
  4133. /**
  4134. * The color node to process.
  4135. *
  4136. * @type {Node}
  4137. */
  4138. this.colorNode = colorNode;
  4139. /**
  4140. * The tone mapping type.
  4141. *
  4142. * @type {Number?}
  4143. */
  4144. this.toneMapping = toneMapping;
  4145. /**
  4146. * The output color space.
  4147. *
  4148. * @type {String?}
  4149. */
  4150. this.outputColorSpace = outputColorSpace;
  4151. /**
  4152. * This flag can be used for type testing.
  4153. *
  4154. * @type {Boolean}
  4155. * @readonly
  4156. * @default true
  4157. */
  4158. this.isRenderOutputNode = true;
  4159. }
  4160. setup( { context } ) {
  4161. let outputNode = this.colorNode || context.color;
  4162. // tone mapping
  4163. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  4164. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  4165. if ( toneMapping !== NoToneMapping ) {
  4166. outputNode = outputNode.toneMapping( toneMapping );
  4167. }
  4168. // working to output color space
  4169. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  4170. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  4171. }
  4172. return outputNode;
  4173. }
  4174. }
  4175. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  4176. addMethodChaining( 'renderOutput', renderOutput );
  4177. // Non-PURE exports list, side-effects are required here.
  4178. // TSL Base Syntax
  4179. function addNodeElement( name/*, nodeElement*/ ) {
  4180. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  4181. }
  4182. /**
  4183. * Base class for representing shader attributes as nodes.
  4184. *
  4185. * @augments Node
  4186. */
  4187. class AttributeNode extends Node {
  4188. static get type() {
  4189. return 'AttributeNode';
  4190. }
  4191. /**
  4192. * Constructs a new attribute node.
  4193. *
  4194. * @param {String} attributeName - The name of the attribute.
  4195. * @param {String?} nodeType - The node type.
  4196. */
  4197. constructor( attributeName, nodeType = null ) {
  4198. super( nodeType );
  4199. /**
  4200. * `AttributeNode` sets this property to `true` by default.
  4201. *
  4202. * @type {Boolean}
  4203. * @default true
  4204. */
  4205. this.global = true;
  4206. this._attributeName = attributeName;
  4207. }
  4208. getHash( builder ) {
  4209. return this.getAttributeName( builder );
  4210. }
  4211. getNodeType( builder ) {
  4212. let nodeType = this.nodeType;
  4213. if ( nodeType === null ) {
  4214. const attributeName = this.getAttributeName( builder );
  4215. if ( builder.hasGeometryAttribute( attributeName ) ) {
  4216. const attribute = builder.geometry.getAttribute( attributeName );
  4217. nodeType = builder.getTypeFromAttribute( attribute );
  4218. } else {
  4219. nodeType = 'float';
  4220. }
  4221. }
  4222. return nodeType;
  4223. }
  4224. /**
  4225. * Sets the attribute name to the given value. The method can be
  4226. * overwritten in derived classes if the final name must be computed
  4227. * analytically.
  4228. *
  4229. * @param {String} attributeName - The name of the attribute.
  4230. * @return {AttributeNode} A reference to this node.
  4231. */
  4232. setAttributeName( attributeName ) {
  4233. this._attributeName = attributeName;
  4234. return this;
  4235. }
  4236. /**
  4237. * Returns the attribute name of this node. The method can be
  4238. * overwritten in derived classes if the final name must be computed
  4239. * analytically.
  4240. *
  4241. * @param {NodeBuilder} builder - The current node builder.
  4242. * @return {String} The attribute name.
  4243. */
  4244. getAttributeName( /*builder*/ ) {
  4245. return this._attributeName;
  4246. }
  4247. generate( builder ) {
  4248. const attributeName = this.getAttributeName( builder );
  4249. const nodeType = this.getNodeType( builder );
  4250. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  4251. if ( geometryAttribute === true ) {
  4252. const attribute = builder.geometry.getAttribute( attributeName );
  4253. const attributeType = builder.getTypeFromAttribute( attribute );
  4254. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  4255. if ( builder.shaderStage === 'vertex' ) {
  4256. return builder.format( nodeAttribute.name, attributeType, nodeType );
  4257. } else {
  4258. const nodeVarying = varying( this );
  4259. return nodeVarying.build( builder, nodeType );
  4260. }
  4261. } else {
  4262. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  4263. return builder.generateConst( nodeType );
  4264. }
  4265. }
  4266. serialize( data ) {
  4267. super.serialize( data );
  4268. data.global = this.global;
  4269. data._attributeName = this._attributeName;
  4270. }
  4271. deserialize( data ) {
  4272. super.deserialize( data );
  4273. this.global = data.global;
  4274. this._attributeName = data._attributeName;
  4275. }
  4276. }
  4277. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  4278. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  4279. class TextureSizeNode extends Node {
  4280. static get type() {
  4281. return 'TextureSizeNode';
  4282. }
  4283. constructor( textureNode, levelNode = null ) {
  4284. super( 'uvec2' );
  4285. this.isTextureSizeNode = true;
  4286. this.textureNode = textureNode;
  4287. this.levelNode = levelNode;
  4288. }
  4289. generate( builder, output ) {
  4290. const textureProperty = this.textureNode.build( builder, 'property' );
  4291. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  4292. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  4293. }
  4294. }
  4295. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  4296. /**
  4297. * A special type of uniform node that computes the
  4298. * maximum mipmap level for a given texture node.
  4299. *
  4300. * ```js
  4301. * const level = maxMipLevel( textureNode );
  4302. * ```
  4303. *
  4304. * @augments UniformNode
  4305. */
  4306. class MaxMipLevelNode extends UniformNode {
  4307. static get type() {
  4308. return 'MaxMipLevelNode';
  4309. }
  4310. /**
  4311. * Constructs a new max mip level node.
  4312. *
  4313. * @param {TextureNode} node - The texture node to compute the max mip level for.
  4314. */
  4315. constructor( textureNode ) {
  4316. super( 0 );
  4317. /**
  4318. * The texture node to compute the max mip level for.
  4319. *
  4320. * @private
  4321. * @type {TextureNode}
  4322. */
  4323. this._textureNode = textureNode;
  4324. /**
  4325. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  4326. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  4327. *
  4328. * @type {String}
  4329. * @default 'frame'
  4330. */
  4331. this.updateType = NodeUpdateType.FRAME;
  4332. }
  4333. /**
  4334. * The texture node to compute the max mip level for.
  4335. *
  4336. * @readonly
  4337. * @type {TextureNode}
  4338. */
  4339. get textureNode() {
  4340. return this._textureNode;
  4341. }
  4342. /**
  4343. * The texture.
  4344. *
  4345. * @readonly
  4346. * @type {Texture}
  4347. */
  4348. get texture() {
  4349. return this._textureNode.value;
  4350. }
  4351. update() {
  4352. const texture = this.texture;
  4353. const images = texture.images;
  4354. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  4355. if ( image && image.width !== undefined ) {
  4356. const { width, height } = image;
  4357. this.value = Math.log2( Math.max( width, height ) );
  4358. }
  4359. }
  4360. }
  4361. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  4362. class TextureNode extends UniformNode {
  4363. static get type() {
  4364. return 'TextureNode';
  4365. }
  4366. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  4367. super( value );
  4368. this.isTextureNode = true;
  4369. this.uvNode = uvNode;
  4370. this.levelNode = levelNode;
  4371. this.biasNode = biasNode;
  4372. this.compareNode = null;
  4373. this.depthNode = null;
  4374. this.gradNode = null;
  4375. this.sampler = true;
  4376. this.updateMatrix = false;
  4377. this.updateType = NodeUpdateType.NONE;
  4378. this.referenceNode = null;
  4379. this._value = value;
  4380. this._matrixUniform = null;
  4381. this.setUpdateMatrix( uvNode === null );
  4382. }
  4383. set value( value ) {
  4384. if ( this.referenceNode ) {
  4385. this.referenceNode.value = value;
  4386. } else {
  4387. this._value = value;
  4388. }
  4389. }
  4390. get value() {
  4391. return this.referenceNode ? this.referenceNode.value : this._value;
  4392. }
  4393. getUniformHash( /*builder*/ ) {
  4394. return this.value.uuid;
  4395. }
  4396. getNodeType( /*builder*/ ) {
  4397. if ( this.value.isDepthTexture === true ) return 'float';
  4398. if ( this.value.type === UnsignedIntType ) {
  4399. return 'uvec4';
  4400. } else if ( this.value.type === IntType ) {
  4401. return 'ivec4';
  4402. }
  4403. return 'vec4';
  4404. }
  4405. getInputType( /*builder*/ ) {
  4406. return 'texture';
  4407. }
  4408. getDefaultUV() {
  4409. return uv( this.value.channel );
  4410. }
  4411. updateReference( /*state*/ ) {
  4412. return this.value;
  4413. }
  4414. getTransformedUV( uvNode ) {
  4415. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  4416. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  4417. }
  4418. setUpdateMatrix( value ) {
  4419. this.updateMatrix = value;
  4420. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  4421. return this;
  4422. }
  4423. setupUV( builder, uvNode ) {
  4424. const texture = this.value;
  4425. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  4426. if ( this.sampler ) {
  4427. uvNode = uvNode.flipY();
  4428. } else {
  4429. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  4430. }
  4431. }
  4432. return uvNode;
  4433. }
  4434. setup( builder ) {
  4435. const properties = builder.getNodeProperties( this );
  4436. properties.referenceNode = this.referenceNode;
  4437. //
  4438. let uvNode = this.uvNode;
  4439. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  4440. uvNode = builder.context.getUV( this );
  4441. }
  4442. if ( ! uvNode ) uvNode = this.getDefaultUV();
  4443. if ( this.updateMatrix === true ) {
  4444. uvNode = this.getTransformedUV( uvNode );
  4445. }
  4446. uvNode = this.setupUV( builder, uvNode );
  4447. //
  4448. let levelNode = this.levelNode;
  4449. if ( levelNode === null && builder.context.getTextureLevel ) {
  4450. levelNode = builder.context.getTextureLevel( this );
  4451. }
  4452. //
  4453. properties.uvNode = uvNode;
  4454. properties.levelNode = levelNode;
  4455. properties.biasNode = this.biasNode;
  4456. properties.compareNode = this.compareNode;
  4457. properties.gradNode = this.gradNode;
  4458. properties.depthNode = this.depthNode;
  4459. }
  4460. generateUV( builder, uvNode ) {
  4461. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  4462. }
  4463. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  4464. const texture = this.value;
  4465. let snippet;
  4466. if ( levelSnippet ) {
  4467. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  4468. } else if ( biasSnippet ) {
  4469. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  4470. } else if ( gradSnippet ) {
  4471. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  4472. } else if ( compareSnippet ) {
  4473. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  4474. } else if ( this.sampler === false ) {
  4475. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  4476. } else {
  4477. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  4478. }
  4479. return snippet;
  4480. }
  4481. generate( builder, output ) {
  4482. const properties = builder.getNodeProperties( this );
  4483. const texture = this.value;
  4484. if ( ! texture || texture.isTexture !== true ) {
  4485. throw new Error( 'TextureNode: Need a three.js texture.' );
  4486. }
  4487. const textureProperty = super.generate( builder, 'property' );
  4488. if ( output === 'sampler' ) {
  4489. return textureProperty + '_sampler';
  4490. } else if ( builder.isReference( output ) ) {
  4491. return textureProperty;
  4492. } else {
  4493. const nodeData = builder.getDataFromNode( this );
  4494. let propertyName = nodeData.propertyName;
  4495. if ( propertyName === undefined ) {
  4496. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  4497. const uvSnippet = this.generateUV( builder, uvNode );
  4498. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  4499. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  4500. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  4501. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  4502. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  4503. const nodeVar = builder.getVarFromNode( this );
  4504. propertyName = builder.getPropertyName( nodeVar );
  4505. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  4506. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  4507. nodeData.snippet = snippet;
  4508. nodeData.propertyName = propertyName;
  4509. }
  4510. let snippet = propertyName;
  4511. const nodeType = this.getNodeType( builder );
  4512. if ( builder.needsToWorkingColorSpace( texture ) ) {
  4513. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  4514. }
  4515. return builder.format( snippet, nodeType, output );
  4516. }
  4517. }
  4518. setSampler( value ) {
  4519. this.sampler = value;
  4520. return this;
  4521. }
  4522. getSampler() {
  4523. return this.sampler;
  4524. }
  4525. // @TODO: Move to TSL
  4526. uv( uvNode ) { // @deprecated, r172
  4527. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  4528. return this.sample( uvNode );
  4529. }
  4530. sample( uvNode ) {
  4531. const textureNode = this.clone();
  4532. textureNode.uvNode = nodeObject( uvNode );
  4533. textureNode.referenceNode = this.getSelf();
  4534. return nodeObject( textureNode );
  4535. }
  4536. blur( amountNode ) {
  4537. const textureNode = this.clone();
  4538. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  4539. textureNode.referenceNode = this.getSelf();
  4540. return nodeObject( textureNode );
  4541. }
  4542. level( levelNode ) {
  4543. const textureNode = this.clone();
  4544. textureNode.levelNode = nodeObject( levelNode );
  4545. textureNode.referenceNode = this.getSelf();
  4546. return nodeObject( textureNode );
  4547. }
  4548. size( levelNode ) {
  4549. return textureSize( this, levelNode );
  4550. }
  4551. bias( biasNode ) {
  4552. const textureNode = this.clone();
  4553. textureNode.biasNode = nodeObject( biasNode );
  4554. textureNode.referenceNode = this.getSelf();
  4555. return nodeObject( textureNode );
  4556. }
  4557. compare( compareNode ) {
  4558. const textureNode = this.clone();
  4559. textureNode.compareNode = nodeObject( compareNode );
  4560. textureNode.referenceNode = this.getSelf();
  4561. return nodeObject( textureNode );
  4562. }
  4563. grad( gradNodeX, gradNodeY ) {
  4564. const textureNode = this.clone();
  4565. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  4566. textureNode.referenceNode = this.getSelf();
  4567. return nodeObject( textureNode );
  4568. }
  4569. depth( depthNode ) {
  4570. const textureNode = this.clone();
  4571. textureNode.depthNode = nodeObject( depthNode );
  4572. textureNode.referenceNode = this.getSelf();
  4573. return nodeObject( textureNode );
  4574. }
  4575. // --
  4576. serialize( data ) {
  4577. super.serialize( data );
  4578. data.value = this.value.toJSON( data.meta ).uuid;
  4579. data.sampler = this.sampler;
  4580. data.updateMatrix = this.updateMatrix;
  4581. data.updateType = this.updateType;
  4582. }
  4583. deserialize( data ) {
  4584. super.deserialize( data );
  4585. this.value = data.meta.textures[ data.value ];
  4586. this.sampler = data.sampler;
  4587. this.updateMatrix = data.updateMatrix;
  4588. this.updateType = data.updateType;
  4589. }
  4590. update() {
  4591. const texture = this.value;
  4592. const matrixUniform = this._matrixUniform;
  4593. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  4594. if ( texture.matrixAutoUpdate === true ) {
  4595. texture.updateMatrix();
  4596. }
  4597. }
  4598. clone() {
  4599. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  4600. newNode.sampler = this.sampler;
  4601. return newNode;
  4602. }
  4603. }
  4604. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  4605. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  4606. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  4607. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  4608. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  4609. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  4610. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  4611. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  4612. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  4613. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  4614. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  4615. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  4616. class Object3DNode extends Node {
  4617. static get type() {
  4618. return 'Object3DNode';
  4619. }
  4620. constructor( scope, object3d = null ) {
  4621. super();
  4622. this.scope = scope;
  4623. this.object3d = object3d;
  4624. this.updateType = NodeUpdateType.OBJECT;
  4625. this._uniformNode = new UniformNode( null );
  4626. }
  4627. getNodeType() {
  4628. const scope = this.scope;
  4629. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4630. return 'mat4';
  4631. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4632. return 'vec3';
  4633. }
  4634. }
  4635. update( frame ) {
  4636. const object = this.object3d;
  4637. const uniformNode = this._uniformNode;
  4638. const scope = this.scope;
  4639. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4640. uniformNode.value = object.matrixWorld;
  4641. } else if ( scope === Object3DNode.POSITION ) {
  4642. uniformNode.value = uniformNode.value || new Vector3();
  4643. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4644. } else if ( scope === Object3DNode.SCALE ) {
  4645. uniformNode.value = uniformNode.value || new Vector3();
  4646. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  4647. } else if ( scope === Object3DNode.DIRECTION ) {
  4648. uniformNode.value = uniformNode.value || new Vector3();
  4649. object.getWorldDirection( uniformNode.value );
  4650. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  4651. const camera = frame.camera;
  4652. uniformNode.value = uniformNode.value || new Vector3();
  4653. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4654. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  4655. }
  4656. }
  4657. generate( builder ) {
  4658. const scope = this.scope;
  4659. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4660. this._uniformNode.nodeType = 'mat4';
  4661. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4662. this._uniformNode.nodeType = 'vec3';
  4663. }
  4664. return this._uniformNode.build( builder );
  4665. }
  4666. serialize( data ) {
  4667. super.serialize( data );
  4668. data.scope = this.scope;
  4669. }
  4670. deserialize( data ) {
  4671. super.deserialize( data );
  4672. this.scope = data.scope;
  4673. }
  4674. }
  4675. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  4676. Object3DNode.POSITION = 'position';
  4677. Object3DNode.SCALE = 'scale';
  4678. Object3DNode.VIEW_POSITION = 'viewPosition';
  4679. Object3DNode.DIRECTION = 'direction';
  4680. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  4681. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  4682. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  4683. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  4684. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  4685. class ModelNode extends Object3DNode {
  4686. static get type() {
  4687. return 'ModelNode';
  4688. }
  4689. constructor( scope ) {
  4690. super( scope );
  4691. }
  4692. update( frame ) {
  4693. this.object3d = frame.object;
  4694. super.update( frame );
  4695. }
  4696. }
  4697. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  4698. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  4699. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  4700. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  4701. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  4702. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  4703. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  4704. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  4705. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4706. builder.context.isHighPrecisionModelViewMatrix = true;
  4707. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  4708. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4709. } );
  4710. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  4711. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4712. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  4713. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  4714. if ( isHighPrecisionModelViewMatrix !== true ) {
  4715. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4716. }
  4717. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  4718. } );
  4719. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  4720. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  4721. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  4722. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  4723. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  4724. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  4725. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  4726. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  4727. /**
  4728. * This node can be used to evaluate whether a primitive is front or back facing.
  4729. *
  4730. * @augments Node
  4731. */
  4732. class FrontFacingNode extends Node {
  4733. static get type() {
  4734. return 'FrontFacingNode';
  4735. }
  4736. /**
  4737. * Constructs a new front facing node.
  4738. */
  4739. constructor() {
  4740. super( 'bool' );
  4741. /**
  4742. * This flag can be used for type testing.
  4743. *
  4744. * @type {Boolean}
  4745. * @readonly
  4746. * @default true
  4747. */
  4748. this.isFrontFacingNode = true;
  4749. }
  4750. generate( builder ) {
  4751. const { renderer, material } = builder;
  4752. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  4753. if ( material.side === BackSide ) {
  4754. return 'false';
  4755. }
  4756. }
  4757. return builder.getFrontFacing();
  4758. }
  4759. }
  4760. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  4761. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  4762. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  4763. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  4764. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  4765. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  4766. return vec3( 0, 1, 0 );
  4767. }
  4768. return normalGeometry;
  4769. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  4770. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  4771. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4772. let node;
  4773. if ( builder.material.flatShading === true ) {
  4774. node = normalFlat;
  4775. } else {
  4776. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  4777. }
  4778. return node;
  4779. }, 'vec3' ).once() )().toVar( 'normalView' );
  4780. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  4781. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4782. return builder.context.setupNormal();
  4783. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  4784. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  4785. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4786. return builder.context.setupClearcoatNormal();
  4787. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  4788. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  4789. const m = mat3( matrix );
  4790. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  4791. return m.mul( transformedNormal ).xyz;
  4792. } );
  4793. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  4794. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  4795. if ( modelNormalViewMatrix !== null ) {
  4796. return modelNormalViewMatrix.transformDirection( normal );
  4797. }
  4798. //
  4799. const transformedNormal = modelNormalMatrix.mul( normal );
  4800. return cameraViewMatrix.transformDirection( transformedNormal );
  4801. } );
  4802. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  4803. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  4804. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  4805. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4806. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4807. class CubeTextureNode extends TextureNode {
  4808. static get type() {
  4809. return 'CubeTextureNode';
  4810. }
  4811. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  4812. super( value, uvNode, levelNode, biasNode );
  4813. this.isCubeTextureNode = true;
  4814. }
  4815. getInputType( /*builder*/ ) {
  4816. return 'cubeTexture';
  4817. }
  4818. getDefaultUV() {
  4819. const texture = this.value;
  4820. if ( texture.mapping === CubeReflectionMapping ) {
  4821. return reflectVector;
  4822. } else if ( texture.mapping === CubeRefractionMapping ) {
  4823. return refractVector;
  4824. } else {
  4825. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  4826. return vec3( 0, 0, 0 );
  4827. }
  4828. }
  4829. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  4830. setupUV( builder, uvNode ) {
  4831. const texture = this.value;
  4832. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  4833. return vec3( uvNode.x.negate(), uvNode.yz );
  4834. } else {
  4835. return uvNode;
  4836. }
  4837. }
  4838. generateUV( builder, cubeUV ) {
  4839. return cubeUV.build( builder, 'vec3' );
  4840. }
  4841. }
  4842. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  4843. class BufferNode extends UniformNode {
  4844. static get type() {
  4845. return 'BufferNode';
  4846. }
  4847. constructor( value, bufferType, bufferCount = 0 ) {
  4848. super( value, bufferType );
  4849. this.isBufferNode = true;
  4850. this.bufferType = bufferType;
  4851. this.bufferCount = bufferCount;
  4852. }
  4853. getElementType( builder ) {
  4854. return this.getNodeType( builder );
  4855. }
  4856. getInputType( /*builder*/ ) {
  4857. return 'buffer';
  4858. }
  4859. }
  4860. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  4861. class UniformArrayElementNode extends ArrayElementNode {
  4862. static get type() {
  4863. return 'UniformArrayElementNode';
  4864. }
  4865. constructor( arrayBuffer, indexNode ) {
  4866. super( arrayBuffer, indexNode );
  4867. this.isArrayBufferElementNode = true;
  4868. }
  4869. generate( builder ) {
  4870. const snippet = super.generate( builder );
  4871. const type = this.getNodeType();
  4872. const paddedType = this.node.getPaddedType();
  4873. return builder.format( snippet, paddedType, type );
  4874. }
  4875. }
  4876. class UniformArrayNode extends BufferNode {
  4877. static get type() {
  4878. return 'UniformArrayNode';
  4879. }
  4880. constructor( value, elementType = null ) {
  4881. super( null );
  4882. this.array = value;
  4883. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  4884. this.paddedType = this.getPaddedType();
  4885. this.updateType = NodeUpdateType.RENDER;
  4886. this.isArrayBufferNode = true;
  4887. }
  4888. getNodeType() {
  4889. return this.paddedType;
  4890. }
  4891. getElementType() {
  4892. return this.elementType;
  4893. }
  4894. getPaddedType() {
  4895. const elementType = this.elementType;
  4896. let paddedType = 'vec4';
  4897. if ( elementType === 'mat2' ) {
  4898. paddedType = 'mat2';
  4899. } else if ( /mat/.test( elementType ) === true ) {
  4900. paddedType = 'mat4';
  4901. } else if ( elementType.charAt( 0 ) === 'i' ) {
  4902. paddedType = 'ivec4';
  4903. } else if ( elementType.charAt( 0 ) === 'u' ) {
  4904. paddedType = 'uvec4';
  4905. }
  4906. return paddedType;
  4907. }
  4908. update( /*frame*/ ) {
  4909. const { array, value } = this;
  4910. const elementType = this.elementType;
  4911. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  4912. for ( let i = 0; i < array.length; i ++ ) {
  4913. const index = i * 4;
  4914. value[ index ] = array[ i ];
  4915. }
  4916. } else if ( elementType === 'color' ) {
  4917. for ( let i = 0; i < array.length; i ++ ) {
  4918. const index = i * 4;
  4919. const vector = array[ i ];
  4920. value[ index ] = vector.r;
  4921. value[ index + 1 ] = vector.g;
  4922. value[ index + 2 ] = vector.b || 0;
  4923. //value[ index + 3 ] = vector.a || 0;
  4924. }
  4925. } else if ( elementType === 'mat2' ) {
  4926. for ( let i = 0; i < array.length; i ++ ) {
  4927. const index = i * 4;
  4928. const matrix = array[ i ];
  4929. value[ index ] = matrix.elements[ 0 ];
  4930. value[ index + 1 ] = matrix.elements[ 1 ];
  4931. value[ index + 2 ] = matrix.elements[ 2 ];
  4932. value[ index + 3 ] = matrix.elements[ 3 ];
  4933. }
  4934. } else if ( elementType === 'mat3' ) {
  4935. for ( let i = 0; i < array.length; i ++ ) {
  4936. const index = i * 16;
  4937. const matrix = array[ i ];
  4938. value[ index ] = matrix.elements[ 0 ];
  4939. value[ index + 1 ] = matrix.elements[ 1 ];
  4940. value[ index + 2 ] = matrix.elements[ 2 ];
  4941. value[ index + 4 ] = matrix.elements[ 3 ];
  4942. value[ index + 5 ] = matrix.elements[ 4 ];
  4943. value[ index + 6 ] = matrix.elements[ 5 ];
  4944. value[ index + 8 ] = matrix.elements[ 6 ];
  4945. value[ index + 9 ] = matrix.elements[ 7 ];
  4946. value[ index + 10 ] = matrix.elements[ 8 ];
  4947. value[ index + 15 ] = 1;
  4948. }
  4949. } else if ( elementType === 'mat4' ) {
  4950. for ( let i = 0; i < array.length; i ++ ) {
  4951. const index = i * 16;
  4952. const matrix = array[ i ];
  4953. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  4954. value[ index + i ] = matrix.elements[ i ];
  4955. }
  4956. }
  4957. } else {
  4958. for ( let i = 0; i < array.length; i ++ ) {
  4959. const index = i * 4;
  4960. const vector = array[ i ];
  4961. value[ index ] = vector.x;
  4962. value[ index + 1 ] = vector.y;
  4963. value[ index + 2 ] = vector.z || 0;
  4964. value[ index + 3 ] = vector.w || 0;
  4965. }
  4966. }
  4967. }
  4968. setup( builder ) {
  4969. const length = this.array.length;
  4970. const elementType = this.elementType;
  4971. let arrayType = Float32Array;
  4972. const paddedType = this.paddedType;
  4973. const paddedElementLength = builder.getTypeLength( paddedType );
  4974. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  4975. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  4976. this.value = new arrayType( length * paddedElementLength );
  4977. this.bufferCount = length;
  4978. this.bufferType = paddedType;
  4979. return super.setup( builder );
  4980. }
  4981. element( indexNode ) {
  4982. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  4983. }
  4984. }
  4985. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  4986. //
  4987. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  4988. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  4989. return nodeObject( new UniformArrayNode( values, nodeType ) );
  4990. };
  4991. class ReferenceElementNode extends ArrayElementNode {
  4992. static get type() {
  4993. return 'ReferenceElementNode';
  4994. }
  4995. constructor( referenceNode, indexNode ) {
  4996. super( referenceNode, indexNode );
  4997. this.referenceNode = referenceNode;
  4998. this.isReferenceElementNode = true;
  4999. }
  5000. getNodeType() {
  5001. return this.referenceNode.uniformType;
  5002. }
  5003. generate( builder ) {
  5004. const snippet = super.generate( builder );
  5005. const arrayType = this.referenceNode.getNodeType();
  5006. const elementType = this.getNodeType();
  5007. return builder.format( snippet, arrayType, elementType );
  5008. }
  5009. }
  5010. // TODO: Extends this from ReferenceBaseNode
  5011. class ReferenceNode extends Node {
  5012. static get type() {
  5013. return 'ReferenceNode';
  5014. }
  5015. constructor( property, uniformType, object = null, count = null ) {
  5016. super();
  5017. this.property = property;
  5018. this.uniformType = uniformType;
  5019. this.object = object;
  5020. this.count = count;
  5021. this.properties = property.split( '.' );
  5022. this.reference = object;
  5023. this.node = null;
  5024. this.group = null;
  5025. this.name = null;
  5026. this.updateType = NodeUpdateType.OBJECT;
  5027. }
  5028. element( indexNode ) {
  5029. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  5030. }
  5031. setGroup( group ) {
  5032. this.group = group;
  5033. return this;
  5034. }
  5035. label( name ) {
  5036. this.name = name;
  5037. return this;
  5038. }
  5039. setNodeType( uniformType ) {
  5040. let node = null;
  5041. if ( this.count !== null ) {
  5042. node = buffer( null, uniformType, this.count );
  5043. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  5044. node = uniformArray( null, uniformType );
  5045. } else if ( uniformType === 'texture' ) {
  5046. node = texture( null );
  5047. } else if ( uniformType === 'cubeTexture' ) {
  5048. node = cubeTexture( null );
  5049. } else {
  5050. node = uniform( null, uniformType );
  5051. }
  5052. if ( this.group !== null ) {
  5053. node.setGroup( this.group );
  5054. }
  5055. if ( this.name !== null ) node.label( this.name );
  5056. this.node = node.getSelf();
  5057. }
  5058. getNodeType( builder ) {
  5059. if ( this.node === null ) {
  5060. this.updateReference( builder );
  5061. this.updateValue();
  5062. }
  5063. return this.node.getNodeType( builder );
  5064. }
  5065. getValueFromReference( object = this.reference ) {
  5066. const { properties } = this;
  5067. let value = object[ properties[ 0 ] ];
  5068. for ( let i = 1; i < properties.length; i ++ ) {
  5069. value = value[ properties[ i ] ];
  5070. }
  5071. return value;
  5072. }
  5073. updateReference( state ) {
  5074. this.reference = this.object !== null ? this.object : state.object;
  5075. return this.reference;
  5076. }
  5077. setup() {
  5078. this.updateValue();
  5079. return this.node;
  5080. }
  5081. update( /*frame*/ ) {
  5082. this.updateValue();
  5083. }
  5084. updateValue() {
  5085. if ( this.node === null ) this.setNodeType( this.uniformType );
  5086. const value = this.getValueFromReference();
  5087. if ( Array.isArray( value ) ) {
  5088. this.node.array = value;
  5089. } else {
  5090. this.node.value = value;
  5091. }
  5092. }
  5093. }
  5094. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  5095. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  5096. class MaterialReferenceNode extends ReferenceNode {
  5097. static get type() {
  5098. return 'MaterialReferenceNode';
  5099. }
  5100. constructor( property, inputType, material = null ) {
  5101. super( property, inputType, material );
  5102. this.material = material;
  5103. //this.updateType = NodeUpdateType.RENDER;
  5104. this.isMaterialReferenceNode = true;
  5105. }
  5106. /*setNodeType( node ) {
  5107. super.setNodeType( node );
  5108. this.node.groupNode = renderGroup;
  5109. }*/
  5110. updateReference( state ) {
  5111. this.reference = this.material !== null ? this.material : state.material;
  5112. return this.reference;
  5113. }
  5114. }
  5115. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  5116. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  5117. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  5118. builder.geometry.computeTangents();
  5119. }
  5120. return attribute( 'tangent', 'vec4' );
  5121. } )();
  5122. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  5123. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  5124. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  5125. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  5126. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  5127. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  5128. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  5129. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  5130. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  5131. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  5132. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  5133. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  5134. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  5135. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  5136. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  5137. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  5138. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  5139. let bentNormal = anisotropyB.cross( positionViewDirection );
  5140. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  5141. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  5142. return bentNormal;
  5143. } )();
  5144. // Normal Mapping Without Precomputed Tangents
  5145. // http://www.thetenthplanet.de/archives/1180
  5146. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  5147. const { eye_pos, surf_norm, mapN, uv } = inputs;
  5148. const q0 = eye_pos.dFdx();
  5149. const q1 = eye_pos.dFdy();
  5150. const st0 = uv.dFdx();
  5151. const st1 = uv.dFdy();
  5152. const N = surf_norm; // normalized
  5153. const q1perp = q1.cross( N );
  5154. const q0perp = N.cross( q0 );
  5155. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  5156. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  5157. const det = T.dot( T ).max( B.dot( B ) );
  5158. const scale = faceDirection.mul( det.inverseSqrt() );
  5159. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  5160. } );
  5161. /**
  5162. * This class can be used for applying normals maps to materials.
  5163. *
  5164. * ```js
  5165. * material.normalNode = normalMap( texture( normalTex ) );
  5166. * ```
  5167. *
  5168. * @augments TempNode
  5169. */
  5170. class NormalMapNode extends TempNode {
  5171. static get type() {
  5172. return 'NormalMapNode';
  5173. }
  5174. /**
  5175. * Constructs a new normal map node.
  5176. *
  5177. * @param {Node} textureNode - Represents the normal map data.
  5178. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  5179. */
  5180. constructor( node, scaleNode = null ) {
  5181. super( 'vec3' );
  5182. /**
  5183. * Represents the normal map data.
  5184. *
  5185. * @type {Node}
  5186. */
  5187. this.node = node;
  5188. /**
  5189. * Controls the intensity of the effect.
  5190. *
  5191. * @type {Node?}
  5192. * @default null
  5193. */
  5194. this.scaleNode = scaleNode;
  5195. /**
  5196. * The normal map type.
  5197. *
  5198. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  5199. * @default TangentSpaceNormalMap
  5200. */
  5201. this.normalMapType = TangentSpaceNormalMap;
  5202. }
  5203. setup( builder ) {
  5204. const { normalMapType, scaleNode } = this;
  5205. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  5206. if ( scaleNode !== null ) {
  5207. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  5208. }
  5209. let outputNode = null;
  5210. if ( normalMapType === ObjectSpaceNormalMap ) {
  5211. outputNode = transformNormalToView( normalMap );
  5212. } else if ( normalMapType === TangentSpaceNormalMap ) {
  5213. const tangent = builder.hasGeometryAttribute( 'tangent' );
  5214. if ( tangent === true ) {
  5215. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  5216. } else {
  5217. outputNode = perturbNormal2Arb( {
  5218. eye_pos: positionView,
  5219. surf_norm: normalView,
  5220. mapN: normalMap,
  5221. uv: uv()
  5222. } );
  5223. }
  5224. }
  5225. return outputNode;
  5226. }
  5227. }
  5228. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  5229. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  5230. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  5231. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  5232. // It's used to preserve the same TextureNode instance
  5233. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  5234. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  5235. return vec2(
  5236. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  5237. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  5238. ).mul( bumpScale );
  5239. } );
  5240. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  5241. const perturbNormalArb = Fn( ( inputs ) => {
  5242. const { surf_pos, surf_norm, dHdxy } = inputs;
  5243. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  5244. const vSigmaX = surf_pos.dFdx().normalize();
  5245. const vSigmaY = surf_pos.dFdy().normalize();
  5246. const vN = surf_norm; // normalized
  5247. const R1 = vSigmaY.cross( vN );
  5248. const R2 = vN.cross( vSigmaX );
  5249. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  5250. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  5251. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  5252. } );
  5253. /**
  5254. * This class can be used for applying bump maps to materials.
  5255. *
  5256. * ```js
  5257. * material.normalNode = bumpMap( texture( bumpTex ) );
  5258. * ```
  5259. *
  5260. * @augments TempNode
  5261. */
  5262. class BumpMapNode extends TempNode {
  5263. static get type() {
  5264. return 'BumpMapNode';
  5265. }
  5266. /**
  5267. * Constructs a new bump map node.
  5268. *
  5269. * @param {Node} textureNode - Represents the bump map data.
  5270. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  5271. */
  5272. constructor( textureNode, scaleNode = null ) {
  5273. super( 'vec3' );
  5274. /**
  5275. * Represents the bump map data.
  5276. *
  5277. * @type {Node}
  5278. */
  5279. this.textureNode = textureNode;
  5280. /**
  5281. * Controls the intensity of the bump effect.
  5282. *
  5283. * @type {Node?}
  5284. * @default null
  5285. */
  5286. this.scaleNode = scaleNode;
  5287. }
  5288. setup() {
  5289. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  5290. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  5291. return perturbNormalArb( {
  5292. surf_pos: positionView,
  5293. surf_norm: normalView,
  5294. dHdxy
  5295. } );
  5296. }
  5297. }
  5298. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  5299. const _propertyCache = new Map();
  5300. class MaterialNode extends Node {
  5301. static get type() {
  5302. return 'MaterialNode';
  5303. }
  5304. constructor( scope ) {
  5305. super();
  5306. this.scope = scope;
  5307. }
  5308. getCache( property, type ) {
  5309. let node = _propertyCache.get( property );
  5310. if ( node === undefined ) {
  5311. node = materialReference( property, type );
  5312. _propertyCache.set( property, node );
  5313. }
  5314. return node;
  5315. }
  5316. getFloat( property ) {
  5317. return this.getCache( property, 'float' );
  5318. }
  5319. getColor( property ) {
  5320. return this.getCache( property, 'color' );
  5321. }
  5322. getTexture( property ) {
  5323. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  5324. }
  5325. setup( builder ) {
  5326. const material = builder.context.material;
  5327. const scope = this.scope;
  5328. let node = null;
  5329. if ( scope === MaterialNode.COLOR ) {
  5330. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  5331. if ( material.map && material.map.isTexture === true ) {
  5332. node = colorNode.mul( this.getTexture( 'map' ) );
  5333. } else {
  5334. node = colorNode;
  5335. }
  5336. } else if ( scope === MaterialNode.OPACITY ) {
  5337. const opacityNode = this.getFloat( scope );
  5338. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  5339. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  5340. } else {
  5341. node = opacityNode;
  5342. }
  5343. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  5344. if ( material.specularMap && material.specularMap.isTexture === true ) {
  5345. node = this.getTexture( 'specular' ).r;
  5346. } else {
  5347. node = float( 1 );
  5348. }
  5349. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  5350. const specularIntensity = this.getFloat( scope );
  5351. if ( material.specularMap ) {
  5352. node = specularIntensity.mul( this.getTexture( scope ).a );
  5353. } else {
  5354. node = specularIntensity;
  5355. }
  5356. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  5357. const specularColorNode = this.getColor( scope );
  5358. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  5359. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  5360. } else {
  5361. node = specularColorNode;
  5362. }
  5363. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  5364. const roughnessNode = this.getFloat( scope );
  5365. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  5366. node = roughnessNode.mul( this.getTexture( scope ).g );
  5367. } else {
  5368. node = roughnessNode;
  5369. }
  5370. } else if ( scope === MaterialNode.METALNESS ) {
  5371. const metalnessNode = this.getFloat( scope );
  5372. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  5373. node = metalnessNode.mul( this.getTexture( scope ).b );
  5374. } else {
  5375. node = metalnessNode;
  5376. }
  5377. } else if ( scope === MaterialNode.EMISSIVE ) {
  5378. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  5379. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  5380. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  5381. node = emissiveNode.mul( this.getTexture( scope ) );
  5382. } else {
  5383. node = emissiveNode;
  5384. }
  5385. } else if ( scope === MaterialNode.NORMAL ) {
  5386. if ( material.normalMap ) {
  5387. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  5388. node.normalMapType = material.normalMapType;
  5389. } else if ( material.bumpMap ) {
  5390. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  5391. } else {
  5392. node = normalView;
  5393. }
  5394. } else if ( scope === MaterialNode.CLEARCOAT ) {
  5395. const clearcoatNode = this.getFloat( scope );
  5396. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  5397. node = clearcoatNode.mul( this.getTexture( scope ).r );
  5398. } else {
  5399. node = clearcoatNode;
  5400. }
  5401. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  5402. const clearcoatRoughnessNode = this.getFloat( scope );
  5403. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  5404. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  5405. } else {
  5406. node = clearcoatRoughnessNode;
  5407. }
  5408. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  5409. if ( material.clearcoatNormalMap ) {
  5410. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  5411. } else {
  5412. node = normalView;
  5413. }
  5414. } else if ( scope === MaterialNode.SHEEN ) {
  5415. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  5416. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  5417. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  5418. } else {
  5419. node = sheenNode;
  5420. }
  5421. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  5422. const sheenRoughnessNode = this.getFloat( scope );
  5423. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  5424. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  5425. } else {
  5426. node = sheenRoughnessNode;
  5427. }
  5428. node = node.clamp( 0.07, 1.0 );
  5429. } else if ( scope === MaterialNode.ANISOTROPY ) {
  5430. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  5431. const anisotropyPolar = this.getTexture( scope );
  5432. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  5433. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  5434. } else {
  5435. node = materialAnisotropyVector;
  5436. }
  5437. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  5438. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  5439. if ( material.iridescenceThicknessMap ) {
  5440. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  5441. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  5442. } else {
  5443. node = iridescenceThicknessMaximum;
  5444. }
  5445. } else if ( scope === MaterialNode.TRANSMISSION ) {
  5446. const transmissionNode = this.getFloat( scope );
  5447. if ( material.transmissionMap ) {
  5448. node = transmissionNode.mul( this.getTexture( scope ).r );
  5449. } else {
  5450. node = transmissionNode;
  5451. }
  5452. } else if ( scope === MaterialNode.THICKNESS ) {
  5453. const thicknessNode = this.getFloat( scope );
  5454. if ( material.thicknessMap ) {
  5455. node = thicknessNode.mul( this.getTexture( scope ).g );
  5456. } else {
  5457. node = thicknessNode;
  5458. }
  5459. } else if ( scope === MaterialNode.IOR ) {
  5460. node = this.getFloat( scope );
  5461. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  5462. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  5463. } else if ( scope === MaterialNode.AO_MAP ) {
  5464. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  5465. } else {
  5466. const outputType = this.getNodeType( builder );
  5467. node = this.getCache( scope, outputType );
  5468. }
  5469. return node;
  5470. }
  5471. }
  5472. MaterialNode.ALPHA_TEST = 'alphaTest';
  5473. MaterialNode.COLOR = 'color';
  5474. MaterialNode.OPACITY = 'opacity';
  5475. MaterialNode.SHININESS = 'shininess';
  5476. MaterialNode.SPECULAR = 'specular';
  5477. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  5478. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  5479. MaterialNode.SPECULAR_COLOR = 'specularColor';
  5480. MaterialNode.REFLECTIVITY = 'reflectivity';
  5481. MaterialNode.ROUGHNESS = 'roughness';
  5482. MaterialNode.METALNESS = 'metalness';
  5483. MaterialNode.NORMAL = 'normal';
  5484. MaterialNode.CLEARCOAT = 'clearcoat';
  5485. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  5486. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  5487. MaterialNode.EMISSIVE = 'emissive';
  5488. MaterialNode.ROTATION = 'rotation';
  5489. MaterialNode.SHEEN = 'sheen';
  5490. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  5491. MaterialNode.ANISOTROPY = 'anisotropy';
  5492. MaterialNode.IRIDESCENCE = 'iridescence';
  5493. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  5494. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  5495. MaterialNode.IOR = 'ior';
  5496. MaterialNode.TRANSMISSION = 'transmission';
  5497. MaterialNode.THICKNESS = 'thickness';
  5498. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  5499. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  5500. MaterialNode.LINE_SCALE = 'scale';
  5501. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  5502. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  5503. MaterialNode.LINE_WIDTH = 'linewidth';
  5504. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  5505. MaterialNode.POINT_WIDTH = 'pointWidth';
  5506. MaterialNode.DISPERSION = 'dispersion';
  5507. MaterialNode.LIGHT_MAP = 'light';
  5508. MaterialNode.AO_MAP = 'ao';
  5509. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  5510. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  5511. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  5512. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  5513. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  5514. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  5515. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  5516. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  5517. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  5518. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  5519. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  5520. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  5521. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  5522. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  5523. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  5524. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  5525. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  5526. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  5527. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  5528. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  5529. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  5530. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  5531. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  5532. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  5533. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  5534. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  5535. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  5536. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  5537. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  5538. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  5539. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  5540. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  5541. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  5542. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  5543. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  5544. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  5545. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  5546. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  5547. return frame.material;
  5548. } ).onRenderUpdate( function ( { material } ) {
  5549. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  5550. } );
  5551. class ModelViewProjectionNode extends TempNode {
  5552. static get type() {
  5553. return 'ModelViewProjectionNode';
  5554. }
  5555. constructor( positionNode = null ) {
  5556. super( 'vec4' );
  5557. this.positionNode = positionNode;
  5558. }
  5559. setup( builder ) {
  5560. if ( builder.shaderStage === 'fragment' ) {
  5561. return varying( builder.context.mvp );
  5562. }
  5563. const position = this.positionNode || positionLocal;
  5564. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  5565. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  5566. }
  5567. }
  5568. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  5569. /**
  5570. * This class represents shader indices of different types. The following predefined node
  5571. * objects cover frequent use cases:
  5572. *
  5573. * - `vertexIndex`: The index of a vertex within a mesh.
  5574. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  5575. * - `drawIndex`: The index of a draw call.
  5576. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  5577. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  5578. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  5579. *
  5580. * @augments Node
  5581. */
  5582. class IndexNode extends Node {
  5583. static get type() {
  5584. return 'IndexNode';
  5585. }
  5586. /**
  5587. * Constructs a new index node.
  5588. *
  5589. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} value - The scope of the index node.
  5590. */
  5591. constructor( scope ) {
  5592. super( 'uint' );
  5593. /**
  5594. * The scope of the index node.
  5595. *
  5596. * @type {String}
  5597. */
  5598. this.scope = scope;
  5599. /**
  5600. * This flag can be used for type testing.
  5601. *
  5602. * @type {Boolean}
  5603. * @readonly
  5604. * @default true
  5605. */
  5606. this.isIndexNode = true;
  5607. }
  5608. generate( builder ) {
  5609. const nodeType = this.getNodeType( builder );
  5610. const scope = this.scope;
  5611. let propertyName;
  5612. if ( scope === IndexNode.VERTEX ) {
  5613. propertyName = builder.getVertexIndex();
  5614. } else if ( scope === IndexNode.INSTANCE ) {
  5615. propertyName = builder.getInstanceIndex();
  5616. } else if ( scope === IndexNode.DRAW ) {
  5617. propertyName = builder.getDrawIndex();
  5618. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  5619. propertyName = builder.getInvocationLocalIndex();
  5620. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  5621. propertyName = builder.getInvocationSubgroupIndex();
  5622. } else if ( scope === IndexNode.SUBGROUP ) {
  5623. propertyName = builder.getSubgroupIndex();
  5624. } else {
  5625. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  5626. }
  5627. let output;
  5628. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5629. output = propertyName;
  5630. } else {
  5631. const nodeVarying = varying( this );
  5632. output = nodeVarying.build( builder, nodeType );
  5633. }
  5634. return output;
  5635. }
  5636. }
  5637. IndexNode.VERTEX = 'vertex';
  5638. IndexNode.INSTANCE = 'instance';
  5639. IndexNode.SUBGROUP = 'subgroup';
  5640. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  5641. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  5642. IndexNode.DRAW = 'draw';
  5643. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  5644. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  5645. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  5646. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  5647. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  5648. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  5649. class InstanceNode extends Node {
  5650. static get type() {
  5651. return 'InstanceNode';
  5652. }
  5653. constructor( count, instanceMatrix, instanceColor ) {
  5654. super( 'void' );
  5655. this.count = count;
  5656. this.instanceMatrix = instanceMatrix;
  5657. this.instanceColor = instanceColor;
  5658. this.instanceMatrixNode = null;
  5659. this.instanceColorNode = null;
  5660. this.updateType = NodeUpdateType.FRAME;
  5661. this.buffer = null;
  5662. this.bufferColor = null;
  5663. }
  5664. setup( builder ) {
  5665. const { count, instanceMatrix, instanceColor } = this;
  5666. let { instanceMatrixNode, instanceColorNode } = this;
  5667. if ( instanceMatrixNode === null ) {
  5668. // 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.
  5669. if ( count <= 1000 ) {
  5670. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  5671. } else {
  5672. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  5673. this.buffer = buffer;
  5674. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5675. const instanceBuffers = [
  5676. // F.Signature -> bufferAttribute( array, type, stride, offset )
  5677. bufferFn( buffer, 'vec4', 16, 0 ),
  5678. bufferFn( buffer, 'vec4', 16, 4 ),
  5679. bufferFn( buffer, 'vec4', 16, 8 ),
  5680. bufferFn( buffer, 'vec4', 16, 12 )
  5681. ];
  5682. instanceMatrixNode = mat4( ...instanceBuffers );
  5683. }
  5684. this.instanceMatrixNode = instanceMatrixNode;
  5685. }
  5686. if ( instanceColor && instanceColorNode === null ) {
  5687. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  5688. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5689. this.bufferColor = buffer;
  5690. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  5691. this.instanceColorNode = instanceColorNode;
  5692. }
  5693. // POSITION
  5694. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  5695. positionLocal.assign( instancePosition );
  5696. // NORMAL
  5697. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5698. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  5699. // ASSIGNS
  5700. normalLocal.assign( instanceNormal );
  5701. }
  5702. // COLOR
  5703. if ( this.instanceColorNode !== null ) {
  5704. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  5705. }
  5706. }
  5707. update( /*frame*/ ) {
  5708. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  5709. this.buffer.version = this.instanceMatrix.version;
  5710. }
  5711. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  5712. this.bufferColor.version = this.instanceColor.version;
  5713. }
  5714. }
  5715. }
  5716. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  5717. class InstancedMeshNode extends InstanceNode {
  5718. static get type() {
  5719. return 'InstancedMeshNode';
  5720. }
  5721. constructor( instanceMesh ) {
  5722. const { count, instanceMatrix, instanceColor } = instanceMesh;
  5723. super( count, instanceMatrix, instanceColor );
  5724. this.instanceMesh = instanceMesh;
  5725. }
  5726. }
  5727. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  5728. class BatchNode extends Node {
  5729. static get type() {
  5730. return 'BatchNode';
  5731. }
  5732. constructor( batchMesh ) {
  5733. super( 'void' );
  5734. this.batchMesh = batchMesh;
  5735. this.batchingIdNode = null;
  5736. }
  5737. setup( builder ) {
  5738. // POSITION
  5739. if ( this.batchingIdNode === null ) {
  5740. if ( builder.getDrawIndex() === null ) {
  5741. this.batchingIdNode = instanceIndex;
  5742. } else {
  5743. this.batchingIdNode = drawIndex;
  5744. }
  5745. }
  5746. const getIndirectIndex = Fn( ( [ id ] ) => {
  5747. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  5748. const x = int( id ).modInt( int( size ) );
  5749. const y = int( id ).div( int( size ) );
  5750. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  5751. } ).setLayout( {
  5752. name: 'getIndirectIndex',
  5753. type: 'uint',
  5754. inputs: [
  5755. { name: 'id', type: 'int' }
  5756. ]
  5757. } );
  5758. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  5759. const matricesTexture = this.batchMesh._matricesTexture;
  5760. const size = textureSize( textureLoad( matricesTexture ), 0 );
  5761. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  5762. const x = j.modInt( size );
  5763. const y = j.div( int( size ) );
  5764. const batchingMatrix = mat4(
  5765. textureLoad( matricesTexture, ivec2( x, y ) ),
  5766. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  5767. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  5768. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  5769. );
  5770. const colorsTexture = this.batchMesh._colorsTexture;
  5771. if ( colorsTexture !== null ) {
  5772. const getBatchingColor = Fn( ( [ id ] ) => {
  5773. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  5774. const j = id;
  5775. const x = j.modInt( size );
  5776. const y = j.div( size );
  5777. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  5778. } ).setLayout( {
  5779. name: 'getBatchingColor',
  5780. type: 'vec3',
  5781. inputs: [
  5782. { name: 'id', type: 'int' }
  5783. ]
  5784. } );
  5785. const color = getBatchingColor( indirectId );
  5786. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  5787. }
  5788. const bm = mat3( batchingMatrix );
  5789. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  5790. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  5791. const batchingNormal = bm.mul( transformedNormal ).xyz;
  5792. normalLocal.assign( batchingNormal );
  5793. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5794. tangentLocal.mulAssign( bm );
  5795. }
  5796. }
  5797. }
  5798. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  5799. const _frameId = new WeakMap();
  5800. class SkinningNode extends Node {
  5801. static get type() {
  5802. return 'SkinningNode';
  5803. }
  5804. constructor( skinnedMesh, useReference = false ) {
  5805. super( 'void' );
  5806. this.skinnedMesh = skinnedMesh;
  5807. this.useReference = useReference;
  5808. this.updateType = NodeUpdateType.OBJECT;
  5809. //
  5810. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  5811. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  5812. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  5813. if ( useReference ) {
  5814. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  5815. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  5816. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5817. } else {
  5818. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  5819. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  5820. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  5821. }
  5822. this.bindMatrixNode = bindMatrixNode;
  5823. this.bindMatrixInverseNode = bindMatrixInverseNode;
  5824. this.boneMatricesNode = boneMatricesNode;
  5825. this.previousBoneMatricesNode = null;
  5826. }
  5827. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  5828. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5829. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5830. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5831. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5832. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5833. // POSITION
  5834. const skinVertex = bindMatrixNode.mul( position );
  5835. const skinned = add(
  5836. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  5837. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  5838. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  5839. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  5840. );
  5841. return bindMatrixInverseNode.mul( skinned ).xyz;
  5842. }
  5843. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  5844. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5845. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5846. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5847. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5848. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5849. // NORMAL
  5850. let skinMatrix = add(
  5851. skinWeightNode.x.mul( boneMatX ),
  5852. skinWeightNode.y.mul( boneMatY ),
  5853. skinWeightNode.z.mul( boneMatZ ),
  5854. skinWeightNode.w.mul( boneMatW )
  5855. );
  5856. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  5857. return skinMatrix.transformDirection( normal ).xyz;
  5858. }
  5859. getPreviousSkinnedPosition( builder ) {
  5860. const skinnedMesh = builder.object;
  5861. if ( this.previousBoneMatricesNode === null ) {
  5862. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  5863. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5864. }
  5865. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  5866. }
  5867. needsPreviousBoneMatrices( builder ) {
  5868. const mrt = builder.renderer.getMRT();
  5869. return mrt && mrt.has( 'velocity' );
  5870. }
  5871. setup( builder ) {
  5872. if ( this.needsPreviousBoneMatrices( builder ) ) {
  5873. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  5874. }
  5875. const skinPosition = this.getSkinnedPosition();
  5876. positionLocal.assign( skinPosition );
  5877. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5878. const skinNormal = this.getSkinnedNormal();
  5879. normalLocal.assign( skinNormal );
  5880. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5881. tangentLocal.assign( skinNormal );
  5882. }
  5883. }
  5884. }
  5885. generate( builder, output ) {
  5886. if ( output !== 'void' ) {
  5887. return positionLocal.build( builder, output );
  5888. }
  5889. }
  5890. update( frame ) {
  5891. const object = this.useReference ? frame.object : this.skinnedMesh;
  5892. const skeleton = object.skeleton;
  5893. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  5894. _frameId.set( skeleton, frame.frameId );
  5895. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  5896. skeleton.update();
  5897. }
  5898. }
  5899. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  5900. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  5901. /**
  5902. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  5903. * ```js
  5904. * Loop( count, ( { i } ) => {
  5905. *
  5906. * } );
  5907. * ```
  5908. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  5909. * ```js
  5910. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  5911. *
  5912. * } );
  5913. *```
  5914. * Nested loops can be definde in a compacted form:
  5915. * ```js
  5916. * Loop( 10, 5, ( { i, j } ) => {
  5917. *
  5918. * } );
  5919. * ```
  5920. * Loops that should run backwards can be defined like so:
  5921. * ```js
  5922. * Loop( { start: 10 }, () => {} );
  5923. * ```
  5924. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  5925. * @augments Node
  5926. */
  5927. class LoopNode extends Node {
  5928. static get type() {
  5929. return 'LoopNode';
  5930. }
  5931. /**
  5932. * Constructs a new loop node.
  5933. *
  5934. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  5935. */
  5936. constructor( params = [] ) {
  5937. super();
  5938. this.params = params;
  5939. }
  5940. /**
  5941. * Returns a loop variable name based on an index. The pattern is
  5942. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  5943. *
  5944. * @param {Number} index - The index.
  5945. * @return {String} The loop variable name.
  5946. */
  5947. getVarName( index ) {
  5948. return String.fromCharCode( 'i'.charCodeAt() + index );
  5949. }
  5950. /**
  5951. * Returns properties about this node.
  5952. *
  5953. * @param {NodeBuilder} builder - The current node builder.
  5954. * @return {Object} The node properties.
  5955. */
  5956. getProperties( builder ) {
  5957. const properties = builder.getNodeProperties( this );
  5958. if ( properties.stackNode !== undefined ) return properties;
  5959. //
  5960. const inputs = {};
  5961. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  5962. const param = this.params[ i ];
  5963. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  5964. const type = ( param.isNode !== true && param.type ) || 'int';
  5965. inputs[ name ] = expression( name, type );
  5966. }
  5967. const stack = builder.addStack(); // TODO: cache() it
  5968. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  5969. properties.stackNode = stack;
  5970. builder.removeStack();
  5971. return properties;
  5972. }
  5973. /**
  5974. * This method is overwritten since the node type is inferred based on the loop configuration.
  5975. *
  5976. * @param {NodeBuilder} builder - The current node builder.
  5977. * @return {String} The node type.
  5978. */
  5979. getNodeType( builder ) {
  5980. const { returnsNode } = this.getProperties( builder );
  5981. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  5982. }
  5983. setup( builder ) {
  5984. // setup properties
  5985. this.getProperties( builder );
  5986. }
  5987. generate( builder ) {
  5988. const properties = this.getProperties( builder );
  5989. const params = this.params;
  5990. const stackNode = properties.stackNode;
  5991. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  5992. const param = params[ i ];
  5993. let start = null, end = null, name = null, type = null, condition = null, update = null;
  5994. if ( param.isNode ) {
  5995. type = 'int';
  5996. name = this.getVarName( i );
  5997. start = '0';
  5998. end = param.build( builder, type );
  5999. condition = '<';
  6000. } else {
  6001. type = param.type || 'int';
  6002. name = param.name || this.getVarName( i );
  6003. start = param.start;
  6004. end = param.end;
  6005. condition = param.condition;
  6006. update = param.update;
  6007. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  6008. else if ( start && start.isNode ) start = start.build( builder, type );
  6009. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  6010. else if ( end && end.isNode ) end = end.build( builder, type );
  6011. if ( start !== undefined && end === undefined ) {
  6012. start = start + ' - 1';
  6013. end = '0';
  6014. condition = '>=';
  6015. } else if ( end !== undefined && start === undefined ) {
  6016. start = '0';
  6017. condition = '<';
  6018. }
  6019. if ( condition === undefined ) {
  6020. if ( Number( start ) > Number( end ) ) {
  6021. condition = '>=';
  6022. } else {
  6023. condition = '<';
  6024. }
  6025. }
  6026. }
  6027. const internalParam = { start, end, condition };
  6028. //
  6029. const startSnippet = internalParam.start;
  6030. const endSnippet = internalParam.end;
  6031. let declarationSnippet = '';
  6032. let conditionalSnippet = '';
  6033. let updateSnippet = '';
  6034. if ( ! update ) {
  6035. if ( type === 'int' || type === 'uint' ) {
  6036. if ( condition.includes( '<' ) ) update = '++';
  6037. else update = '--';
  6038. } else {
  6039. if ( condition.includes( '<' ) ) update = '+= 1.';
  6040. else update = '-= 1.';
  6041. }
  6042. }
  6043. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  6044. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  6045. updateSnippet += name + ' ' + update;
  6046. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  6047. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  6048. }
  6049. const stackSnippet = stackNode.build( builder, 'void' );
  6050. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  6051. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  6052. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  6053. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  6054. }
  6055. builder.addFlowTab();
  6056. return returnsSnippet;
  6057. }
  6058. }
  6059. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  6060. const Continue = () => expression( 'continue' ).append();
  6061. const Break = () => expression( 'break' ).append();
  6062. //
  6063. const loop = ( ...params ) => { // @deprecated, r168
  6064. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  6065. return Loop( ...params );
  6066. };
  6067. const _morphTextures = /*@__PURE__*/ new WeakMap();
  6068. const _morphVec4 = /*@__PURE__*/ new Vector4();
  6069. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  6070. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  6071. const y = texelIndex.div( width );
  6072. const x = texelIndex.sub( y.mul( width ) );
  6073. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  6074. return bufferAttrib.mul( influence );
  6075. } );
  6076. function getEntry( geometry ) {
  6077. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  6078. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  6079. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  6080. // instead of using attributes, the WebGL 2 code path encodes morph targets
  6081. // into an array of data textures. Each layer represents a single morph target.
  6082. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  6083. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  6084. let entry = _morphTextures.get( geometry );
  6085. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  6086. if ( entry !== undefined ) entry.texture.dispose();
  6087. const morphTargets = geometry.morphAttributes.position || [];
  6088. const morphNormals = geometry.morphAttributes.normal || [];
  6089. const morphColors = geometry.morphAttributes.color || [];
  6090. let vertexDataCount = 0;
  6091. if ( hasMorphPosition === true ) vertexDataCount = 1;
  6092. if ( hasMorphNormals === true ) vertexDataCount = 2;
  6093. if ( hasMorphColors === true ) vertexDataCount = 3;
  6094. let width = geometry.attributes.position.count * vertexDataCount;
  6095. let height = 1;
  6096. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  6097. if ( width > maxTextureSize ) {
  6098. height = Math.ceil( width / maxTextureSize );
  6099. width = maxTextureSize;
  6100. }
  6101. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  6102. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  6103. bufferTexture.type = FloatType;
  6104. bufferTexture.needsUpdate = true;
  6105. // fill buffer
  6106. const vertexDataStride = vertexDataCount * 4;
  6107. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  6108. const morphTarget = morphTargets[ i ];
  6109. const morphNormal = morphNormals[ i ];
  6110. const morphColor = morphColors[ i ];
  6111. const offset = width * height * 4 * i;
  6112. for ( let j = 0; j < morphTarget.count; j ++ ) {
  6113. const stride = j * vertexDataStride;
  6114. if ( hasMorphPosition === true ) {
  6115. _morphVec4.fromBufferAttribute( morphTarget, j );
  6116. buffer[ offset + stride + 0 ] = _morphVec4.x;
  6117. buffer[ offset + stride + 1 ] = _morphVec4.y;
  6118. buffer[ offset + stride + 2 ] = _morphVec4.z;
  6119. buffer[ offset + stride + 3 ] = 0;
  6120. }
  6121. if ( hasMorphNormals === true ) {
  6122. _morphVec4.fromBufferAttribute( morphNormal, j );
  6123. buffer[ offset + stride + 4 ] = _morphVec4.x;
  6124. buffer[ offset + stride + 5 ] = _morphVec4.y;
  6125. buffer[ offset + stride + 6 ] = _morphVec4.z;
  6126. buffer[ offset + stride + 7 ] = 0;
  6127. }
  6128. if ( hasMorphColors === true ) {
  6129. _morphVec4.fromBufferAttribute( morphColor, j );
  6130. buffer[ offset + stride + 8 ] = _morphVec4.x;
  6131. buffer[ offset + stride + 9 ] = _morphVec4.y;
  6132. buffer[ offset + stride + 10 ] = _morphVec4.z;
  6133. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  6134. }
  6135. }
  6136. }
  6137. entry = {
  6138. count: morphTargetsCount,
  6139. texture: bufferTexture,
  6140. stride: vertexDataCount,
  6141. size: new Vector2( width, height )
  6142. };
  6143. _morphTextures.set( geometry, entry );
  6144. function disposeTexture() {
  6145. bufferTexture.dispose();
  6146. _morphTextures.delete( geometry );
  6147. geometry.removeEventListener( 'dispose', disposeTexture );
  6148. }
  6149. geometry.addEventListener( 'dispose', disposeTexture );
  6150. }
  6151. return entry;
  6152. }
  6153. class MorphNode extends Node {
  6154. static get type() {
  6155. return 'MorphNode';
  6156. }
  6157. constructor( mesh ) {
  6158. super( 'void' );
  6159. this.mesh = mesh;
  6160. this.morphBaseInfluence = uniform( 1 );
  6161. this.updateType = NodeUpdateType.OBJECT;
  6162. }
  6163. setup( builder ) {
  6164. const { geometry } = builder;
  6165. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  6166. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  6167. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  6168. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  6169. // nodes
  6170. const { texture: bufferMap, stride, size } = getEntry( geometry );
  6171. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  6172. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  6173. const width = int( size.width );
  6174. Loop( morphTargetsCount, ( { i } ) => {
  6175. const influence = float( 0 ).toVar();
  6176. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  6177. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  6178. } else {
  6179. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  6180. }
  6181. if ( hasMorphPosition === true ) {
  6182. positionLocal.addAssign( getMorph( {
  6183. bufferMap,
  6184. influence,
  6185. stride,
  6186. width,
  6187. depth: i,
  6188. offset: int( 0 )
  6189. } ) );
  6190. }
  6191. if ( hasMorphNormals === true ) {
  6192. normalLocal.addAssign( getMorph( {
  6193. bufferMap,
  6194. influence,
  6195. stride,
  6196. width,
  6197. depth: i,
  6198. offset: int( 1 )
  6199. } ) );
  6200. }
  6201. } );
  6202. }
  6203. update() {
  6204. const morphBaseInfluence = this.morphBaseInfluence;
  6205. if ( this.mesh.geometry.morphTargetsRelative ) {
  6206. morphBaseInfluence.value = 1;
  6207. } else {
  6208. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  6209. }
  6210. }
  6211. }
  6212. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  6213. class LightingNode extends Node {
  6214. static get type() {
  6215. return 'LightingNode';
  6216. }
  6217. constructor() {
  6218. super( 'vec3' );
  6219. this.isLightingNode = true;
  6220. }
  6221. generate( /*builder*/ ) {
  6222. console.warn( 'Abstract function.' );
  6223. }
  6224. }
  6225. class AONode extends LightingNode {
  6226. static get type() {
  6227. return 'AONode';
  6228. }
  6229. constructor( aoNode = null ) {
  6230. super();
  6231. this.aoNode = aoNode;
  6232. }
  6233. setup( builder ) {
  6234. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  6235. }
  6236. }
  6237. class LightingContextNode extends ContextNode {
  6238. static get type() {
  6239. return 'LightingContextNode';
  6240. }
  6241. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  6242. super( node );
  6243. this.lightingModel = lightingModel;
  6244. this.backdropNode = backdropNode;
  6245. this.backdropAlphaNode = backdropAlphaNode;
  6246. this._value = null;
  6247. }
  6248. getContext() {
  6249. const { backdropNode, backdropAlphaNode } = this;
  6250. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  6251. directSpecular = vec3().toVar( 'directSpecular' ),
  6252. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  6253. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  6254. const reflectedLight = {
  6255. directDiffuse,
  6256. directSpecular,
  6257. indirectDiffuse,
  6258. indirectSpecular
  6259. };
  6260. const context = {
  6261. radiance: vec3().toVar( 'radiance' ),
  6262. irradiance: vec3().toVar( 'irradiance' ),
  6263. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  6264. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  6265. reflectedLight,
  6266. backdrop: backdropNode,
  6267. backdropAlpha: backdropAlphaNode
  6268. };
  6269. return context;
  6270. }
  6271. setup( builder ) {
  6272. this.value = this._value || ( this._value = this.getContext() );
  6273. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  6274. return super.setup( builder );
  6275. }
  6276. }
  6277. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  6278. class IrradianceNode extends LightingNode {
  6279. static get type() {
  6280. return 'IrradianceNode';
  6281. }
  6282. constructor( node ) {
  6283. super();
  6284. this.node = node;
  6285. }
  6286. setup( builder ) {
  6287. builder.context.irradiance.addAssign( this.node );
  6288. }
  6289. }
  6290. let screenSizeVec, viewportVec;
  6291. /**
  6292. * This node provides a collection of screen related metrics.
  6293. * Depending on {@link ScreenNode#scope}, the nodes can represent
  6294. * resolution or viewport data as well as fragment or uv coordinates.
  6295. *
  6296. * @augments Node
  6297. */
  6298. class ScreenNode extends Node {
  6299. static get type() {
  6300. return 'ScreenNode';
  6301. }
  6302. /**
  6303. * Constructs a new screen node.
  6304. *
  6305. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  6306. */
  6307. constructor( scope ) {
  6308. super();
  6309. /**
  6310. * The node represents different metric depending on which scope is selected.
  6311. *
  6312. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  6313. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  6314. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  6315. * - `ScreenNode.UV`: Normalized screen coordinates.
  6316. *
  6317. * @type {('coordinate'|'viewport'|'size'|'uv')}
  6318. */
  6319. this.scope = scope;
  6320. /**
  6321. * This flag can be used for type testing.
  6322. *
  6323. * @type {Boolean}
  6324. * @readonly
  6325. * @default true
  6326. */
  6327. this.isViewportNode = true;
  6328. }
  6329. /**
  6330. * This method is overwritten since the node type depends on the selected scope.
  6331. *
  6332. * @return {('vec2'|'vec4')} The node type.
  6333. */
  6334. getNodeType() {
  6335. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  6336. else return 'vec2';
  6337. }
  6338. /**
  6339. * This method is overwritten since the node's update type depends on the selected scope.
  6340. *
  6341. * @return {NodeUpdateType} The update type.
  6342. */
  6343. getUpdateType() {
  6344. let updateType = NodeUpdateType.NONE;
  6345. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  6346. updateType = NodeUpdateType.RENDER;
  6347. }
  6348. this.updateType = updateType;
  6349. return updateType;
  6350. }
  6351. /**
  6352. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  6353. * from the current renderer.
  6354. *
  6355. * @param {NodeFrame} frame - A reference to the current node frame.
  6356. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  6357. */
  6358. update( { renderer } ) {
  6359. const renderTarget = renderer.getRenderTarget();
  6360. if ( this.scope === ScreenNode.VIEWPORT ) {
  6361. if ( renderTarget !== null ) {
  6362. viewportVec.copy( renderTarget.viewport );
  6363. } else {
  6364. renderer.getViewport( viewportVec );
  6365. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  6366. }
  6367. } else {
  6368. if ( renderTarget !== null ) {
  6369. screenSizeVec.width = renderTarget.width;
  6370. screenSizeVec.height = renderTarget.height;
  6371. } else {
  6372. renderer.getDrawingBufferSize( screenSizeVec );
  6373. }
  6374. }
  6375. }
  6376. setup( /*builder*/ ) {
  6377. const scope = this.scope;
  6378. let output = null;
  6379. if ( scope === ScreenNode.SIZE ) {
  6380. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  6381. } else if ( scope === ScreenNode.VIEWPORT ) {
  6382. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  6383. } else {
  6384. output = vec2( screenCoordinate.div( screenSize ) );
  6385. }
  6386. return output;
  6387. }
  6388. generate( builder ) {
  6389. if ( this.scope === ScreenNode.COORDINATE ) {
  6390. let coord = builder.getFragCoord();
  6391. if ( builder.isFlipY() ) {
  6392. // follow webgpu standards
  6393. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  6394. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  6395. }
  6396. return coord;
  6397. }
  6398. return super.generate( builder );
  6399. }
  6400. }
  6401. ScreenNode.COORDINATE = 'coordinate';
  6402. ScreenNode.VIEWPORT = 'viewport';
  6403. ScreenNode.SIZE = 'size';
  6404. ScreenNode.UV = 'uv';
  6405. // Screen
  6406. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  6407. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  6408. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  6409. // Viewport
  6410. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  6411. const viewportSize = viewport.zw;
  6412. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  6413. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  6414. // Deprecated
  6415. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  6416. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  6417. return screenSize;
  6418. }, 'vec2' ).once() )();
  6419. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  6420. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  6421. return screenUV;
  6422. }, 'vec2' ).once() )();
  6423. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  6424. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  6425. return screenUV.flipY();
  6426. }, 'vec2' ).once() )();
  6427. const _size$4 = /*@__PURE__*/ new Vector2();
  6428. /**
  6429. * A special type of texture node which represents the data of the current viewport
  6430. * as a texture. The module extracts data from the current bound framebuffer with
  6431. * a copy operation so no extra render pass is required to produce the texture data
  6432. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  6433. * variety of effects like refractive or transmissive materials.
  6434. *
  6435. * @augments TextureNode
  6436. */
  6437. class ViewportTextureNode extends TextureNode {
  6438. static get type() {
  6439. return 'ViewportTextureNode';
  6440. }
  6441. /**
  6442. * Constructs a new viewport texture node.
  6443. *
  6444. * @param {Node} [uvNode=screenUV] - The uv node.
  6445. * @param {Node?} [levelNode=null] - The level node.
  6446. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  6447. */
  6448. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  6449. if ( framebufferTexture === null ) {
  6450. framebufferTexture = new FramebufferTexture();
  6451. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  6452. }
  6453. super( framebufferTexture, uvNode, levelNode );
  6454. /**
  6455. * Whether to generate mipmaps or not.
  6456. *
  6457. * @type {Boolean}
  6458. * @default false
  6459. */
  6460. this.generateMipmaps = false;
  6461. /**
  6462. * This flag can be used for type testing.
  6463. *
  6464. * @type {Boolean}
  6465. * @readonly
  6466. * @default true
  6467. */
  6468. this.isOutputTextureNode = true;
  6469. /**
  6470. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  6471. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  6472. *
  6473. * @type {String}
  6474. * @default 'frame'
  6475. */
  6476. this.updateBeforeType = NodeUpdateType.FRAME;
  6477. }
  6478. updateBefore( frame ) {
  6479. const renderer = frame.renderer;
  6480. renderer.getDrawingBufferSize( _size$4 );
  6481. //
  6482. const framebufferTexture = this.value;
  6483. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  6484. framebufferTexture.image.width = _size$4.width;
  6485. framebufferTexture.image.height = _size$4.height;
  6486. framebufferTexture.needsUpdate = true;
  6487. }
  6488. //
  6489. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  6490. framebufferTexture.generateMipmaps = this.generateMipmaps;
  6491. renderer.copyFramebufferToTexture( framebufferTexture );
  6492. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  6493. }
  6494. clone() {
  6495. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  6496. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  6497. return viewportTextureNode;
  6498. }
  6499. }
  6500. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  6501. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  6502. let sharedDepthbuffer = null;
  6503. /**
  6504. * Represents the depth of the current viewport as a texture. This module
  6505. * can be used in combination with viewport texture to achieve effects
  6506. * that require depth evaluation.
  6507. *
  6508. * @augments ViewportTextureNode
  6509. */
  6510. class ViewportDepthTextureNode extends ViewportTextureNode {
  6511. static get type() {
  6512. return 'ViewportDepthTextureNode';
  6513. }
  6514. /**
  6515. * Constructs a new viewport shared texture node.
  6516. *
  6517. * @param {Node} [uvNode=screenUV] - The uv node.
  6518. * @param {Node?} [levelNode=null] - The level node.
  6519. */
  6520. constructor( uvNode = screenUV, levelNode = null ) {
  6521. if ( sharedDepthbuffer === null ) {
  6522. sharedDepthbuffer = new DepthTexture();
  6523. }
  6524. super( uvNode, levelNode, sharedDepthbuffer );
  6525. }
  6526. }
  6527. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  6528. /**
  6529. * This node offers a collection of features in context of the depth logic in the fragment shader.
  6530. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  6531. * fragment or for depth evaluation purposes.
  6532. *
  6533. * @augments Node
  6534. */
  6535. class ViewportDepthNode extends Node {
  6536. static get type() {
  6537. return 'ViewportDepthNode';
  6538. }
  6539. /**
  6540. * Constructs a new viewport depth node.
  6541. *
  6542. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  6543. * @param {Node?} [valueNode=null] - The value node.
  6544. */
  6545. constructor( scope, valueNode = null ) {
  6546. super( 'float' );
  6547. /**
  6548. * The node behaves differently depending on which scope is selected.
  6549. *
  6550. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  6551. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  6552. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  6553. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  6554. *
  6555. * @type {('depth'|'depthBase'|'linearDepth')}
  6556. */
  6557. this.scope = scope;
  6558. /**
  6559. * Can be used to define a custom depth value.
  6560. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  6561. *
  6562. * @type {Node}
  6563. * @default null
  6564. */
  6565. this.valueNode = valueNode;
  6566. /**
  6567. * This flag can be used for type testing.
  6568. *
  6569. * @type {Boolean}
  6570. * @readonly
  6571. * @default true
  6572. */
  6573. this.isViewportDepthNode = true;
  6574. }
  6575. generate( builder ) {
  6576. const { scope } = this;
  6577. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  6578. return builder.getFragDepth();
  6579. }
  6580. return super.generate( builder );
  6581. }
  6582. setup( { camera } ) {
  6583. const { scope } = this;
  6584. const value = this.valueNode;
  6585. let node = null;
  6586. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  6587. if ( value !== null ) {
  6588. node = depthBase().assign( value );
  6589. }
  6590. } else if ( scope === ViewportDepthNode.DEPTH ) {
  6591. if ( camera.isPerspectiveCamera ) {
  6592. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  6593. } else {
  6594. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6595. }
  6596. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  6597. if ( value !== null ) {
  6598. if ( camera.isPerspectiveCamera ) {
  6599. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  6600. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  6601. } else {
  6602. node = value;
  6603. }
  6604. } else {
  6605. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6606. }
  6607. }
  6608. return node;
  6609. }
  6610. }
  6611. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  6612. ViewportDepthNode.DEPTH = 'depth';
  6613. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  6614. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  6615. // -near maps to 0; -far maps to 1
  6616. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  6617. // maps orthographic depth in [ 0, 1 ] to viewZ
  6618. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  6619. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  6620. // -near maps to 0; -far maps to 1
  6621. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  6622. // maps perspective depth in [ 0, 1 ] to viewZ
  6623. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  6624. // -near maps to 0; -far maps to 1
  6625. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  6626. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  6627. // The final logarithmic depth formula used here is adapted from one described in an
  6628. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  6629. // which was an improvement upon an earlier formula one described in an
  6630. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  6631. // Ulrich's formula is the following:
  6632. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  6633. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  6634. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  6635. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  6636. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  6637. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  6638. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  6639. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  6640. // be used, and ultimately Ulrich's "near plane" version was chosen.
  6641. // Outerra eventually made another improvement to their original "C-constant" variant,
  6642. // but it still does not incorporate the camera near plane (for this version,
  6643. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  6644. // Here we make 4 changes to Ulrich's formula:
  6645. // 1. Clamp the camera near plane so we don't divide by 0.
  6646. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  6647. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  6648. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  6649. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  6650. // so we do the same here, hence the 'viewZ.negate()' call.
  6651. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  6652. near = near.max( 1e-6 ).toVar();
  6653. const numerator = log2( viewZ.negate().div( near ) );
  6654. const denominator = log2( far.div( near ) );
  6655. return numerator.div( denominator );
  6656. };
  6657. // maps logarithmic depth in [ 0, 1 ] to viewZ
  6658. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  6659. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  6660. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  6661. // a negative viewZ).
  6662. const exponent = depth.mul( log( far.div( near ) ) );
  6663. return float( Math.E ).pow( exponent ).mul( near ).negate();
  6664. };
  6665. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  6666. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  6667. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  6668. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  6669. depth.assign = ( value ) => depthBase( value );
  6670. class BuiltinNode extends Node {
  6671. constructor( name ) {
  6672. super( 'float' );
  6673. this.name = name;
  6674. this.isBuiltinNode = true;
  6675. }
  6676. generate( /* builder */ ) {
  6677. return this.name;
  6678. }
  6679. }
  6680. const builtin = nodeProxy( BuiltinNode );
  6681. class ClippingNode extends Node {
  6682. static get type() {
  6683. return 'ClippingNode';
  6684. }
  6685. constructor( scope = ClippingNode.DEFAULT ) {
  6686. super();
  6687. this.scope = scope;
  6688. }
  6689. setup( builder ) {
  6690. super.setup( builder );
  6691. const clippingContext = builder.clippingContext;
  6692. const { intersectionPlanes, unionPlanes } = clippingContext;
  6693. this.hardwareClipping = builder.material.hardwareClipping;
  6694. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  6695. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  6696. } else if ( this.scope === ClippingNode.HARDWARE ) {
  6697. return this.setupHardwareClipping( unionPlanes, builder );
  6698. } else {
  6699. return this.setupDefault( intersectionPlanes, unionPlanes );
  6700. }
  6701. }
  6702. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  6703. return Fn( () => {
  6704. const distanceToPlane = float().toVar( 'distanceToPlane' );
  6705. const distanceGradient = float().toVar( 'distanceToGradient' );
  6706. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  6707. const numUnionPlanes = unionPlanes.length;
  6708. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  6709. const clippingPlanes = uniformArray( unionPlanes );
  6710. Loop( numUnionPlanes, ( { i } ) => {
  6711. const plane = clippingPlanes.element( i );
  6712. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  6713. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  6714. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  6715. } );
  6716. }
  6717. const numIntersectionPlanes = intersectionPlanes.length;
  6718. if ( numIntersectionPlanes > 0 ) {
  6719. const clippingPlanes = uniformArray( intersectionPlanes );
  6720. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  6721. Loop( numIntersectionPlanes, ( { i } ) => {
  6722. const plane = clippingPlanes.element( i );
  6723. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  6724. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  6725. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  6726. } );
  6727. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  6728. }
  6729. diffuseColor.a.mulAssign( clipOpacity );
  6730. diffuseColor.a.equal( 0.0 ).discard();
  6731. } )();
  6732. }
  6733. setupDefault( intersectionPlanes, unionPlanes ) {
  6734. return Fn( () => {
  6735. const numUnionPlanes = unionPlanes.length;
  6736. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  6737. const clippingPlanes = uniformArray( unionPlanes );
  6738. Loop( numUnionPlanes, ( { i } ) => {
  6739. const plane = clippingPlanes.element( i );
  6740. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  6741. } );
  6742. }
  6743. const numIntersectionPlanes = intersectionPlanes.length;
  6744. if ( numIntersectionPlanes > 0 ) {
  6745. const clippingPlanes = uniformArray( intersectionPlanes );
  6746. const clipped = bool( true ).toVar( 'clipped' );
  6747. Loop( numIntersectionPlanes, ( { i } ) => {
  6748. const plane = clippingPlanes.element( i );
  6749. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  6750. } );
  6751. clipped.discard();
  6752. }
  6753. } )();
  6754. }
  6755. setupHardwareClipping( unionPlanes, builder ) {
  6756. const numUnionPlanes = unionPlanes.length;
  6757. builder.enableHardwareClipping( numUnionPlanes );
  6758. return Fn( () => {
  6759. const clippingPlanes = uniformArray( unionPlanes );
  6760. const hw_clip_distances = builtin( builder.getClipDistance() );
  6761. Loop( numUnionPlanes, ( { i } ) => {
  6762. const plane = clippingPlanes.element( i );
  6763. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  6764. hw_clip_distances.element( i ).assign( distance );
  6765. } );
  6766. } )();
  6767. }
  6768. }
  6769. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  6770. ClippingNode.DEFAULT = 'default';
  6771. ClippingNode.HARDWARE = 'hardware';
  6772. const clipping = () => nodeObject( new ClippingNode() );
  6773. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  6774. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  6775. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  6776. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  6777. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  6778. 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 ) ) ) ) ) );
  6779. } );
  6780. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  6781. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  6782. } );
  6783. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  6784. // Find the discretized derivatives of our coordinates
  6785. const maxDeriv = max$1(
  6786. length( dFdx( position.xyz ) ),
  6787. length( dFdy( position.xyz ) )
  6788. );
  6789. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  6790. // Find two nearest log-discretized noise scales
  6791. const pixScales = vec2(
  6792. exp2( floor( log2( pixScale ) ) ),
  6793. exp2( ceil( log2( pixScale ) ) )
  6794. );
  6795. // Compute alpha thresholds at our two noise scales
  6796. const alpha = vec2(
  6797. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  6798. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  6799. );
  6800. // Factor to interpolate lerp with
  6801. const lerpFactor = fract( log2( pixScale ) );
  6802. // Interpolate alpha threshold from noise at two scales
  6803. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  6804. // Pass into CDF to compute uniformly distrib threshold
  6805. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  6806. const cases = vec3(
  6807. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  6808. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  6809. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  6810. // Find our final, uniformly distributed alpha threshold (ατ)
  6811. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  6812. // Avoids ατ == 0. Could also do ατ =1-ατ
  6813. return clamp( threshold, 1.0e-6, 1.0 );
  6814. } ).setLayout( {
  6815. name: 'getAlphaHashThreshold',
  6816. type: 'float',
  6817. inputs: [
  6818. { name: 'position', type: 'vec3' }
  6819. ]
  6820. } );
  6821. class NodeMaterial extends Material {
  6822. static get type() {
  6823. return 'NodeMaterial';
  6824. }
  6825. get type() {
  6826. return this.constructor.type;
  6827. }
  6828. set type( _value ) { /* */ }
  6829. constructor() {
  6830. super();
  6831. this.isNodeMaterial = true;
  6832. this.forceSinglePass = false;
  6833. this.fog = true;
  6834. this.lights = false;
  6835. this.hardwareClipping = false;
  6836. this.lightsNode = null;
  6837. this.envNode = null;
  6838. this.aoNode = null;
  6839. this.colorNode = null;
  6840. this.normalNode = null;
  6841. this.opacityNode = null;
  6842. this.backdropNode = null;
  6843. this.backdropAlphaNode = null;
  6844. this.alphaTestNode = null;
  6845. this.positionNode = null;
  6846. this.geometryNode = null;
  6847. this.depthNode = null;
  6848. this.shadowPositionNode = null;
  6849. this.receivedShadowNode = null;
  6850. this.castShadowNode = null;
  6851. this.outputNode = null;
  6852. this.mrtNode = null;
  6853. this.fragmentNode = null;
  6854. this.vertexNode = null;
  6855. }
  6856. customProgramCacheKey() {
  6857. return this.type + getCacheKey$1( this );
  6858. }
  6859. build( builder ) {
  6860. this.setup( builder );
  6861. }
  6862. setupObserver( builder ) {
  6863. return new NodeMaterialObserver( builder );
  6864. }
  6865. setup( builder ) {
  6866. builder.context.setupNormal = () => this.setupNormal( builder );
  6867. const renderer = builder.renderer;
  6868. const renderTarget = renderer.getRenderTarget();
  6869. // < VERTEX STAGE >
  6870. builder.addStack();
  6871. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  6872. if ( this.geometryNode !== null ) {
  6873. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  6874. }
  6875. builder.addFlow( 'vertex', builder.removeStack() );
  6876. // < FRAGMENT STAGE >
  6877. builder.addStack();
  6878. let resultNode;
  6879. const clippingNode = this.setupClipping( builder );
  6880. if ( this.depthWrite === true ) {
  6881. // only write depth if depth buffer is configured
  6882. if ( renderTarget !== null ) {
  6883. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  6884. } else {
  6885. if ( renderer.depth === true ) this.setupDepth( builder );
  6886. }
  6887. }
  6888. if ( this.fragmentNode === null ) {
  6889. this.setupDiffuseColor( builder );
  6890. this.setupVariants( builder );
  6891. const outgoingLightNode = this.setupLighting( builder );
  6892. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  6893. // force unsigned floats - useful for RenderTargets
  6894. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  6895. resultNode = this.setupOutput( builder, basicOutput );
  6896. // OUTPUT NODE
  6897. output.assign( resultNode );
  6898. //
  6899. if ( this.outputNode !== null ) resultNode = this.outputNode;
  6900. // MRT
  6901. if ( renderTarget !== null ) {
  6902. const mrt = renderer.getMRT();
  6903. const materialMRT = this.mrtNode;
  6904. if ( mrt !== null ) {
  6905. resultNode = mrt;
  6906. if ( materialMRT !== null ) {
  6907. resultNode = mrt.merge( materialMRT );
  6908. }
  6909. } else if ( materialMRT !== null ) {
  6910. resultNode = materialMRT;
  6911. }
  6912. }
  6913. } else {
  6914. let fragmentNode = this.fragmentNode;
  6915. if ( fragmentNode.isOutputStructNode !== true ) {
  6916. fragmentNode = vec4( fragmentNode );
  6917. }
  6918. resultNode = this.setupOutput( builder, fragmentNode );
  6919. }
  6920. builder.stack.outputNode = resultNode;
  6921. builder.addFlow( 'fragment', builder.removeStack() );
  6922. // < MONITOR >
  6923. builder.monitor = this.setupObserver( builder );
  6924. }
  6925. setupClipping( builder ) {
  6926. if ( builder.clippingContext === null ) return null;
  6927. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  6928. let result = null;
  6929. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  6930. const samples = builder.renderer.samples;
  6931. if ( this.alphaToCoverage && samples > 1 ) {
  6932. // to be added to flow when the color/alpha value has been determined
  6933. result = clippingAlpha();
  6934. } else {
  6935. builder.stack.add( clipping() );
  6936. }
  6937. }
  6938. return result;
  6939. }
  6940. setupHardwareClipping( builder ) {
  6941. this.hardwareClipping = false;
  6942. if ( builder.clippingContext === null ) return;
  6943. const candidateCount = builder.clippingContext.unionPlanes.length;
  6944. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  6945. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  6946. builder.stack.add( hardwareClipping() );
  6947. this.hardwareClipping = true;
  6948. }
  6949. return;
  6950. }
  6951. setupDepth( builder ) {
  6952. const { renderer, camera } = builder;
  6953. // Depth
  6954. let depthNode = this.depthNode;
  6955. if ( depthNode === null ) {
  6956. const mrt = renderer.getMRT();
  6957. if ( mrt && mrt.has( 'depth' ) ) {
  6958. depthNode = mrt.get( 'depth' );
  6959. } else if ( renderer.logarithmicDepthBuffer === true ) {
  6960. if ( camera.isPerspectiveCamera ) {
  6961. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  6962. } else {
  6963. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6964. }
  6965. }
  6966. }
  6967. if ( depthNode !== null ) {
  6968. depth.assign( depthNode ).append();
  6969. }
  6970. }
  6971. setupPosition( builder ) {
  6972. const { object } = builder;
  6973. const geometry = object.geometry;
  6974. builder.addStack();
  6975. // Vertex
  6976. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  6977. morphReference( object ).append();
  6978. }
  6979. if ( object.isSkinnedMesh === true ) {
  6980. skinningReference( object ).append();
  6981. }
  6982. if ( this.displacementMap ) {
  6983. const displacementMap = materialReference( 'displacementMap', 'texture' );
  6984. const displacementScale = materialReference( 'displacementScale', 'float' );
  6985. const displacementBias = materialReference( 'displacementBias', 'float' );
  6986. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  6987. }
  6988. if ( object.isBatchedMesh ) {
  6989. batch( object ).append();
  6990. }
  6991. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  6992. instancedMesh( object ).append();
  6993. }
  6994. if ( this.positionNode !== null ) {
  6995. positionLocal.assign( this.positionNode );
  6996. }
  6997. this.setupHardwareClipping( builder );
  6998. const mvp = modelViewProjection();
  6999. builder.context.vertex = builder.removeStack();
  7000. builder.context.mvp = mvp;
  7001. return mvp;
  7002. }
  7003. setupDiffuseColor( { object, geometry } ) {
  7004. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  7005. // VERTEX COLORS
  7006. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  7007. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  7008. }
  7009. // Instanced colors
  7010. if ( object.instanceColor ) {
  7011. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  7012. colorNode = instanceColor.mul( colorNode );
  7013. }
  7014. if ( object.isBatchedMesh && object._colorsTexture ) {
  7015. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  7016. colorNode = batchColor.mul( colorNode );
  7017. }
  7018. // COLOR
  7019. diffuseColor.assign( colorNode );
  7020. // OPACITY
  7021. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7022. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  7023. // ALPHA TEST
  7024. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  7025. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  7026. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  7027. }
  7028. // ALPHA HASH
  7029. if ( this.alphaHash === true ) {
  7030. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  7031. }
  7032. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  7033. diffuseColor.a.assign( 1.0 );
  7034. }
  7035. }
  7036. setupVariants( /*builder*/ ) {
  7037. // Interface function.
  7038. }
  7039. setupOutgoingLight() {
  7040. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  7041. }
  7042. setupNormal() {
  7043. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  7044. }
  7045. setupEnvironment( /*builder*/ ) {
  7046. let node = null;
  7047. if ( this.envNode ) {
  7048. node = this.envNode;
  7049. } else if ( this.envMap ) {
  7050. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  7051. }
  7052. return node;
  7053. }
  7054. setupLightMap( builder ) {
  7055. let node = null;
  7056. if ( builder.material.lightMap ) {
  7057. node = new IrradianceNode( materialLightMap );
  7058. }
  7059. return node;
  7060. }
  7061. setupLights( builder ) {
  7062. const materialLightsNode = [];
  7063. //
  7064. const envNode = this.setupEnvironment( builder );
  7065. if ( envNode && envNode.isLightingNode ) {
  7066. materialLightsNode.push( envNode );
  7067. }
  7068. const lightMapNode = this.setupLightMap( builder );
  7069. if ( lightMapNode && lightMapNode.isLightingNode ) {
  7070. materialLightsNode.push( lightMapNode );
  7071. }
  7072. if ( this.aoNode !== null || builder.material.aoMap ) {
  7073. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  7074. materialLightsNode.push( new AONode( aoNode ) );
  7075. }
  7076. let lightsN = this.lightsNode || builder.lightsNode;
  7077. if ( materialLightsNode.length > 0 ) {
  7078. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  7079. }
  7080. return lightsN;
  7081. }
  7082. setupLightingModel( /*builder*/ ) {
  7083. // Interface function.
  7084. }
  7085. setupLighting( builder ) {
  7086. const { material } = builder;
  7087. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  7088. // OUTGOING LIGHT
  7089. const lights = this.lights === true || this.lightsNode !== null;
  7090. const lightsNode = lights ? this.setupLights( builder ) : null;
  7091. let outgoingLightNode = this.setupOutgoingLight( builder );
  7092. if ( lightsNode && lightsNode.getScope().hasLights ) {
  7093. const lightingModel = this.setupLightingModel( builder );
  7094. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  7095. } else if ( backdropNode !== null ) {
  7096. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  7097. }
  7098. // EMISSIVE
  7099. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  7100. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  7101. outgoingLightNode = outgoingLightNode.add( emissive );
  7102. }
  7103. return outgoingLightNode;
  7104. }
  7105. setupOutput( builder, outputNode ) {
  7106. // FOG
  7107. if ( this.fog === true ) {
  7108. const fogNode = builder.fogNode;
  7109. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  7110. }
  7111. return outputNode;
  7112. }
  7113. setDefaultValues( material ) {
  7114. // This approach is to reuse the native refreshUniforms*
  7115. // and turn available the use of features like transmission and environment in core
  7116. for ( const property in material ) {
  7117. const value = material[ property ];
  7118. if ( this[ property ] === undefined ) {
  7119. this[ property ] = value;
  7120. if ( value && value.clone ) this[ property ] = value.clone();
  7121. }
  7122. }
  7123. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  7124. for ( const key in descriptors ) {
  7125. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  7126. descriptors[ key ].get !== undefined ) {
  7127. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  7128. }
  7129. }
  7130. }
  7131. toJSON( meta ) {
  7132. const isRoot = ( meta === undefined || typeof meta === 'string' );
  7133. if ( isRoot ) {
  7134. meta = {
  7135. textures: {},
  7136. images: {},
  7137. nodes: {}
  7138. };
  7139. }
  7140. const data = Material.prototype.toJSON.call( this, meta );
  7141. const nodeChildren = getNodeChildren( this );
  7142. data.inputNodes = {};
  7143. for ( const { property, childNode } of nodeChildren ) {
  7144. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  7145. }
  7146. // TODO: Copied from Object3D.toJSON
  7147. function extractFromCache( cache ) {
  7148. const values = [];
  7149. for ( const key in cache ) {
  7150. const data = cache[ key ];
  7151. delete data.metadata;
  7152. values.push( data );
  7153. }
  7154. return values;
  7155. }
  7156. if ( isRoot ) {
  7157. const textures = extractFromCache( meta.textures );
  7158. const images = extractFromCache( meta.images );
  7159. const nodes = extractFromCache( meta.nodes );
  7160. if ( textures.length > 0 ) data.textures = textures;
  7161. if ( images.length > 0 ) data.images = images;
  7162. if ( nodes.length > 0 ) data.nodes = nodes;
  7163. }
  7164. return data;
  7165. }
  7166. copy( source ) {
  7167. this.lightsNode = source.lightsNode;
  7168. this.envNode = source.envNode;
  7169. this.colorNode = source.colorNode;
  7170. this.normalNode = source.normalNode;
  7171. this.opacityNode = source.opacityNode;
  7172. this.backdropNode = source.backdropNode;
  7173. this.backdropAlphaNode = source.backdropAlphaNode;
  7174. this.alphaTestNode = source.alphaTestNode;
  7175. this.positionNode = source.positionNode;
  7176. this.geometryNode = source.geometryNode;
  7177. this.depthNode = source.depthNode;
  7178. this.shadowPositionNode = source.shadowPositionNode;
  7179. this.receivedShadowNode = source.receivedShadowNode;
  7180. this.castShadowNode = source.castShadowNode;
  7181. this.outputNode = source.outputNode;
  7182. this.mrtNode = source.mrtNode;
  7183. this.fragmentNode = source.fragmentNode;
  7184. this.vertexNode = source.vertexNode;
  7185. return super.copy( source );
  7186. }
  7187. }
  7188. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  7189. class InstancedPointsNodeMaterial extends NodeMaterial {
  7190. static get type() {
  7191. return 'InstancedPointsNodeMaterial';
  7192. }
  7193. constructor( params = {} ) {
  7194. super();
  7195. this.lights = false;
  7196. this.useAlphaToCoverage = true;
  7197. this.useColor = params.vertexColors;
  7198. this.pointWidth = 1;
  7199. this.pointColorNode = null;
  7200. this.pointWidthNode = null;
  7201. this.setDefaultValues( _defaultValues$e );
  7202. this.setValues( params );
  7203. }
  7204. setup( builder ) {
  7205. this.setupShaders( builder );
  7206. super.setup( builder );
  7207. }
  7208. setupShaders( { renderer } ) {
  7209. const useAlphaToCoverage = this.alphaToCoverage;
  7210. const useColor = this.useColor;
  7211. this.vertexNode = Fn( () => {
  7212. const instancePosition = attribute( 'instancePosition' ).xyz;
  7213. // camera space
  7214. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  7215. const aspect = viewport.z.div( viewport.w );
  7216. // clip space
  7217. const clipPos = cameraProjectionMatrix.mul( mvPos );
  7218. // offset in ndc space
  7219. const offset = positionGeometry.xy.toVar();
  7220. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  7221. offset.assign( offset.div( viewport.z ) );
  7222. offset.y.assign( offset.y.mul( aspect ) );
  7223. // back to clip space
  7224. offset.assign( offset.mul( clipPos.w ) );
  7225. //clipPos.xy += offset;
  7226. clipPos.addAssign( vec4( offset, 0, 0 ) );
  7227. return clipPos;
  7228. } )();
  7229. this.fragmentNode = Fn( () => {
  7230. const alpha = float( 1 ).toVar();
  7231. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  7232. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7233. const dlen = float( len2.fwidth() ).toVar();
  7234. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  7235. } else {
  7236. len2.greaterThan( 1.0 ).discard();
  7237. }
  7238. let pointColorNode;
  7239. if ( this.pointColorNode ) {
  7240. pointColorNode = this.pointColorNode;
  7241. } else {
  7242. if ( useColor ) {
  7243. const instanceColor = attribute( 'instanceColor' );
  7244. pointColorNode = instanceColor.mul( materialColor );
  7245. } else {
  7246. pointColorNode = materialColor;
  7247. }
  7248. }
  7249. alpha.mulAssign( materialOpacity );
  7250. return vec4( pointColorNode, alpha );
  7251. } )();
  7252. }
  7253. get alphaToCoverage() {
  7254. return this.useAlphaToCoverage;
  7255. }
  7256. set alphaToCoverage( value ) {
  7257. if ( this.useAlphaToCoverage !== value ) {
  7258. this.useAlphaToCoverage = value;
  7259. this.needsUpdate = true;
  7260. }
  7261. }
  7262. }
  7263. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  7264. class LineBasicNodeMaterial extends NodeMaterial {
  7265. static get type() {
  7266. return 'LineBasicNodeMaterial';
  7267. }
  7268. constructor( parameters ) {
  7269. super();
  7270. this.isLineBasicNodeMaterial = true;
  7271. this.lights = false;
  7272. this.setDefaultValues( _defaultValues$d );
  7273. this.setValues( parameters );
  7274. }
  7275. }
  7276. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  7277. class LineDashedNodeMaterial extends NodeMaterial {
  7278. static get type() {
  7279. return 'LineDashedNodeMaterial';
  7280. }
  7281. constructor( parameters ) {
  7282. super();
  7283. this.isLineDashedNodeMaterial = true;
  7284. this.lights = false;
  7285. this.setDefaultValues( _defaultValues$c );
  7286. this.dashOffset = 0;
  7287. this.offsetNode = null;
  7288. this.dashScaleNode = null;
  7289. this.dashSizeNode = null;
  7290. this.gapSizeNode = null;
  7291. this.setValues( parameters );
  7292. }
  7293. setupVariants() {
  7294. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  7295. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  7296. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  7297. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  7298. dashSize.assign( dashSizeNode );
  7299. gapSize.assign( gapSizeNode );
  7300. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  7301. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  7302. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  7303. }
  7304. }
  7305. let _sharedFramebuffer = null;
  7306. /**
  7307. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  7308. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  7309. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  7310. *
  7311. * @augments ViewportTextureNode
  7312. */
  7313. class ViewportSharedTextureNode extends ViewportTextureNode {
  7314. static get type() {
  7315. return 'ViewportSharedTextureNode';
  7316. }
  7317. /**
  7318. * Constructs a new viewport shared texture node.
  7319. *
  7320. * @param {Node} [uvNode=screenUV] - The uv node.
  7321. * @param {Node?} [levelNode=null] - The level node.
  7322. */
  7323. constructor( uvNode = screenUV, levelNode = null ) {
  7324. if ( _sharedFramebuffer === null ) {
  7325. _sharedFramebuffer = new FramebufferTexture();
  7326. }
  7327. super( uvNode, levelNode, _sharedFramebuffer );
  7328. }
  7329. updateReference() {
  7330. return this;
  7331. }
  7332. }
  7333. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  7334. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  7335. class Line2NodeMaterial extends NodeMaterial {
  7336. static get type() {
  7337. return 'Line2NodeMaterial';
  7338. }
  7339. constructor( params = {} ) {
  7340. super();
  7341. this.lights = false;
  7342. this.setDefaultValues( _defaultValues$b );
  7343. this.useAlphaToCoverage = true;
  7344. this.useColor = params.vertexColors;
  7345. this.useDash = params.dashed;
  7346. this.useWorldUnits = false;
  7347. this.dashOffset = 0;
  7348. this.lineWidth = 1;
  7349. this.lineColorNode = null;
  7350. this.offsetNode = null;
  7351. this.dashScaleNode = null;
  7352. this.dashSizeNode = null;
  7353. this.gapSizeNode = null;
  7354. this.blending = NoBlending;
  7355. this.setValues( params );
  7356. }
  7357. setup( builder ) {
  7358. this.setupShaders( builder );
  7359. super.setup( builder );
  7360. }
  7361. setupShaders( { renderer } ) {
  7362. const useAlphaToCoverage = this.alphaToCoverage;
  7363. const useColor = this.useColor;
  7364. const useDash = this.dashed;
  7365. const useWorldUnits = this.worldUnits;
  7366. const trimSegment = Fn( ( { start, end } ) => {
  7367. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  7368. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  7369. const nearEstimate = b.mul( - 0.5 ).div( a );
  7370. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  7371. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  7372. } ).setLayout( {
  7373. name: 'trimSegment',
  7374. type: 'vec4',
  7375. inputs: [
  7376. { name: 'start', type: 'vec4' },
  7377. { name: 'end', type: 'vec4' }
  7378. ]
  7379. } );
  7380. this.vertexNode = Fn( () => {
  7381. const instanceStart = attribute( 'instanceStart' );
  7382. const instanceEnd = attribute( 'instanceEnd' );
  7383. // camera space
  7384. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  7385. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  7386. if ( useDash ) {
  7387. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  7388. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  7389. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  7390. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  7391. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  7392. lineDistance = lineDistance.add( offsetNode );
  7393. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  7394. }
  7395. if ( useWorldUnits ) {
  7396. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  7397. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  7398. }
  7399. const aspect = viewport.z.div( viewport.w );
  7400. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  7401. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  7402. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  7403. // perhaps there is a more elegant solution -- WestLangley
  7404. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  7405. If( perspective, () => {
  7406. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  7407. end.assign( trimSegment( { start: start, end: end } ) );
  7408. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  7409. start.assign( trimSegment( { start: end, end: start } ) );
  7410. } );
  7411. } );
  7412. // clip space
  7413. const clipStart = cameraProjectionMatrix.mul( start );
  7414. const clipEnd = cameraProjectionMatrix.mul( end );
  7415. // ndc space
  7416. const ndcStart = clipStart.xyz.div( clipStart.w );
  7417. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  7418. // direction
  7419. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  7420. // account for clip-space aspect ratio
  7421. dir.x.assign( dir.x.mul( aspect ) );
  7422. dir.assign( dir.normalize() );
  7423. const clip = vec4().toVar();
  7424. if ( useWorldUnits ) {
  7425. // get the offset direction as perpendicular to the view vector
  7426. const worldDir = end.xyz.sub( start.xyz ).normalize();
  7427. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  7428. const worldUp = worldDir.cross( tmpFwd ).normalize();
  7429. const worldFwd = worldDir.cross( worldUp );
  7430. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  7431. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  7432. // height offset
  7433. const hw = materialLineWidth.mul( 0.5 );
  7434. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  7435. // don't extend the line if we're rendering dashes because we
  7436. // won't be rendering the endcaps
  7437. if ( ! useDash ) {
  7438. // cap extension
  7439. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  7440. // add width to the box
  7441. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  7442. // endcaps
  7443. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  7444. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  7445. } );
  7446. }
  7447. // project the worldpos
  7448. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  7449. // shift the depth of the projected points so the line
  7450. // segments overlap neatly
  7451. const clipPose = vec3().toVar();
  7452. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  7453. clip.z.assign( clipPose.z.mul( clip.w ) );
  7454. } else {
  7455. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  7456. // undo aspect ratio adjustment
  7457. dir.x.assign( dir.x.div( aspect ) );
  7458. offset.x.assign( offset.x.div( aspect ) );
  7459. // sign flip
  7460. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  7461. // endcaps
  7462. If( positionGeometry.y.lessThan( 0.0 ), () => {
  7463. offset.assign( offset.sub( dir ) );
  7464. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  7465. offset.assign( offset.add( dir ) );
  7466. } );
  7467. // adjust for linewidth
  7468. offset.assign( offset.mul( materialLineWidth ) );
  7469. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  7470. offset.assign( offset.div( viewport.w ) );
  7471. // select end
  7472. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  7473. // back to clip space
  7474. offset.assign( offset.mul( clip.w ) );
  7475. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  7476. }
  7477. return clip;
  7478. } )();
  7479. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  7480. const p13 = p1.sub( p3 );
  7481. const p43 = p4.sub( p3 );
  7482. const p21 = p2.sub( p1 );
  7483. const d1343 = p13.dot( p43 );
  7484. const d4321 = p43.dot( p21 );
  7485. const d1321 = p13.dot( p21 );
  7486. const d4343 = p43.dot( p43 );
  7487. const d2121 = p21.dot( p21 );
  7488. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  7489. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  7490. const mua = numer.div( denom ).clamp();
  7491. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  7492. return vec2( mua, mub );
  7493. } );
  7494. this.colorNode = Fn( () => {
  7495. const vUv = uv();
  7496. if ( useDash ) {
  7497. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  7498. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  7499. dashSize.assign( dashSizeNode );
  7500. gapSize.assign( gapSizeNode );
  7501. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  7502. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  7503. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  7504. }
  7505. const alpha = float( 1 ).toVar( 'alpha' );
  7506. if ( useWorldUnits ) {
  7507. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  7508. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  7509. // Find the closest points on the view ray and the line segment
  7510. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  7511. const lineDir = worldEnd.sub( worldStart );
  7512. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  7513. const p1 = worldStart.add( lineDir.mul( params.x ) );
  7514. const p2 = rayEnd.mul( params.y );
  7515. const delta = p1.sub( p2 );
  7516. const len = delta.length();
  7517. const norm = len.div( materialLineWidth );
  7518. if ( ! useDash ) {
  7519. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7520. const dnorm = norm.fwidth();
  7521. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  7522. } else {
  7523. norm.greaterThan( 0.5 ).discard();
  7524. }
  7525. }
  7526. } else {
  7527. // round endcaps
  7528. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7529. const a = vUv.x;
  7530. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  7531. const len2 = a.mul( a ).add( b.mul( b ) );
  7532. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  7533. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  7534. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  7535. } );
  7536. } else {
  7537. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  7538. const a = vUv.x;
  7539. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  7540. const len2 = a.mul( a ).add( b.mul( b ) );
  7541. len2.greaterThan( 1.0 ).discard();
  7542. } );
  7543. }
  7544. }
  7545. let lineColorNode;
  7546. if ( this.lineColorNode ) {
  7547. lineColorNode = this.lineColorNode;
  7548. } else {
  7549. if ( useColor ) {
  7550. const instanceColorStart = attribute( 'instanceColorStart' );
  7551. const instanceColorEnd = attribute( 'instanceColorEnd' );
  7552. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  7553. lineColorNode = instanceColor.mul( materialColor );
  7554. } else {
  7555. lineColorNode = materialColor;
  7556. }
  7557. }
  7558. return vec4( lineColorNode, alpha );
  7559. } )();
  7560. if ( this.transparent ) {
  7561. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7562. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  7563. }
  7564. }
  7565. get worldUnits() {
  7566. return this.useWorldUnits;
  7567. }
  7568. set worldUnits( value ) {
  7569. if ( this.useWorldUnits !== value ) {
  7570. this.useWorldUnits = value;
  7571. this.needsUpdate = true;
  7572. }
  7573. }
  7574. get dashed() {
  7575. return this.useDash;
  7576. }
  7577. set dashed( value ) {
  7578. if ( this.useDash !== value ) {
  7579. this.useDash = value;
  7580. this.needsUpdate = true;
  7581. }
  7582. }
  7583. get alphaToCoverage() {
  7584. return this.useAlphaToCoverage;
  7585. }
  7586. set alphaToCoverage( value ) {
  7587. if ( this.useAlphaToCoverage !== value ) {
  7588. this.useAlphaToCoverage = value;
  7589. this.needsUpdate = true;
  7590. }
  7591. }
  7592. }
  7593. /** @module Packing **/
  7594. /**
  7595. * Packs a direction vector into a color value.
  7596. *
  7597. * @method
  7598. * @param {Node<vec3>} node - The direction to pack.
  7599. * @return {Node<vec3>} The color.
  7600. */
  7601. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  7602. /**
  7603. * Unpacks a color value into a direction vector.
  7604. *
  7605. * @method
  7606. * @param {Node<vec3>} color - The color to unpack.
  7607. * @return {Node<vec3>} The direction.
  7608. */
  7609. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  7610. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  7611. class MeshNormalNodeMaterial extends NodeMaterial {
  7612. static get type() {
  7613. return 'MeshNormalNodeMaterial';
  7614. }
  7615. constructor( parameters ) {
  7616. super();
  7617. this.lights = false;
  7618. this.isMeshNormalNodeMaterial = true;
  7619. this.setDefaultValues( _defaultValues$a );
  7620. this.setValues( parameters );
  7621. }
  7622. setupDiffuseColor() {
  7623. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7624. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  7625. }
  7626. }
  7627. /**
  7628. * Can be used to compute texture coordinates for projecting an
  7629. * equirectangular texture onto a mesh for using it as the scene's
  7630. * background.
  7631. *
  7632. * ```js
  7633. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  7634. * ```
  7635. *
  7636. * @augments TempNode
  7637. */
  7638. class EquirectUVNode extends TempNode {
  7639. static get type() {
  7640. return 'EquirectUVNode';
  7641. }
  7642. /**
  7643. * Constructs a new equirect uv node.
  7644. *
  7645. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling why is by default `positionWorldDirection`.
  7646. */
  7647. constructor( dirNode = positionWorldDirection ) {
  7648. super( 'vec2' );
  7649. /**
  7650. * A direction vector for sampling why is by default `positionWorldDirection`.
  7651. *
  7652. * @type {Node<vec3>}
  7653. */
  7654. this.dirNode = dirNode;
  7655. }
  7656. setup() {
  7657. const dir = this.dirNode;
  7658. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  7659. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  7660. return vec2( u, v );
  7661. }
  7662. }
  7663. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  7664. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  7665. class CubeRenderTarget extends WebGLCubeRenderTarget {
  7666. constructor( size = 1, options = {} ) {
  7667. super( size, options );
  7668. this.isCubeRenderTarget = true;
  7669. }
  7670. fromEquirectangularTexture( renderer, texture$1 ) {
  7671. const currentMinFilter = texture$1.minFilter;
  7672. const currentGenerateMipmaps = texture$1.generateMipmaps;
  7673. texture$1.generateMipmaps = true;
  7674. this.texture.type = texture$1.type;
  7675. this.texture.colorSpace = texture$1.colorSpace;
  7676. this.texture.generateMipmaps = texture$1.generateMipmaps;
  7677. this.texture.minFilter = texture$1.minFilter;
  7678. this.texture.magFilter = texture$1.magFilter;
  7679. const geometry = new BoxGeometry( 5, 5, 5 );
  7680. const uvNode = equirectUV( positionWorldDirection );
  7681. const material = new NodeMaterial();
  7682. material.colorNode = texture( texture$1, uvNode, 0 );
  7683. material.side = BackSide;
  7684. material.blending = NoBlending;
  7685. const mesh = new Mesh( geometry, material );
  7686. const scene = new Scene();
  7687. scene.add( mesh );
  7688. // Avoid blurred poles
  7689. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  7690. const camera = new CubeCamera( 1, 10, this );
  7691. const currentMRT = renderer.getMRT();
  7692. renderer.setMRT( null );
  7693. camera.update( renderer, scene );
  7694. renderer.setMRT( currentMRT );
  7695. texture$1.minFilter = currentMinFilter;
  7696. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  7697. mesh.geometry.dispose();
  7698. mesh.material.dispose();
  7699. return this;
  7700. }
  7701. }
  7702. const _cache$1 = new WeakMap();
  7703. /**
  7704. * This node can be used to automatically convert environment maps in the
  7705. * equirectangular format into the cube map format.
  7706. *
  7707. * @augments TempNode
  7708. */
  7709. class CubeMapNode extends TempNode {
  7710. static get type() {
  7711. return 'CubeMapNode';
  7712. }
  7713. /**
  7714. * Constructs a new cube map node.
  7715. *
  7716. * @param {Node} envNode - The node representing the environment map.
  7717. */
  7718. constructor( envNode ) {
  7719. super( 'vec3' );
  7720. /**
  7721. * The node representing the environment map.
  7722. *
  7723. * @type {Node}
  7724. */
  7725. this.envNode = envNode;
  7726. /**
  7727. * A reference to the internal cube texture.
  7728. *
  7729. * @private
  7730. * @type {CubeTexture}
  7731. * @default null
  7732. */
  7733. this._cubeTexture = null;
  7734. /**
  7735. * A reference to the internal cube texture node.
  7736. *
  7737. * @private
  7738. * @type {CubeTextureNode}
  7739. */
  7740. this._cubeTextureNode = cubeTexture();
  7741. const defaultTexture = new CubeTexture();
  7742. defaultTexture.isRenderTargetTexture = true;
  7743. /**
  7744. * A default cube texture that acts as a placeholder.
  7745. * It is used when the conversion from equirectangular to cube
  7746. * map has not finished yet for a given texture.
  7747. *
  7748. * @private
  7749. * @type {CubeTexture}
  7750. */
  7751. this._defaultTexture = defaultTexture;
  7752. /**
  7753. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  7754. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  7755. *
  7756. * @type {String}
  7757. * @default 'render'
  7758. */
  7759. this.updateBeforeType = NodeUpdateType.RENDER;
  7760. }
  7761. updateBefore( frame ) {
  7762. const { renderer, material } = frame;
  7763. const envNode = this.envNode;
  7764. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  7765. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  7766. if ( texture && texture.isTexture ) {
  7767. const mapping = texture.mapping;
  7768. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  7769. // check for converted cubemap map
  7770. if ( _cache$1.has( texture ) ) {
  7771. const cubeMap = _cache$1.get( texture );
  7772. mapTextureMapping( cubeMap, texture.mapping );
  7773. this._cubeTexture = cubeMap;
  7774. } else {
  7775. // create cube map from equirectangular map
  7776. const image = texture.image;
  7777. if ( isEquirectangularMapReady$1( image ) ) {
  7778. const renderTarget = new CubeRenderTarget( image.height );
  7779. renderTarget.fromEquirectangularTexture( renderer, texture );
  7780. mapTextureMapping( renderTarget.texture, texture.mapping );
  7781. this._cubeTexture = renderTarget.texture;
  7782. _cache$1.set( texture, renderTarget.texture );
  7783. texture.addEventListener( 'dispose', onTextureDispose );
  7784. } else {
  7785. // default cube texture as fallback when equirectangular texture is not yet loaded
  7786. this._cubeTexture = this._defaultTexture;
  7787. }
  7788. }
  7789. //
  7790. this._cubeTextureNode.value = this._cubeTexture;
  7791. } else {
  7792. // envNode already refers to a cube map
  7793. this._cubeTextureNode = this.envNode;
  7794. }
  7795. }
  7796. }
  7797. }
  7798. setup( builder ) {
  7799. this.updateBefore( builder );
  7800. return this._cubeTextureNode;
  7801. }
  7802. }
  7803. /**
  7804. * Returns true if the given equirectangular image has been fully loaded
  7805. * and is ready for further processing.
  7806. *
  7807. * @private
  7808. * @param {Image} image - The equirectangular image to check.
  7809. * @return {Boolean} Whether the image is ready or not.
  7810. */
  7811. function isEquirectangularMapReady$1( image ) {
  7812. if ( image === null || image === undefined ) return false;
  7813. return image.height > 0;
  7814. }
  7815. /**
  7816. * This function is executed when `dispose()` is called on the equirectangular
  7817. * texture. In this case, the generated cube map with its render target
  7818. * is deleted as well.
  7819. *
  7820. * @private
  7821. * @param {Object} event - The event object.
  7822. */
  7823. function onTextureDispose( event ) {
  7824. const texture = event.target;
  7825. texture.removeEventListener( 'dispose', onTextureDispose );
  7826. const renderTarget = _cache$1.get( texture );
  7827. if ( renderTarget !== undefined ) {
  7828. _cache$1.delete( texture );
  7829. renderTarget.dispose();
  7830. }
  7831. }
  7832. /**
  7833. * This function makes sure the generated cube map uses the correct
  7834. * texture mapping that corresponds to the equirectangular original.
  7835. *
  7836. * @private
  7837. * @param {Texture} texture - The cube texture.
  7838. * @param {Number} mapping - The original texture mapping.
  7839. */
  7840. function mapTextureMapping( texture, mapping ) {
  7841. if ( mapping === EquirectangularReflectionMapping ) {
  7842. texture.mapping = CubeReflectionMapping;
  7843. } else if ( mapping === EquirectangularRefractionMapping ) {
  7844. texture.mapping = CubeRefractionMapping;
  7845. }
  7846. }
  7847. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  7848. class BasicEnvironmentNode extends LightingNode {
  7849. static get type() {
  7850. return 'BasicEnvironmentNode';
  7851. }
  7852. constructor( envNode = null ) {
  7853. super();
  7854. this.envNode = envNode;
  7855. }
  7856. setup( builder ) {
  7857. // environment property is used in the finish() method of BasicLightingModel
  7858. builder.context.environment = cubeMapNode( this.envNode );
  7859. }
  7860. }
  7861. class BasicLightMapNode extends LightingNode {
  7862. static get type() {
  7863. return 'BasicLightMapNode';
  7864. }
  7865. constructor( lightMapNode = null ) {
  7866. super();
  7867. this.lightMapNode = lightMapNode;
  7868. }
  7869. setup( builder ) {
  7870. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  7871. const RECIPROCAL_PI = float( 1 / Math.PI );
  7872. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  7873. }
  7874. }
  7875. /**
  7876. * Abstract class for implementing lighting models. The module defines
  7877. * multiple methods that concrete lighting models can implement. These
  7878. * methods are executed at different points during the light evaluation
  7879. * process.
  7880. */
  7881. class LightingModel {
  7882. /**
  7883. * This method is intended for setting up lighting model and context data
  7884. * which are later used in the evaluation process.
  7885. *
  7886. * @abstract
  7887. * @param {ContextNode} input - The current node context.
  7888. * @param {StackNode} stack - The current stack.
  7889. * @param {NodeBuilder} builder - The current node builder.
  7890. */
  7891. start( /*input, stack, builder*/ ) { }
  7892. /**
  7893. * This method is intended for executing final tasks like final updates
  7894. * to the outgoing light.
  7895. *
  7896. * @abstract
  7897. * @param {ContextNode} input - The current node context.
  7898. * @param {StackNode} stack - The current stack.
  7899. * @param {NodeBuilder} builder - The current node builder.
  7900. */
  7901. finish( /*input, stack, builder*/ ) { }
  7902. /**
  7903. * This method is intended for implementing the direct light term and
  7904. * executed during the build process of directional, point and spot light nodes.
  7905. *
  7906. * @abstract
  7907. * @param {Object} input - The input data.
  7908. * @param {StackNode} stack - The current stack.
  7909. * @param {NodeBuilder} builder - The current node builder.
  7910. */
  7911. direct( /*input, stack, builder*/ ) { }
  7912. /**
  7913. * This method is intended for implementing the direct light term for
  7914. * rect area light nodes.
  7915. *
  7916. * @abstract
  7917. * @param {Object} input - The input data.
  7918. * @param {StackNode} stack - The current stack.
  7919. * @param {NodeBuilder} builder - The current node builder.
  7920. */
  7921. directRectArea( /*input, stack, builder*/ ) {}
  7922. /**
  7923. * This method is intended for implementing the indirect light term.
  7924. *
  7925. * @abstract
  7926. * @param {ContextNode} input - The current node context.
  7927. * @param {StackNode} stack - The current stack.
  7928. * @param {NodeBuilder} builder - The current node builder.
  7929. */
  7930. indirect( /*input, stack, builder*/ ) { }
  7931. /**
  7932. * This method is intended for implementing the ambient occlusion term.
  7933. * Unlike other methods, this method must be called manually by the lighting
  7934. * model in its indirect term.
  7935. *
  7936. * @abstract
  7937. * @param {ContextNode} input - The current node context.
  7938. * @param {StackNode} stack - The current stack.
  7939. * @param {NodeBuilder} builder - The current node builder.
  7940. */
  7941. ambientOcclusion( /*input, stack, builder*/ ) { }
  7942. }
  7943. /**
  7944. * Represents the lighting model for unlit materials. The only light contribution
  7945. * is baked indirect lighting modulated with ambient occlusion and the material's
  7946. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  7947. *
  7948. * @augments LightingModel
  7949. */
  7950. class BasicLightingModel extends LightingModel {
  7951. /**
  7952. * Constructs a new basic lighting model.
  7953. */
  7954. constructor() {
  7955. super();
  7956. }
  7957. /**
  7958. * Implements the baked indirect lighting with its modulation.
  7959. *
  7960. * @param {ContextNode} input - The current node context.
  7961. * @param {StackNode} stack - The current stack.
  7962. * @param {NodeBuilder} builder - The current node builder.
  7963. */
  7964. indirect( context, stack, builder ) {
  7965. const ambientOcclusion = context.ambientOcclusion;
  7966. const reflectedLight = context.reflectedLight;
  7967. const irradianceLightMap = builder.context.irradianceLightMap;
  7968. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  7969. // accumulation (baked indirect lighting only)
  7970. if ( irradianceLightMap ) {
  7971. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  7972. } else {
  7973. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  7974. }
  7975. // modulation
  7976. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7977. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  7978. }
  7979. /**
  7980. * Implements the environment mapping.
  7981. *
  7982. * @param {ContextNode} input - The current node context.
  7983. * @param {StackNode} stack - The current stack.
  7984. * @param {NodeBuilder} builder - The current node builder.
  7985. */
  7986. finish( context, stack, builder ) {
  7987. const material = builder.material;
  7988. const outgoingLight = context.outgoingLight;
  7989. const envNode = builder.context.environment;
  7990. if ( envNode ) {
  7991. switch ( material.combine ) {
  7992. case MultiplyOperation:
  7993. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  7994. break;
  7995. case MixOperation:
  7996. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  7997. break;
  7998. case AddOperation:
  7999. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  8000. break;
  8001. default:
  8002. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  8003. break;
  8004. }
  8005. }
  8006. }
  8007. }
  8008. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  8009. class MeshBasicNodeMaterial extends NodeMaterial {
  8010. static get type() {
  8011. return 'MeshBasicNodeMaterial';
  8012. }
  8013. constructor( parameters ) {
  8014. super();
  8015. this.isMeshBasicNodeMaterial = true;
  8016. this.lights = true;
  8017. this.setDefaultValues( _defaultValues$9 );
  8018. this.setValues( parameters );
  8019. }
  8020. setupNormal() {
  8021. return normalView; // see #28839
  8022. }
  8023. setupEnvironment( builder ) {
  8024. const envNode = super.setupEnvironment( builder );
  8025. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8026. }
  8027. setupLightMap( builder ) {
  8028. let node = null;
  8029. if ( builder.material.lightMap ) {
  8030. node = new BasicLightMapNode( materialLightMap );
  8031. }
  8032. return node;
  8033. }
  8034. setupOutgoingLight() {
  8035. return diffuseColor.rgb;
  8036. }
  8037. setupLightingModel() {
  8038. return new BasicLightingModel();
  8039. }
  8040. }
  8041. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  8042. // Original approximation by Christophe Schlick '94
  8043. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  8044. // Optimized variant (presented by Epic at SIGGRAPH '13)
  8045. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  8046. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  8047. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  8048. } ); // validated
  8049. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  8050. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  8051. } ); // validated
  8052. const G_BlinnPhong_Implicit = () => float( 0.25 );
  8053. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  8054. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  8055. } );
  8056. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  8057. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8058. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  8059. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  8060. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  8061. const G = G_BlinnPhong_Implicit();
  8062. const D = D_BlinnPhong( { dotNH } );
  8063. return F.mul( G ).mul( D );
  8064. } );
  8065. /**
  8066. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  8067. *
  8068. * @augments LightingModel
  8069. */
  8070. class PhongLightingModel extends BasicLightingModel {
  8071. /**
  8072. * Constructs a new phong lighting model.
  8073. *
  8074. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  8075. */
  8076. constructor( specular = true ) {
  8077. super();
  8078. /**
  8079. * Whether specular is supported or not. Set this to `false` if you are
  8080. * lookking for a Lambert-like material meaning a material for non-shiny
  8081. * surfaces, without specular highlights.
  8082. *
  8083. * @type {Boolean}
  8084. * @default true
  8085. */
  8086. this.specular = specular;
  8087. }
  8088. /**
  8089. * Implements the direct lighting. The specular portion is optional an can be controlled
  8090. * with the {@link PhongLightingModel#specular} flag.
  8091. *
  8092. * @param {Object} input - The input data.
  8093. * @param {StackNode} stack - The current stack.
  8094. * @param {NodeBuilder} builder - The current node builder.
  8095. */
  8096. direct( { lightDirection, lightColor, reflectedLight } ) {
  8097. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  8098. const irradiance = dotNL.mul( lightColor );
  8099. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  8100. if ( this.specular === true ) {
  8101. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  8102. }
  8103. }
  8104. /**
  8105. * Implements the indirect lighting.
  8106. *
  8107. * @param {ContextNode} input - The current node context.
  8108. * @param {StackNode} stack - The current stack.
  8109. * @param {NodeBuilder} builder - The current node builder.
  8110. */
  8111. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  8112. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  8113. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  8114. }
  8115. }
  8116. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  8117. class MeshLambertNodeMaterial extends NodeMaterial {
  8118. static get type() {
  8119. return 'MeshLambertNodeMaterial';
  8120. }
  8121. constructor( parameters ) {
  8122. super();
  8123. this.isMeshLambertNodeMaterial = true;
  8124. this.lights = true;
  8125. this.setDefaultValues( _defaultValues$8 );
  8126. this.setValues( parameters );
  8127. }
  8128. setupEnvironment( builder ) {
  8129. const envNode = super.setupEnvironment( builder );
  8130. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8131. }
  8132. setupLightingModel( /*builder*/ ) {
  8133. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  8134. }
  8135. }
  8136. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  8137. class MeshPhongNodeMaterial extends NodeMaterial {
  8138. static get type() {
  8139. return 'MeshPhongNodeMaterial';
  8140. }
  8141. constructor( parameters ) {
  8142. super();
  8143. this.isMeshPhongNodeMaterial = true;
  8144. this.lights = true;
  8145. this.shininessNode = null;
  8146. this.specularNode = null;
  8147. this.setDefaultValues( _defaultValues$7 );
  8148. this.setValues( parameters );
  8149. }
  8150. setupEnvironment( builder ) {
  8151. const envNode = super.setupEnvironment( builder );
  8152. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8153. }
  8154. setupLightingModel( /*builder*/ ) {
  8155. return new PhongLightingModel();
  8156. }
  8157. setupVariants() {
  8158. // SHININESS
  8159. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  8160. shininess.assign( shininessNode );
  8161. // SPECULAR COLOR
  8162. const specularNode = this.specularNode || materialSpecular;
  8163. specularColor.assign( specularNode );
  8164. }
  8165. copy( source ) {
  8166. this.shininessNode = source.shininessNode;
  8167. this.specularNode = source.specularNode;
  8168. return super.copy( source );
  8169. }
  8170. }
  8171. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  8172. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8173. return float( 0 );
  8174. }
  8175. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  8176. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  8177. return geometryRoughness;
  8178. } );
  8179. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  8180. const { roughness } = inputs;
  8181. const geometryRoughness = getGeometryRoughness();
  8182. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  8183. roughnessFactor = roughnessFactor.add( geometryRoughness );
  8184. roughnessFactor = roughnessFactor.min( 1.0 );
  8185. return roughnessFactor;
  8186. } );
  8187. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  8188. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  8189. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  8190. const a2 = alpha.pow2();
  8191. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  8192. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  8193. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  8194. } ).setLayout( {
  8195. name: 'V_GGX_SmithCorrelated',
  8196. type: 'float',
  8197. inputs: [
  8198. { name: 'alpha', type: 'float' },
  8199. { name: 'dotNL', type: 'float' },
  8200. { name: 'dotNV', type: 'float' }
  8201. ]
  8202. } ); // validated
  8203. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  8204. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  8205. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  8206. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  8207. const v = div( 0.5, gv.add( gl ) );
  8208. return v.saturate();
  8209. } ).setLayout( {
  8210. name: 'V_GGX_SmithCorrelated_Anisotropic',
  8211. type: 'float',
  8212. inputs: [
  8213. { name: 'alphaT', type: 'float', qualifier: 'in' },
  8214. { name: 'alphaB', type: 'float', qualifier: 'in' },
  8215. { name: 'dotTV', type: 'float', qualifier: 'in' },
  8216. { name: 'dotBV', type: 'float', qualifier: 'in' },
  8217. { name: 'dotTL', type: 'float', qualifier: 'in' },
  8218. { name: 'dotBL', type: 'float', qualifier: 'in' },
  8219. { name: 'dotNV', type: 'float', qualifier: 'in' },
  8220. { name: 'dotNL', type: 'float', qualifier: 'in' }
  8221. ]
  8222. } );
  8223. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  8224. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  8225. // alpha is "roughness squared" in Disney’s reparameterization
  8226. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  8227. const a2 = alpha.pow2();
  8228. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  8229. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  8230. } ).setLayout( {
  8231. name: 'D_GGX',
  8232. type: 'float',
  8233. inputs: [
  8234. { name: 'alpha', type: 'float' },
  8235. { name: 'dotNH', type: 'float' }
  8236. ]
  8237. } ); // validated
  8238. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  8239. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  8240. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  8241. const a2 = alphaT.mul( alphaB );
  8242. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  8243. const v2 = v.dot( v );
  8244. const w2 = a2.div( v2 );
  8245. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  8246. } ).setLayout( {
  8247. name: 'D_GGX_Anisotropic',
  8248. type: 'float',
  8249. inputs: [
  8250. { name: 'alphaT', type: 'float', qualifier: 'in' },
  8251. { name: 'alphaB', type: 'float', qualifier: 'in' },
  8252. { name: 'dotNH', type: 'float', qualifier: 'in' },
  8253. { name: 'dotTH', type: 'float', qualifier: 'in' },
  8254. { name: 'dotBH', type: 'float', qualifier: 'in' }
  8255. ]
  8256. } );
  8257. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  8258. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  8259. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  8260. const normalView = inputs.normalView || transformedNormalView;
  8261. const alpha = roughness.pow2(); // UE4's roughness
  8262. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8263. const dotNL = normalView.dot( lightDirection ).clamp();
  8264. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  8265. const dotNH = normalView.dot( halfDir ).clamp();
  8266. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  8267. let F = F_Schlick( { f0, f90, dotVH } );
  8268. let V, D;
  8269. if ( defined( USE_IRIDESCENCE ) ) {
  8270. F = iridescence.mix( F, f );
  8271. }
  8272. if ( defined( USE_ANISOTROPY ) ) {
  8273. const dotTL = anisotropyT.dot( lightDirection );
  8274. const dotTV = anisotropyT.dot( positionViewDirection );
  8275. const dotTH = anisotropyT.dot( halfDir );
  8276. const dotBL = anisotropyB.dot( lightDirection );
  8277. const dotBV = anisotropyB.dot( positionViewDirection );
  8278. const dotBH = anisotropyB.dot( halfDir );
  8279. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  8280. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  8281. } else {
  8282. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  8283. D = D_GGX( { alpha, dotNH } );
  8284. }
  8285. return F.mul( V ).mul( D );
  8286. } ); // validated
  8287. // Analytical approximation of the DFG LUT, one half of the
  8288. // split-sum approximation used in indirect specular lighting.
  8289. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  8290. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  8291. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  8292. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  8293. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  8294. const r = roughness.mul( c0 ).add( c1 );
  8295. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  8296. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  8297. return fab;
  8298. } ).setLayout( {
  8299. name: 'DFGApprox',
  8300. type: 'vec2',
  8301. inputs: [
  8302. { name: 'roughness', type: 'float' },
  8303. { name: 'dotNV', type: 'vec3' }
  8304. ]
  8305. } );
  8306. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  8307. const { dotNV, specularColor, specularF90, roughness } = inputs;
  8308. const fab = DFGApprox( { dotNV, roughness } );
  8309. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  8310. } );
  8311. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  8312. const x = dotVH.oneMinus().saturate();
  8313. const x2 = x.mul( x );
  8314. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  8315. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  8316. } ).setLayout( {
  8317. name: 'Schlick_to_F0',
  8318. type: 'vec3',
  8319. inputs: [
  8320. { name: 'f', type: 'vec3' },
  8321. { name: 'f90', type: 'float' },
  8322. { name: 'dotVH', type: 'float' }
  8323. ]
  8324. } );
  8325. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  8326. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  8327. const alpha = roughness.pow2();
  8328. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  8329. const invAlpha = float( 1.0 ).div( alpha );
  8330. const cos2h = dotNH.pow2();
  8331. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  8332. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  8333. } ).setLayout( {
  8334. name: 'D_Charlie',
  8335. type: 'float',
  8336. inputs: [
  8337. { name: 'roughness', type: 'float' },
  8338. { name: 'dotNH', type: 'float' }
  8339. ]
  8340. } );
  8341. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  8342. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  8343. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  8344. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  8345. } ).setLayout( {
  8346. name: 'V_Neubelt',
  8347. type: 'float',
  8348. inputs: [
  8349. { name: 'dotNV', type: 'float' },
  8350. { name: 'dotNL', type: 'float' }
  8351. ]
  8352. } );
  8353. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  8354. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8355. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  8356. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  8357. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  8358. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  8359. const V = V_Neubelt( { dotNV, dotNL } );
  8360. return sheen.mul( D ).mul( V );
  8361. } );
  8362. // Rect Area Light
  8363. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  8364. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  8365. // code: https://github.com/selfshadow/ltc_code/
  8366. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  8367. const LUT_SIZE = 64.0;
  8368. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  8369. const LUT_BIAS = 0.5 / LUT_SIZE;
  8370. const dotNV = N.dot( V ).saturate();
  8371. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  8372. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  8373. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  8374. return uv;
  8375. } ).setLayout( {
  8376. name: 'LTC_Uv',
  8377. type: 'vec2',
  8378. inputs: [
  8379. { name: 'N', type: 'vec3' },
  8380. { name: 'V', type: 'vec3' },
  8381. { name: 'roughness', type: 'float' }
  8382. ]
  8383. } );
  8384. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  8385. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  8386. // An approximation of the form factor of a horizon-clipped rectangle.
  8387. const l = f.length();
  8388. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  8389. } ).setLayout( {
  8390. name: 'LTC_ClippedSphereFormFactor',
  8391. type: 'float',
  8392. inputs: [
  8393. { name: 'f', type: 'vec3' }
  8394. ]
  8395. } );
  8396. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  8397. const x = v1.dot( v2 );
  8398. const y = x.abs().toVar();
  8399. // rational polynomial approximation to theta / sin( theta ) / 2PI
  8400. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  8401. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  8402. const v = a.div( b );
  8403. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  8404. return v1.cross( v2 ).mul( theta_sintheta );
  8405. } ).setLayout( {
  8406. name: 'LTC_EdgeVectorFormFactor',
  8407. type: 'vec3',
  8408. inputs: [
  8409. { name: 'v1', type: 'vec3' },
  8410. { name: 'v2', type: 'vec3' }
  8411. ]
  8412. } );
  8413. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  8414. // bail if point is on back side of plane of light
  8415. // assumes ccw winding order of light vertices
  8416. const v1 = p1.sub( p0 ).toVar();
  8417. const v2 = p3.sub( p0 ).toVar();
  8418. const lightNormal = v1.cross( v2 );
  8419. const result = vec3().toVar();
  8420. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  8421. // construct orthonormal basis around N
  8422. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  8423. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  8424. // compute transform
  8425. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  8426. // transform rect
  8427. // & project rect onto sphere
  8428. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  8429. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  8430. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  8431. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  8432. // calculate vector form factor
  8433. const vectorFormFactor = vec3( 0 ).toVar();
  8434. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  8435. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  8436. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  8437. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  8438. // adjust for horizon clipping
  8439. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  8440. } );
  8441. return result;
  8442. } ).setLayout( {
  8443. name: 'LTC_Evaluate',
  8444. type: 'vec3',
  8445. inputs: [
  8446. { name: 'N', type: 'vec3' },
  8447. { name: 'V', type: 'vec3' },
  8448. { name: 'P', type: 'vec3' },
  8449. { name: 'mInv', type: 'mat3' },
  8450. { name: 'p0', type: 'vec3' },
  8451. { name: 'p1', type: 'vec3' },
  8452. { name: 'p2', type: 'vec3' },
  8453. { name: 'p3', type: 'vec3' }
  8454. ]
  8455. } );
  8456. // Mipped Bicubic Texture Filtering by N8
  8457. // https://www.shadertoy.com/view/Dl2SDW
  8458. const bC = 1.0 / 6.0;
  8459. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  8460. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  8461. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  8462. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  8463. const g0 = ( a ) => w0( a ).add( w1( a ) );
  8464. const g1 = ( a ) => w2( a ).add( w3( a ) );
  8465. // h0 and h1 are the two offset functions
  8466. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  8467. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  8468. const bicubic = ( textureNode, texelSize, lod ) => {
  8469. const uv = textureNode.uvNode;
  8470. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  8471. const iuv = floor( uvScaled );
  8472. const fuv = fract( uvScaled );
  8473. const g0x = g0( fuv.x );
  8474. const g1x = g1( fuv.x );
  8475. const h0x = h0( fuv.x );
  8476. const h1x = h1( fuv.x );
  8477. const h0y = h0( fuv.y );
  8478. const h1y = h1( fuv.y );
  8479. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  8480. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  8481. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  8482. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  8483. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  8484. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  8485. return a.add( b );
  8486. };
  8487. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  8488. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  8489. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  8490. const fLodSizeInv = div( 1.0, fLodSize );
  8491. const cLodSizeInv = div( 1.0, cLodSize );
  8492. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  8493. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  8494. return fract( lodNode ).mix( fSample, cSample );
  8495. } );
  8496. //
  8497. // Transmission
  8498. //
  8499. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  8500. // Direction of refracted light.
  8501. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  8502. // Compute rotation-independent scaling of the model matrix.
  8503. const modelScale = vec3(
  8504. length( modelMatrix[ 0 ].xyz ),
  8505. length( modelMatrix[ 1 ].xyz ),
  8506. length( modelMatrix[ 2 ].xyz )
  8507. );
  8508. // The thickness is specified in local space.
  8509. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  8510. } ).setLayout( {
  8511. name: 'getVolumeTransmissionRay',
  8512. type: 'vec3',
  8513. inputs: [
  8514. { name: 'n', type: 'vec3' },
  8515. { name: 'v', type: 'vec3' },
  8516. { name: 'thickness', type: 'float' },
  8517. { name: 'ior', type: 'float' },
  8518. { name: 'modelMatrix', type: 'mat4' }
  8519. ]
  8520. } );
  8521. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  8522. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  8523. // an IOR of 1.5 results in the default amount of microfacet refraction.
  8524. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  8525. } ).setLayout( {
  8526. name: 'applyIorToRoughness',
  8527. type: 'float',
  8528. inputs: [
  8529. { name: 'roughness', type: 'float' },
  8530. { name: 'ior', type: 'float' }
  8531. ]
  8532. } );
  8533. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  8534. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  8535. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  8536. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  8537. const transmissionSample = vTexture.sample( fragCoord );
  8538. //const transmissionSample = viewportMipTexture( fragCoord );
  8539. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  8540. return textureBicubic( transmissionSample, lod );
  8541. } );
  8542. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  8543. If( attenuationDistance.notEqual( 0 ), () => {
  8544. // Compute light attenuation using Beer's law.
  8545. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  8546. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  8547. return transmittance;
  8548. } );
  8549. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  8550. return vec3( 1.0 );
  8551. } ).setLayout( {
  8552. name: 'volumeAttenuation',
  8553. type: 'vec3',
  8554. inputs: [
  8555. { name: 'transmissionDistance', type: 'float' },
  8556. { name: 'attenuationColor', type: 'vec3' },
  8557. { name: 'attenuationDistance', type: 'float' }
  8558. ]
  8559. } );
  8560. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  8561. let transmittedLight, transmittance;
  8562. if ( dispersion ) {
  8563. transmittedLight = vec4().toVar();
  8564. transmittance = vec3().toVar();
  8565. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  8566. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  8567. Loop( { start: 0, end: 3 }, ( { i } ) => {
  8568. const ior = iors.element( i );
  8569. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  8570. const refractedRayExit = position.add( transmissionRay );
  8571. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  8572. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  8573. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  8574. refractionCoords.addAssign( 1.0 );
  8575. refractionCoords.divAssign( 2.0 );
  8576. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  8577. // Sample framebuffer to get pixel the refracted ray hits.
  8578. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  8579. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  8580. transmittedLight.a.addAssign( transmissionSample.a );
  8581. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  8582. } );
  8583. transmittedLight.a.divAssign( 3.0 );
  8584. } else {
  8585. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  8586. const refractedRayExit = position.add( transmissionRay );
  8587. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  8588. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  8589. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  8590. refractionCoords.addAssign( 1.0 );
  8591. refractionCoords.divAssign( 2.0 );
  8592. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  8593. // Sample framebuffer to get pixel the refracted ray hits.
  8594. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  8595. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  8596. }
  8597. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  8598. const dotNV = n.dot( v ).clamp();
  8599. // Get the specular component.
  8600. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  8601. dotNV,
  8602. specularColor,
  8603. specularF90,
  8604. roughness
  8605. } ) );
  8606. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  8607. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  8608. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  8609. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  8610. } );
  8611. //
  8612. // Iridescence
  8613. //
  8614. // XYZ to linear-sRGB color space
  8615. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  8616. 3.2404542, - 0.9692660, 0.0556434,
  8617. - 1.5371385, 1.8760108, - 0.2040259,
  8618. - 0.4985314, 0.0415560, 1.0572252
  8619. );
  8620. // Assume air interface for top
  8621. // Note: We don't handle the case fresnel0 == 1
  8622. const Fresnel0ToIor = ( fresnel0 ) => {
  8623. const sqrtF0 = fresnel0.sqrt();
  8624. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  8625. };
  8626. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  8627. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  8628. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  8629. };
  8630. // Fresnel equations for dielectric/dielectric interfaces.
  8631. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  8632. // Evaluation XYZ sensitivity curves in Fourier space
  8633. const evalSensitivity = ( OPD, shift ) => {
  8634. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  8635. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  8636. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  8637. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  8638. 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() );
  8639. 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() );
  8640. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  8641. const rgb = XYZ_TO_REC709.mul( xyz );
  8642. return rgb;
  8643. };
  8644. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  8645. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  8646. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  8647. // Evaluate the cosTheta on the base layer (Snell law)
  8648. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  8649. // Handle TIR:
  8650. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  8651. If( cosTheta2Sq.lessThan( 0 ), () => {
  8652. return vec3( 1.0 );
  8653. } );
  8654. const cosTheta2 = cosTheta2Sq.sqrt();
  8655. // First interface
  8656. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  8657. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  8658. //const R21 = R12;
  8659. const T121 = R12.oneMinus();
  8660. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  8661. const phi21 = float( Math.PI ).sub( phi12 );
  8662. // Second interface
  8663. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  8664. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  8665. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  8666. const phi23 = vec3(
  8667. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  8668. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  8669. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  8670. );
  8671. // Phase shift
  8672. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  8673. const phi = vec3( phi21 ).add( phi23 );
  8674. // Compound terms
  8675. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  8676. const r123 = R123.sqrt();
  8677. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  8678. // Reflectance term for m = 0 (DC term amplitude)
  8679. const C0 = R12.add( Rs );
  8680. const I = C0.toVar();
  8681. // Reflectance term for m > 0 (pairs of diracs)
  8682. const Cm = Rs.sub( T121 ).toVar();
  8683. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  8684. Cm.mulAssign( r123 );
  8685. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  8686. I.addAssign( Cm.mul( Sm ) );
  8687. } );
  8688. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  8689. return I.max( vec3( 0.0 ) );
  8690. } ).setLayout( {
  8691. name: 'evalIridescence',
  8692. type: 'vec3',
  8693. inputs: [
  8694. { name: 'outsideIOR', type: 'float' },
  8695. { name: 'eta2', type: 'float' },
  8696. { name: 'cosTheta1', type: 'float' },
  8697. { name: 'thinFilmThickness', type: 'float' },
  8698. { name: 'baseF0', type: 'vec3' }
  8699. ]
  8700. } );
  8701. //
  8702. // Sheen
  8703. //
  8704. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  8705. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  8706. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  8707. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  8708. const dotNV = normal.dot( viewDir ).saturate();
  8709. const r2 = roughness.pow2();
  8710. const a = select(
  8711. roughness.lessThan( 0.25 ),
  8712. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  8713. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  8714. );
  8715. const b = select(
  8716. roughness.lessThan( 0.25 ),
  8717. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  8718. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  8719. );
  8720. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  8721. return DG.mul( 1.0 / Math.PI ).saturate();
  8722. } );
  8723. const clearcoatF0 = vec3( 0.04 );
  8724. const clearcoatF90 = float( 1 );
  8725. /**
  8726. * Represents the lighting model for a PBR material.
  8727. *
  8728. * @augments LightingModel
  8729. */
  8730. class PhysicalLightingModel extends LightingModel {
  8731. /**
  8732. * Constructs a new physical lighting model.
  8733. *
  8734. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  8735. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  8736. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  8737. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  8738. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  8739. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  8740. */
  8741. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  8742. super();
  8743. /**
  8744. * Whether clearcoat is supported or not.
  8745. *
  8746. * @type {Boolean}
  8747. * @default false
  8748. */
  8749. this.clearcoat = clearcoat;
  8750. /**
  8751. * Whether sheen is supported or not.
  8752. *
  8753. * @type {Boolean}
  8754. * @default false
  8755. */
  8756. this.sheen = sheen;
  8757. /**
  8758. * Whether iridescence is supported or not.
  8759. *
  8760. * @type {Boolean}
  8761. * @default false
  8762. */
  8763. this.iridescence = iridescence;
  8764. /**
  8765. * Whether anisotropy is supported or not.
  8766. *
  8767. * @type {Boolean}
  8768. * @default false
  8769. */
  8770. this.anisotropy = anisotropy;
  8771. /**
  8772. * Whether transmission is supported or not.
  8773. *
  8774. * @type {Boolean}
  8775. * @default false
  8776. */
  8777. this.transmission = transmission;
  8778. /**
  8779. * Whether dispersion is supported or not.
  8780. *
  8781. * @type {Boolean}
  8782. * @default false
  8783. */
  8784. this.dispersion = dispersion;
  8785. /**
  8786. * The clear coat radiance.
  8787. *
  8788. * @type {Node?}
  8789. * @default null
  8790. */
  8791. this.clearcoatRadiance = null;
  8792. /**
  8793. * The clear coat specular direct.
  8794. *
  8795. * @type {Node?}
  8796. * @default null
  8797. */
  8798. this.clearcoatSpecularDirect = null;
  8799. /**
  8800. * The clear coat specular indirect.
  8801. *
  8802. * @type {Node?}
  8803. * @default null
  8804. */
  8805. this.clearcoatSpecularIndirect = null;
  8806. /**
  8807. * The sheen specular direct.
  8808. *
  8809. * @type {Node?}
  8810. * @default null
  8811. */
  8812. this.sheenSpecularDirect = null;
  8813. /**
  8814. * The sheen specular indirect.
  8815. *
  8816. * @type {Node?}
  8817. * @default null
  8818. */
  8819. this.sheenSpecularIndirect = null;
  8820. /**
  8821. * The iridescence Fresnel.
  8822. *
  8823. * @type {Node?}
  8824. * @default null
  8825. */
  8826. this.iridescenceFresnel = null;
  8827. /**
  8828. * The iridescence F0.
  8829. *
  8830. * @type {Node?}
  8831. * @default null
  8832. */
  8833. this.iridescenceF0 = null;
  8834. }
  8835. /**
  8836. * Depending on what features are requested, the method prepares certain node variables
  8837. * which are later used for lighting computations.
  8838. *
  8839. * @param {ContextNode} input - The current node context.
  8840. */
  8841. start( context ) {
  8842. if ( this.clearcoat === true ) {
  8843. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  8844. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  8845. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  8846. }
  8847. if ( this.sheen === true ) {
  8848. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  8849. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  8850. }
  8851. if ( this.iridescence === true ) {
  8852. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  8853. this.iridescenceFresnel = evalIridescence( {
  8854. outsideIOR: float( 1.0 ),
  8855. eta2: iridescenceIOR,
  8856. cosTheta1: dotNVi,
  8857. thinFilmThickness: iridescenceThickness,
  8858. baseF0: specularColor
  8859. } );
  8860. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  8861. }
  8862. if ( this.transmission === true ) {
  8863. const position = positionWorld;
  8864. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  8865. const n = transformedNormalWorld;
  8866. context.backdrop = getIBLVolumeRefraction(
  8867. n,
  8868. v,
  8869. roughness,
  8870. diffuseColor,
  8871. specularColor,
  8872. specularF90, // specularF90
  8873. position, // positionWorld
  8874. modelWorldMatrix, // modelMatrix
  8875. cameraViewMatrix, // viewMatrix
  8876. cameraProjectionMatrix, // projMatrix
  8877. ior,
  8878. thickness,
  8879. attenuationColor,
  8880. attenuationDistance,
  8881. this.dispersion ? dispersion : null
  8882. );
  8883. context.backdropAlpha = transmission;
  8884. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  8885. }
  8886. }
  8887. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  8888. // Approximates multi-scattering in order to preserve energy.
  8889. // http://www.jcgt.org/published/0008/01/03/
  8890. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  8891. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  8892. const fab = DFGApprox( { roughness, dotNV } );
  8893. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  8894. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  8895. const Ess = fab.x.add( fab.y );
  8896. const Ems = Ess.oneMinus();
  8897. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  8898. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  8899. singleScatter.addAssign( FssEss );
  8900. multiScatter.addAssign( Fms.mul( Ems ) );
  8901. }
  8902. /**
  8903. * Implements the direct light.
  8904. *
  8905. * @param {Object} input - The input data.
  8906. * @param {StackNode} stack - The current stack.
  8907. * @param {NodeBuilder} builder - The current node builder.
  8908. */
  8909. direct( { lightDirection, lightColor, reflectedLight } ) {
  8910. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  8911. const irradiance = dotNL.mul( lightColor );
  8912. if ( this.sheen === true ) {
  8913. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  8914. }
  8915. if ( this.clearcoat === true ) {
  8916. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  8917. const ccIrradiance = dotNLcc.mul( lightColor );
  8918. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  8919. }
  8920. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  8921. 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 } ) ) );
  8922. }
  8923. /**
  8924. * This method is intended for implementing the direct light term for
  8925. * rect area light nodes.
  8926. *
  8927. * @param {Object} input - The input data.
  8928. * @param {StackNode} stack - The current stack.
  8929. * @param {NodeBuilder} builder - The current node builder.
  8930. */
  8931. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  8932. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  8933. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  8934. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  8935. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  8936. const N = transformedNormalView;
  8937. const V = positionViewDirection;
  8938. const P = positionView.toVar();
  8939. const uv = LTC_Uv( { N, V, roughness } );
  8940. const t1 = ltc_1.sample( uv ).toVar();
  8941. const t2 = ltc_2.sample( uv ).toVar();
  8942. const mInv = mat3(
  8943. vec3( t1.x, 0, t1.y ),
  8944. vec3( 0, 1, 0 ),
  8945. vec3( t1.z, 0, t1.w )
  8946. ).toVar();
  8947. // LTC Fresnel Approximation by Stephen Hill
  8948. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  8949. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  8950. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  8951. 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 } ) ) );
  8952. }
  8953. /**
  8954. * Implements the indirect lighting.
  8955. *
  8956. * @param {ContextNode} input - The current node context.
  8957. * @param {StackNode} stack - The current stack.
  8958. * @param {NodeBuilder} builder - The current node builder.
  8959. */
  8960. indirect( context, stack, builder ) {
  8961. this.indirectDiffuse( context, stack, builder );
  8962. this.indirectSpecular( context, stack, builder );
  8963. this.ambientOcclusion( context, stack, builder );
  8964. }
  8965. /**
  8966. * Implements the indirect diffuse term.
  8967. *
  8968. * @param {ContextNode} input - The current node context.
  8969. * @param {StackNode} stack - The current stack.
  8970. * @param {NodeBuilder} builder - The current node builder.
  8971. */
  8972. indirectDiffuse( { irradiance, reflectedLight } ) {
  8973. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  8974. }
  8975. /**
  8976. * Implements the indirect specular term.
  8977. *
  8978. * @param {ContextNode} input - The current node context.
  8979. * @param {StackNode} stack - The current stack.
  8980. * @param {NodeBuilder} builder - The current node builder.
  8981. */
  8982. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  8983. if ( this.sheen === true ) {
  8984. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  8985. sheen,
  8986. IBLSheenBRDF( {
  8987. normal: transformedNormalView,
  8988. viewDir: positionViewDirection,
  8989. roughness: sheenRoughness
  8990. } )
  8991. ) );
  8992. }
  8993. if ( this.clearcoat === true ) {
  8994. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  8995. const clearcoatEnv = EnvironmentBRDF( {
  8996. dotNV: dotNVcc,
  8997. specularColor: clearcoatF0,
  8998. specularF90: clearcoatF90,
  8999. roughness: clearcoatRoughness
  9000. } );
  9001. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  9002. }
  9003. // Both indirect specular and indirect diffuse light accumulate here
  9004. const singleScattering = vec3().toVar( 'singleScattering' );
  9005. const multiScattering = vec3().toVar( 'multiScattering' );
  9006. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  9007. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  9008. const totalScattering = singleScattering.add( multiScattering );
  9009. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  9010. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  9011. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  9012. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  9013. }
  9014. /**
  9015. * Implements the ambient occlusion term.
  9016. *
  9017. * @param {ContextNode} input - The current node context.
  9018. * @param {StackNode} stack - The current stack.
  9019. * @param {NodeBuilder} builder - The current node builder.
  9020. */
  9021. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  9022. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  9023. const aoNV = dotNV.add( ambientOcclusion );
  9024. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  9025. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  9026. if ( this.clearcoat === true ) {
  9027. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  9028. }
  9029. if ( this.sheen === true ) {
  9030. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  9031. }
  9032. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  9033. reflectedLight.indirectSpecular.mulAssign( aoNode );
  9034. }
  9035. /**
  9036. * Used for final lighting accumulations depending on the requested features.
  9037. *
  9038. * @param {ContextNode} input - The current node context.
  9039. * @param {StackNode} stack - The current stack.
  9040. * @param {NodeBuilder} builder - The current node builder.
  9041. */
  9042. finish( context ) {
  9043. const { outgoingLight } = context;
  9044. if ( this.clearcoat === true ) {
  9045. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  9046. const Fcc = F_Schlick( {
  9047. dotVH: dotNVcc,
  9048. f0: clearcoatF0,
  9049. f90: clearcoatF90
  9050. } );
  9051. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  9052. outgoingLight.assign( clearcoatLight );
  9053. }
  9054. if ( this.sheen === true ) {
  9055. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  9056. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  9057. outgoingLight.assign( sheenLight );
  9058. }
  9059. }
  9060. }
  9061. // These defines must match with PMREMGenerator
  9062. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  9063. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  9064. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  9065. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  9066. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  9067. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  9068. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  9069. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  9070. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  9071. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  9072. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  9073. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  9074. // These shader functions convert between the UV coordinates of a single face of
  9075. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  9076. // sampling a textureCube (not generally normalized ).
  9077. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  9078. const absDirection = vec3( abs( direction ) ).toVar();
  9079. const face = float( - 1.0 ).toVar();
  9080. If( absDirection.x.greaterThan( absDirection.z ), () => {
  9081. If( absDirection.x.greaterThan( absDirection.y ), () => {
  9082. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  9083. } ).Else( () => {
  9084. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  9085. } );
  9086. } ).Else( () => {
  9087. If( absDirection.z.greaterThan( absDirection.y ), () => {
  9088. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  9089. } ).Else( () => {
  9090. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  9091. } );
  9092. } );
  9093. return face;
  9094. } ).setLayout( {
  9095. name: 'getFace',
  9096. type: 'float',
  9097. inputs: [
  9098. { name: 'direction', type: 'vec3' }
  9099. ]
  9100. } );
  9101. // RH coordinate system; PMREM face-indexing convention
  9102. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  9103. const uv = vec2().toVar();
  9104. If( face.equal( 0.0 ), () => {
  9105. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  9106. } ).ElseIf( face.equal( 1.0 ), () => {
  9107. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  9108. } ).ElseIf( face.equal( 2.0 ), () => {
  9109. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  9110. } ).ElseIf( face.equal( 3.0 ), () => {
  9111. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  9112. } ).ElseIf( face.equal( 4.0 ), () => {
  9113. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  9114. } ).Else( () => {
  9115. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  9116. } );
  9117. return mul( 0.5, uv.add( 1.0 ) );
  9118. } ).setLayout( {
  9119. name: 'getUV',
  9120. type: 'vec2',
  9121. inputs: [
  9122. { name: 'direction', type: 'vec3' },
  9123. { name: 'face', type: 'float' }
  9124. ]
  9125. } );
  9126. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  9127. const mip = float( 0.0 ).toVar();
  9128. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  9129. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  9130. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  9131. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  9132. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  9133. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  9134. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  9135. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  9136. } ).Else( () => {
  9137. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  9138. } );
  9139. return mip;
  9140. } ).setLayout( {
  9141. name: 'roughnessToMip',
  9142. type: 'float',
  9143. inputs: [
  9144. { name: 'roughness', type: 'float' }
  9145. ]
  9146. } );
  9147. // RH coordinate system; PMREM face-indexing convention
  9148. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  9149. const uv = uv_immutable.toVar();
  9150. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  9151. const direction = vec3( uv, 1.0 ).toVar();
  9152. If( face.equal( 0.0 ), () => {
  9153. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  9154. } ).ElseIf( face.equal( 1.0 ), () => {
  9155. direction.assign( direction.xzy );
  9156. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  9157. } ).ElseIf( face.equal( 2.0 ), () => {
  9158. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  9159. } ).ElseIf( face.equal( 3.0 ), () => {
  9160. direction.assign( direction.zyx );
  9161. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  9162. } ).ElseIf( face.equal( 4.0 ), () => {
  9163. direction.assign( direction.xzy );
  9164. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  9165. } ).ElseIf( face.equal( 5.0 ), () => {
  9166. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  9167. } );
  9168. return direction;
  9169. } ).setLayout( {
  9170. name: 'getDirection',
  9171. type: 'vec3',
  9172. inputs: [
  9173. { name: 'uv', type: 'vec2' },
  9174. { name: 'face', type: 'float' }
  9175. ]
  9176. } );
  9177. //
  9178. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  9179. const roughness = float( roughness_immutable );
  9180. const sampleDir = vec3( sampleDir_immutable );
  9181. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  9182. const mipF = fract( mip );
  9183. const mipInt = floor( mip );
  9184. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  9185. If( mipF.notEqual( 0.0 ), () => {
  9186. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  9187. color0.assign( mix( color0, color1, mipF ) );
  9188. } );
  9189. return color0;
  9190. } );
  9191. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  9192. const mipInt = float( mipInt_immutable ).toVar();
  9193. const direction = vec3( direction_immutable );
  9194. const face = float( getFace( direction ) ).toVar();
  9195. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  9196. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  9197. const faceSize = float( exp2( mipInt ) ).toVar();
  9198. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  9199. If( face.greaterThan( 2.0 ), () => {
  9200. uv.y.addAssign( faceSize );
  9201. face.subAssign( 3.0 );
  9202. } );
  9203. uv.x.addAssign( face.mul( faceSize ) );
  9204. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  9205. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  9206. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  9207. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  9208. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  9209. } );
  9210. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  9211. const cosTheta = cos( theta );
  9212. // Rodrigues' axis-angle rotation
  9213. const sampleDirection = outputDirection.mul( cosTheta )
  9214. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  9215. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  9216. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  9217. } );
  9218. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  9219. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  9220. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  9221. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  9222. } );
  9223. axis.assign( normalize( axis ) );
  9224. const gl_FragColor = vec3().toVar();
  9225. 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 } ) ) );
  9226. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  9227. If( i.greaterThanEqual( samples ), () => {
  9228. Break();
  9229. } );
  9230. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  9231. 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 } ) ) );
  9232. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  9233. } );
  9234. return vec4( gl_FragColor, 1 );
  9235. } );
  9236. let _generator = null;
  9237. const _cache = new WeakMap();
  9238. function _generateCubeUVSize( imageHeight ) {
  9239. const maxMip = Math.log2( imageHeight ) - 2;
  9240. const texelHeight = 1.0 / imageHeight;
  9241. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  9242. return { texelWidth, texelHeight, maxMip };
  9243. }
  9244. function _getPMREMFromTexture( texture ) {
  9245. let cacheTexture = _cache.get( texture );
  9246. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  9247. if ( pmremVersion !== texture.pmremVersion ) {
  9248. const image = texture.image;
  9249. if ( texture.isCubeTexture ) {
  9250. if ( isCubeMapReady( image ) ) {
  9251. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  9252. } else {
  9253. return null;
  9254. }
  9255. } else {
  9256. if ( isEquirectangularMapReady( image ) ) {
  9257. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  9258. } else {
  9259. return null;
  9260. }
  9261. }
  9262. cacheTexture.pmremVersion = texture.pmremVersion;
  9263. _cache.set( texture, cacheTexture );
  9264. }
  9265. return cacheTexture.texture;
  9266. }
  9267. class PMREMNode extends TempNode {
  9268. static get type() {
  9269. return 'PMREMNode';
  9270. }
  9271. constructor( value, uvNode = null, levelNode = null ) {
  9272. super( 'vec3' );
  9273. this._value = value;
  9274. this._pmrem = null;
  9275. this.uvNode = uvNode;
  9276. this.levelNode = levelNode;
  9277. this._generator = null;
  9278. const defaultTexture = new Texture();
  9279. defaultTexture.isRenderTargetTexture = true;
  9280. this._texture = texture( defaultTexture );
  9281. this._width = uniform( 0 );
  9282. this._height = uniform( 0 );
  9283. this._maxMip = uniform( 0 );
  9284. this.updateBeforeType = NodeUpdateType.RENDER;
  9285. }
  9286. set value( value ) {
  9287. this._value = value;
  9288. this._pmrem = null;
  9289. }
  9290. get value() {
  9291. return this._value;
  9292. }
  9293. updateFromTexture( texture ) {
  9294. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  9295. this._texture.value = texture;
  9296. this._width.value = cubeUVSize.texelWidth;
  9297. this._height.value = cubeUVSize.texelHeight;
  9298. this._maxMip.value = cubeUVSize.maxMip;
  9299. }
  9300. updateBefore() {
  9301. let pmrem = this._pmrem;
  9302. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  9303. const texture = this._value;
  9304. if ( pmremVersion !== texture.pmremVersion ) {
  9305. if ( texture.isPMREMTexture === true ) {
  9306. pmrem = texture;
  9307. } else {
  9308. pmrem = _getPMREMFromTexture( texture );
  9309. }
  9310. if ( pmrem !== null ) {
  9311. this._pmrem = pmrem;
  9312. this.updateFromTexture( pmrem );
  9313. }
  9314. }
  9315. }
  9316. setup( builder ) {
  9317. if ( _generator === null ) {
  9318. _generator = builder.createPMREMGenerator();
  9319. }
  9320. //
  9321. this.updateBefore( builder );
  9322. //
  9323. let uvNode = this.uvNode;
  9324. if ( uvNode === null && builder.context.getUV ) {
  9325. uvNode = builder.context.getUV( this );
  9326. }
  9327. //
  9328. const texture = this.value;
  9329. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  9330. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9331. }
  9332. //
  9333. let levelNode = this.levelNode;
  9334. if ( levelNode === null && builder.context.getTextureLevel ) {
  9335. levelNode = builder.context.getTextureLevel( this );
  9336. }
  9337. //
  9338. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  9339. }
  9340. }
  9341. function isCubeMapReady( image ) {
  9342. if ( image === null || image === undefined ) return false;
  9343. let count = 0;
  9344. const length = 6;
  9345. for ( let i = 0; i < length; i ++ ) {
  9346. if ( image[ i ] !== undefined ) count ++;
  9347. }
  9348. return count === length;
  9349. }
  9350. function isEquirectangularMapReady( image ) {
  9351. if ( image === null || image === undefined ) return false;
  9352. return image.height > 0;
  9353. }
  9354. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  9355. const _envNodeCache = new WeakMap();
  9356. class EnvironmentNode extends LightingNode {
  9357. static get type() {
  9358. return 'EnvironmentNode';
  9359. }
  9360. constructor( envNode = null ) {
  9361. super();
  9362. this.envNode = envNode;
  9363. }
  9364. setup( builder ) {
  9365. const { material } = builder;
  9366. let envNode = this.envNode;
  9367. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  9368. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  9369. let cacheEnvNode = _envNodeCache.get( value );
  9370. if ( cacheEnvNode === undefined ) {
  9371. cacheEnvNode = pmremTexture( value );
  9372. _envNodeCache.set( value, cacheEnvNode );
  9373. }
  9374. envNode = cacheEnvNode;
  9375. }
  9376. //
  9377. const envMap = material.envMap;
  9378. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  9379. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  9380. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  9381. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  9382. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  9383. const isolateRadiance = cache( radiance );
  9384. const isolateIrradiance = cache( irradiance );
  9385. //
  9386. builder.context.radiance.addAssign( isolateRadiance );
  9387. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  9388. //
  9389. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  9390. if ( clearcoatRadiance ) {
  9391. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  9392. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  9393. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  9394. }
  9395. }
  9396. }
  9397. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  9398. let reflectVec = null;
  9399. return {
  9400. getUV: () => {
  9401. if ( reflectVec === null ) {
  9402. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  9403. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  9404. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  9405. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  9406. }
  9407. return reflectVec;
  9408. },
  9409. getTextureLevel: () => {
  9410. return roughnessNode;
  9411. }
  9412. };
  9413. };
  9414. const createIrradianceContext = ( normalWorldNode ) => {
  9415. return {
  9416. getUV: () => {
  9417. return normalWorldNode;
  9418. },
  9419. getTextureLevel: () => {
  9420. return float( 1.0 );
  9421. }
  9422. };
  9423. };
  9424. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  9425. class MeshStandardNodeMaterial extends NodeMaterial {
  9426. static get type() {
  9427. return 'MeshStandardNodeMaterial';
  9428. }
  9429. constructor( parameters ) {
  9430. super();
  9431. this.isMeshStandardNodeMaterial = true;
  9432. this.lights = true;
  9433. this.emissiveNode = null;
  9434. this.metalnessNode = null;
  9435. this.roughnessNode = null;
  9436. this.setDefaultValues( _defaultValues$6 );
  9437. this.setValues( parameters );
  9438. }
  9439. setupEnvironment( builder ) {
  9440. let envNode = super.setupEnvironment( builder );
  9441. if ( envNode === null && builder.environmentNode ) {
  9442. envNode = builder.environmentNode;
  9443. }
  9444. return envNode ? new EnvironmentNode( envNode ) : null;
  9445. }
  9446. setupLightingModel( /*builder*/ ) {
  9447. return new PhysicalLightingModel();
  9448. }
  9449. setupSpecular() {
  9450. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  9451. specularColor.assign( specularColorNode );
  9452. specularF90.assign( 1.0 );
  9453. }
  9454. setupVariants() {
  9455. // METALNESS
  9456. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  9457. metalness.assign( metalnessNode );
  9458. // ROUGHNESS
  9459. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  9460. roughnessNode = getRoughness( { roughness: roughnessNode } );
  9461. roughness.assign( roughnessNode );
  9462. // SPECULAR COLOR
  9463. this.setupSpecular();
  9464. // DIFFUSE COLOR
  9465. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  9466. }
  9467. copy( source ) {
  9468. this.emissiveNode = source.emissiveNode;
  9469. this.metalnessNode = source.metalnessNode;
  9470. this.roughnessNode = source.roughnessNode;
  9471. return super.copy( source );
  9472. }
  9473. }
  9474. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  9475. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  9476. static get type() {
  9477. return 'MeshPhysicalNodeMaterial';
  9478. }
  9479. constructor( parameters ) {
  9480. super();
  9481. this.isMeshPhysicalNodeMaterial = true;
  9482. this.clearcoatNode = null;
  9483. this.clearcoatRoughnessNode = null;
  9484. this.clearcoatNormalNode = null;
  9485. this.sheenNode = null;
  9486. this.sheenRoughnessNode = null;
  9487. this.iridescenceNode = null;
  9488. this.iridescenceIORNode = null;
  9489. this.iridescenceThicknessNode = null;
  9490. this.specularIntensityNode = null;
  9491. this.specularColorNode = null;
  9492. this.iorNode = null;
  9493. this.transmissionNode = null;
  9494. this.thicknessNode = null;
  9495. this.attenuationDistanceNode = null;
  9496. this.attenuationColorNode = null;
  9497. this.dispersionNode = null;
  9498. this.anisotropyNode = null;
  9499. this.setDefaultValues( _defaultValues$5 );
  9500. this.setValues( parameters );
  9501. }
  9502. get useClearcoat() {
  9503. return this.clearcoat > 0 || this.clearcoatNode !== null;
  9504. }
  9505. get useIridescence() {
  9506. return this.iridescence > 0 || this.iridescenceNode !== null;
  9507. }
  9508. get useSheen() {
  9509. return this.sheen > 0 || this.sheenNode !== null;
  9510. }
  9511. get useAnisotropy() {
  9512. return this.anisotropy > 0 || this.anisotropyNode !== null;
  9513. }
  9514. get useTransmission() {
  9515. return this.transmission > 0 || this.transmissionNode !== null;
  9516. }
  9517. get useDispersion() {
  9518. return this.dispersion > 0 || this.dispersionNode !== null;
  9519. }
  9520. setupSpecular() {
  9521. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  9522. ior.assign( iorNode );
  9523. 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 ) );
  9524. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  9525. }
  9526. setupLightingModel( /*builder*/ ) {
  9527. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  9528. }
  9529. setupVariants( builder ) {
  9530. super.setupVariants( builder );
  9531. // CLEARCOAT
  9532. if ( this.useClearcoat ) {
  9533. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  9534. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  9535. clearcoat.assign( clearcoatNode );
  9536. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  9537. }
  9538. // SHEEN
  9539. if ( this.useSheen ) {
  9540. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  9541. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  9542. sheen.assign( sheenNode );
  9543. sheenRoughness.assign( sheenRoughnessNode );
  9544. }
  9545. // IRIDESCENCE
  9546. if ( this.useIridescence ) {
  9547. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  9548. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  9549. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  9550. iridescence.assign( iridescenceNode );
  9551. iridescenceIOR.assign( iridescenceIORNode );
  9552. iridescenceThickness.assign( iridescenceThicknessNode );
  9553. }
  9554. // ANISOTROPY
  9555. if ( this.useAnisotropy ) {
  9556. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  9557. anisotropy.assign( anisotropyV.length() );
  9558. If( anisotropy.equal( 0.0 ), () => {
  9559. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  9560. } ).Else( () => {
  9561. anisotropyV.divAssign( vec2( anisotropy ) );
  9562. anisotropy.assign( anisotropy.saturate() );
  9563. } );
  9564. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  9565. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  9566. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  9567. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  9568. }
  9569. // TRANSMISSION
  9570. if ( this.useTransmission ) {
  9571. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  9572. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  9573. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  9574. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  9575. transmission.assign( transmissionNode );
  9576. thickness.assign( thicknessNode );
  9577. attenuationDistance.assign( attenuationDistanceNode );
  9578. attenuationColor.assign( attenuationColorNode );
  9579. if ( this.useDispersion ) {
  9580. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  9581. dispersion.assign( dispersionNode );
  9582. }
  9583. }
  9584. }
  9585. setupClearcoatNormal() {
  9586. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  9587. }
  9588. setup( builder ) {
  9589. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  9590. super.setup( builder );
  9591. }
  9592. copy( source ) {
  9593. this.clearcoatNode = source.clearcoatNode;
  9594. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  9595. this.clearcoatNormalNode = source.clearcoatNormalNode;
  9596. this.sheenNode = source.sheenNode;
  9597. this.sheenRoughnessNode = source.sheenRoughnessNode;
  9598. this.iridescenceNode = source.iridescenceNode;
  9599. this.iridescenceIORNode = source.iridescenceIORNode;
  9600. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  9601. this.specularIntensityNode = source.specularIntensityNode;
  9602. this.specularColorNode = source.specularColorNode;
  9603. this.transmissionNode = source.transmissionNode;
  9604. this.thicknessNode = source.thicknessNode;
  9605. this.attenuationDistanceNode = source.attenuationDistanceNode;
  9606. this.attenuationColorNode = source.attenuationColorNode;
  9607. this.dispersionNode = source.dispersionNode;
  9608. this.anisotropyNode = source.anisotropyNode;
  9609. return super.copy( source );
  9610. }
  9611. }
  9612. class SSSLightingModel extends PhysicalLightingModel {
  9613. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  9614. super( useClearcoat, useSheen, useIridescence );
  9615. this.useSSS = useSSS;
  9616. }
  9617. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  9618. if ( this.useSSS === true ) {
  9619. const material = builder.material;
  9620. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  9621. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  9622. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  9623. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  9624. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  9625. }
  9626. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  9627. }
  9628. }
  9629. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  9630. static get type() {
  9631. return 'MeshSSSNodeMaterial';
  9632. }
  9633. constructor( parameters ) {
  9634. super( parameters );
  9635. this.thicknessColorNode = null;
  9636. this.thicknessDistortionNode = float( 0.1 );
  9637. this.thicknessAmbientNode = float( 0.0 );
  9638. this.thicknessAttenuationNode = float( .1 );
  9639. this.thicknessPowerNode = float( 2.0 );
  9640. this.thicknessScaleNode = float( 10.0 );
  9641. }
  9642. get useSSS() {
  9643. return this.thicknessColorNode !== null;
  9644. }
  9645. setupLightingModel( /*builder*/ ) {
  9646. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  9647. }
  9648. copy( source ) {
  9649. this.thicknessColorNode = source.thicknessColorNode;
  9650. this.thicknessDistortionNode = source.thicknessDistortionNode;
  9651. this.thicknessAmbientNode = source.thicknessAmbientNode;
  9652. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  9653. this.thicknessPowerNode = source.thicknessPowerNode;
  9654. this.thicknessScaleNode = source.thicknessScaleNode;
  9655. return super.copy( source );
  9656. }
  9657. }
  9658. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  9659. // dotNL will be from -1.0 to 1.0
  9660. const dotNL = normal.dot( lightDirection );
  9661. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  9662. if ( builder.material.gradientMap ) {
  9663. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  9664. return vec3( gradientMap.r );
  9665. } else {
  9666. const fw = coord.fwidth().mul( 0.5 );
  9667. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  9668. }
  9669. } );
  9670. /**
  9671. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  9672. *
  9673. * @augments LightingModel
  9674. */
  9675. class ToonLightingModel extends LightingModel {
  9676. /**
  9677. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  9678. * reduced to a small number of discrete shades to create a comic-like, flat look.
  9679. *
  9680. * @param {Object} input - The input data.
  9681. * @param {StackNode} stack - The current stack.
  9682. * @param {NodeBuilder} builder - The current node builder.
  9683. */
  9684. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  9685. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  9686. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  9687. }
  9688. /**
  9689. * Implements the indirect lighting.
  9690. *
  9691. * @param {ContextNode} input - The current node context.
  9692. * @param {StackNode} stack - The current stack.
  9693. * @param {NodeBuilder} builder - The current node builder.
  9694. */
  9695. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  9696. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  9697. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  9698. }
  9699. }
  9700. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  9701. class MeshToonNodeMaterial extends NodeMaterial {
  9702. static get type() {
  9703. return 'MeshToonNodeMaterial';
  9704. }
  9705. constructor( parameters ) {
  9706. super();
  9707. this.isMeshToonNodeMaterial = true;
  9708. this.lights = true;
  9709. this.setDefaultValues( _defaultValues$4 );
  9710. this.setValues( parameters );
  9711. }
  9712. setupLightingModel( /*builder*/ ) {
  9713. return new ToonLightingModel();
  9714. }
  9715. }
  9716. /**
  9717. * Can be used to compute texture coordinates for projecting a
  9718. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  9719. *
  9720. * @augments TempNode
  9721. */
  9722. class MatcapUVNode extends TempNode {
  9723. static get type() {
  9724. return 'MatcapUVNode';
  9725. }
  9726. /**
  9727. * Constructs a new matcap uv node.
  9728. */
  9729. constructor() {
  9730. super( 'vec2' );
  9731. }
  9732. setup() {
  9733. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  9734. const y = positionViewDirection.cross( x );
  9735. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  9736. }
  9737. }
  9738. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  9739. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  9740. class MeshMatcapNodeMaterial extends NodeMaterial {
  9741. static get type() {
  9742. return 'MeshMatcapNodeMaterial';
  9743. }
  9744. constructor( parameters ) {
  9745. super();
  9746. this.lights = false;
  9747. this.isMeshMatcapNodeMaterial = true;
  9748. this.setDefaultValues( _defaultValues$3 );
  9749. this.setValues( parameters );
  9750. }
  9751. setupVariants( builder ) {
  9752. const uv = matcapUV;
  9753. let matcapColor;
  9754. if ( builder.material.matcap ) {
  9755. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  9756. } else {
  9757. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  9758. }
  9759. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  9760. }
  9761. }
  9762. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  9763. class PointsNodeMaterial extends NodeMaterial {
  9764. static get type() {
  9765. return 'PointsNodeMaterial';
  9766. }
  9767. constructor( parameters ) {
  9768. super();
  9769. this.isPointsNodeMaterial = true;
  9770. this.lights = false;
  9771. this.transparent = true;
  9772. this.sizeNode = null;
  9773. this.setDefaultValues( _defaultValues$2 );
  9774. this.setValues( parameters );
  9775. }
  9776. copy( source ) {
  9777. this.sizeNode = source.sizeNode;
  9778. return super.copy( source );
  9779. }
  9780. }
  9781. /**
  9782. * Applies a rotation to the given position node.
  9783. *
  9784. * @augments TempNode
  9785. */
  9786. class RotateNode extends TempNode {
  9787. static get type() {
  9788. return 'RotateNode';
  9789. }
  9790. /**
  9791. * Constructs a new rotate node.
  9792. *
  9793. * @param {Node} positionNode - The position node.
  9794. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  9795. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  9796. */
  9797. constructor( positionNode, rotationNode ) {
  9798. super();
  9799. /**
  9800. * The position node.
  9801. *
  9802. * @type {Node}
  9803. */
  9804. this.positionNode = positionNode;
  9805. /**
  9806. * Represents the rotation that is applied to the position node.
  9807. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  9808. *
  9809. * @type {Node}
  9810. */
  9811. this.rotationNode = rotationNode;
  9812. }
  9813. /**
  9814. * The type of the {@link RotateNode#positionNode} defines the node's type.
  9815. *
  9816. * @param {NodeBuilder} builder - The current node builder.
  9817. * @return {String} The node's type.
  9818. */
  9819. getNodeType( builder ) {
  9820. return this.positionNode.getNodeType( builder );
  9821. }
  9822. setup( builder ) {
  9823. const { rotationNode, positionNode } = this;
  9824. const nodeType = this.getNodeType( builder );
  9825. if ( nodeType === 'vec2' ) {
  9826. const cosAngle = rotationNode.cos();
  9827. const sinAngle = rotationNode.sin();
  9828. const rotationMatrix = mat2(
  9829. cosAngle, sinAngle,
  9830. sinAngle.negate(), cosAngle
  9831. );
  9832. return rotationMatrix.mul( positionNode );
  9833. } else {
  9834. const rotation = rotationNode;
  9835. 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 ) );
  9836. 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 ) );
  9837. 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 ) );
  9838. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  9839. }
  9840. }
  9841. }
  9842. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  9843. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  9844. class SpriteNodeMaterial extends NodeMaterial {
  9845. static get type() {
  9846. return 'SpriteNodeMaterial';
  9847. }
  9848. constructor( parameters ) {
  9849. super();
  9850. this.isSpriteNodeMaterial = true;
  9851. this.lights = false;
  9852. this._useSizeAttenuation = true;
  9853. this.positionNode = null;
  9854. this.rotationNode = null;
  9855. this.scaleNode = null;
  9856. this.setDefaultValues( _defaultValues$1 );
  9857. this.setValues( parameters );
  9858. }
  9859. setupPosition( { object, camera, context } ) {
  9860. const sizeAttenuation = this.sizeAttenuation;
  9861. // < VERTEX STAGE >
  9862. const { positionNode, rotationNode, scaleNode } = this;
  9863. const vertex = positionLocal;
  9864. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  9865. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  9866. if ( scaleNode !== null ) {
  9867. scale = scale.mul( scaleNode );
  9868. }
  9869. if ( ! sizeAttenuation ) {
  9870. if ( camera.isPerspectiveCamera ) {
  9871. scale = scale.mul( mvPosition.z.negate() );
  9872. } else {
  9873. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  9874. scale = scale.mul( orthoScale.mul( 2 ) );
  9875. }
  9876. }
  9877. let alignedPosition = vertex.xy;
  9878. if ( object.center && object.center.isVector2 === true ) {
  9879. const center = reference$1( 'center', 'vec2' );
  9880. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  9881. }
  9882. alignedPosition = alignedPosition.mul( scale );
  9883. const rotation = float( rotationNode || materialRotation );
  9884. const rotatedPosition = rotate( alignedPosition, rotation );
  9885. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  9886. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  9887. context.vertex = vertex;
  9888. return modelViewProjection;
  9889. }
  9890. copy( source ) {
  9891. this.positionNode = source.positionNode;
  9892. this.rotationNode = source.rotationNode;
  9893. this.scaleNode = source.scaleNode;
  9894. return super.copy( source );
  9895. }
  9896. get sizeAttenuation() {
  9897. return this._useSizeAttenuation;
  9898. }
  9899. set sizeAttenuation( value ) {
  9900. if ( this._useSizeAttenuation !== value ) {
  9901. this._useSizeAttenuation = value;
  9902. this.needsUpdate = true;
  9903. }
  9904. }
  9905. }
  9906. /**
  9907. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  9908. *
  9909. * @augments LightingModel
  9910. */
  9911. class ShadowMaskModel extends LightingModel {
  9912. /**
  9913. * Constructs a new shadow mask model.
  9914. */
  9915. constructor() {
  9916. super();
  9917. /**
  9918. * The shadow mask node.
  9919. *
  9920. * @type {Node}
  9921. */
  9922. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  9923. }
  9924. /**
  9925. * Only used to save the shadow mask.
  9926. *
  9927. * @param {Object} input - The input data.
  9928. */
  9929. direct( { shadowMask } ) {
  9930. this.shadowNode.mulAssign( shadowMask );
  9931. }
  9932. /**
  9933. * Uses the shadow mask to produce the final color.
  9934. *
  9935. * @param {ContextNode} input - The current node context.
  9936. */
  9937. finish( context ) {
  9938. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  9939. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  9940. }
  9941. }
  9942. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  9943. class ShadowNodeMaterial extends NodeMaterial {
  9944. static get type() {
  9945. return 'ShadowNodeMaterial';
  9946. }
  9947. constructor( parameters ) {
  9948. super();
  9949. this.isShadowNodeMaterial = true;
  9950. this.lights = true;
  9951. this.setDefaultValues( _defaultValues );
  9952. this.setValues( parameters );
  9953. }
  9954. setupLightingModel( /*builder*/ ) {
  9955. return new ShadowMaskModel();
  9956. }
  9957. }
  9958. const normal = Fn( ( { texture, uv } ) => {
  9959. const epsilon = 0.0001;
  9960. const ret = vec3().toVar();
  9961. If( uv.x.lessThan( epsilon ), () => {
  9962. ret.assign( vec3( 1, 0, 0 ) );
  9963. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  9964. ret.assign( vec3( 0, 1, 0 ) );
  9965. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  9966. ret.assign( vec3( 0, 0, 1 ) );
  9967. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  9968. ret.assign( vec3( - 1, 0, 0 ) );
  9969. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  9970. ret.assign( vec3( 0, - 1, 0 ) );
  9971. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  9972. ret.assign( vec3( 0, 0, - 1 ) );
  9973. } ).Else( () => {
  9974. const step = 0.01;
  9975. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  9976. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  9977. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  9978. ret.assign( vec3( x, y, z ) );
  9979. } );
  9980. return ret.normalize();
  9981. } );
  9982. class Texture3DNode extends TextureNode {
  9983. static get type() {
  9984. return 'Texture3DNode';
  9985. }
  9986. constructor( value, uvNode = null, levelNode = null ) {
  9987. super( value, uvNode, levelNode );
  9988. this.isTexture3DNode = true;
  9989. }
  9990. getInputType( /*builder*/ ) {
  9991. return 'texture3D';
  9992. }
  9993. getDefaultUV() {
  9994. return vec3( 0.5, 0.5, 0.5 );
  9995. }
  9996. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  9997. setupUV( builder, uvNode ) {
  9998. return uvNode;
  9999. }
  10000. generateUV( builder, uvNode ) {
  10001. return uvNode.build( builder, 'vec3' );
  10002. }
  10003. normal( uvNode ) {
  10004. return normal( { texture: this, uv: uvNode } );
  10005. }
  10006. }
  10007. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  10008. class VolumeNodeMaterial extends NodeMaterial {
  10009. static get type() {
  10010. return 'VolumeNodeMaterial';
  10011. }
  10012. constructor( params = {} ) {
  10013. super();
  10014. this.lights = false;
  10015. this.isVolumeNodeMaterial = true;
  10016. this.testNode = null;
  10017. this.setValues( params );
  10018. }
  10019. setup( builder ) {
  10020. const map = texture3D( this.map, null, 0 );
  10021. const hitBox = Fn( ( { orig, dir } ) => {
  10022. const box_min = vec3( - 0.5 );
  10023. const box_max = vec3( 0.5 );
  10024. const inv_dir = dir.reciprocal();
  10025. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  10026. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  10027. const tmin = min$1( tmin_tmp, tmax_tmp );
  10028. const tmax = max$1( tmin_tmp, tmax_tmp );
  10029. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  10030. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  10031. return vec2( t0, t1 );
  10032. } );
  10033. this.fragmentNode = Fn( () => {
  10034. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  10035. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  10036. const rayDir = vDirection.normalize();
  10037. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  10038. bounds.x.greaterThan( bounds.y ).discard();
  10039. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  10040. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  10041. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  10042. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  10043. delta.divAssign( materialReference( 'steps', 'float' ) );
  10044. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  10045. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  10046. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  10047. if ( this.testNode !== null ) {
  10048. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  10049. } else {
  10050. // default to show surface of mesh
  10051. ac.a.assign( 1 );
  10052. Break();
  10053. }
  10054. p.addAssign( rayDir.mul( delta ) );
  10055. } );
  10056. ac.a.equal( 0 ).discard();
  10057. return vec4( ac );
  10058. } )();
  10059. super.setup( builder );
  10060. }
  10061. }
  10062. class Animation {
  10063. constructor( nodes, info ) {
  10064. this.nodes = nodes;
  10065. this.info = info;
  10066. this._context = self;
  10067. this._animationLoop = null;
  10068. this._requestId = null;
  10069. }
  10070. start() {
  10071. const update = ( time, frame ) => {
  10072. this._requestId = this._context.requestAnimationFrame( update );
  10073. if ( this.info.autoReset === true ) this.info.reset();
  10074. this.nodes.nodeFrame.update();
  10075. this.info.frame = this.nodes.nodeFrame.frameId;
  10076. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  10077. };
  10078. update();
  10079. }
  10080. stop() {
  10081. this._context.cancelAnimationFrame( this._requestId );
  10082. this._requestId = null;
  10083. }
  10084. setAnimationLoop( callback ) {
  10085. this._animationLoop = callback;
  10086. }
  10087. setContext( context ) {
  10088. this._context = context;
  10089. }
  10090. dispose() {
  10091. this.stop();
  10092. }
  10093. }
  10094. class ChainMap {
  10095. constructor() {
  10096. this.weakMap = new WeakMap();
  10097. }
  10098. get( keys ) {
  10099. let map = this.weakMap;
  10100. for ( let i = 0; i < keys.length; i ++ ) {
  10101. map = map.get( keys[ i ] );
  10102. if ( map === undefined ) return undefined;
  10103. }
  10104. return map.get( keys[ keys.length - 1 ] );
  10105. }
  10106. set( keys, value ) {
  10107. let map = this.weakMap;
  10108. for ( let i = 0; i < keys.length; i ++ ) {
  10109. const key = keys[ i ];
  10110. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  10111. map = map.get( key );
  10112. }
  10113. return map.set( keys[ keys.length - 1 ], value );
  10114. }
  10115. delete( keys ) {
  10116. let map = this.weakMap;
  10117. for ( let i = 0; i < keys.length; i ++ ) {
  10118. map = map.get( keys[ i ] );
  10119. if ( map === undefined ) return false;
  10120. }
  10121. return map.delete( keys[ keys.length - 1 ] );
  10122. }
  10123. }
  10124. let _id$8 = 0;
  10125. function getKeys( obj ) {
  10126. const keys = Object.keys( obj );
  10127. let proto = Object.getPrototypeOf( obj );
  10128. while ( proto ) {
  10129. const descriptors = Object.getOwnPropertyDescriptors( proto );
  10130. for ( const key in descriptors ) {
  10131. if ( descriptors[ key ] !== undefined ) {
  10132. const descriptor = descriptors[ key ];
  10133. if ( descriptor && typeof descriptor.get === 'function' ) {
  10134. keys.push( key );
  10135. }
  10136. }
  10137. }
  10138. proto = Object.getPrototypeOf( proto );
  10139. }
  10140. return keys;
  10141. }
  10142. class RenderObject {
  10143. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  10144. this._nodes = nodes;
  10145. this._geometries = geometries;
  10146. this.id = _id$8 ++;
  10147. this.renderer = renderer;
  10148. this.object = object;
  10149. this.material = material;
  10150. this.scene = scene;
  10151. this.camera = camera;
  10152. this.lightsNode = lightsNode;
  10153. this.context = renderContext;
  10154. this.geometry = object.geometry;
  10155. this.version = material.version;
  10156. this.drawRange = null;
  10157. this.attributes = null;
  10158. this.pipeline = null;
  10159. this.vertexBuffers = null;
  10160. this.drawParams = null;
  10161. this.bundle = null;
  10162. this.clippingContext = clippingContext;
  10163. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  10164. this.initialNodesCacheKey = this.getDynamicCacheKey();
  10165. this.initialCacheKey = this.getCacheKey();
  10166. this._nodeBuilderState = null;
  10167. this._bindings = null;
  10168. this._monitor = null;
  10169. this.onDispose = null;
  10170. this.isRenderObject = true;
  10171. this.onMaterialDispose = () => {
  10172. this.dispose();
  10173. };
  10174. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  10175. }
  10176. updateClipping( parent ) {
  10177. this.clippingContext = parent;
  10178. }
  10179. get clippingNeedsUpdate() {
  10180. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  10181. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  10182. return true;
  10183. }
  10184. get hardwareClippingPlanes() {
  10185. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  10186. }
  10187. getNodeBuilderState() {
  10188. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  10189. }
  10190. getMonitor() {
  10191. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  10192. }
  10193. getBindings() {
  10194. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  10195. }
  10196. getIndex() {
  10197. return this._geometries.getIndex( this );
  10198. }
  10199. getIndirect() {
  10200. return this._geometries.getIndirect( this );
  10201. }
  10202. getChainArray() {
  10203. return [ this.object, this.material, this.context, this.lightsNode ];
  10204. }
  10205. setGeometry( geometry ) {
  10206. this.geometry = geometry;
  10207. this.attributes = null;
  10208. }
  10209. getAttributes() {
  10210. if ( this.attributes !== null ) return this.attributes;
  10211. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  10212. const geometry = this.geometry;
  10213. const attributes = [];
  10214. const vertexBuffers = new Set();
  10215. for ( const nodeAttribute of nodeAttributes ) {
  10216. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  10217. if ( attribute === undefined ) continue;
  10218. attributes.push( attribute );
  10219. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  10220. vertexBuffers.add( bufferAttribute );
  10221. }
  10222. this.attributes = attributes;
  10223. this.vertexBuffers = Array.from( vertexBuffers.values() );
  10224. return attributes;
  10225. }
  10226. getVertexBuffers() {
  10227. if ( this.vertexBuffers === null ) this.getAttributes();
  10228. return this.vertexBuffers;
  10229. }
  10230. getDrawParameters() {
  10231. const { object, material, geometry, group, drawRange } = this;
  10232. const drawParams = this.drawParams || ( this.drawParams = {
  10233. vertexCount: 0,
  10234. firstVertex: 0,
  10235. instanceCount: 0,
  10236. firstInstance: 0
  10237. } );
  10238. const index = this.getIndex();
  10239. const hasIndex = ( index !== null );
  10240. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  10241. if ( instanceCount === 0 ) return null;
  10242. drawParams.instanceCount = instanceCount;
  10243. if ( object.isBatchedMesh === true ) return drawParams;
  10244. let rangeFactor = 1;
  10245. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  10246. rangeFactor = 2;
  10247. }
  10248. let firstVertex = drawRange.start * rangeFactor;
  10249. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  10250. if ( group !== null ) {
  10251. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  10252. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  10253. }
  10254. const position = geometry.attributes.position;
  10255. let itemCount = Infinity;
  10256. if ( hasIndex ) {
  10257. itemCount = index.count;
  10258. } else if ( position !== undefined && position !== null ) {
  10259. itemCount = position.count;
  10260. }
  10261. firstVertex = Math.max( firstVertex, 0 );
  10262. lastVertex = Math.min( lastVertex, itemCount );
  10263. const count = lastVertex - firstVertex;
  10264. if ( count < 0 || count === Infinity ) return null;
  10265. drawParams.vertexCount = count;
  10266. drawParams.firstVertex = firstVertex;
  10267. return drawParams;
  10268. }
  10269. getGeometryCacheKey() {
  10270. const { geometry } = this;
  10271. let cacheKey = '';
  10272. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  10273. const attribute = geometry.attributes[ name ];
  10274. cacheKey += name + ',';
  10275. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  10276. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  10277. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  10278. if ( attribute.normalized ) cacheKey += 'n,';
  10279. }
  10280. if ( geometry.index ) {
  10281. cacheKey += 'index,';
  10282. }
  10283. return cacheKey;
  10284. }
  10285. getMaterialCacheKey() {
  10286. const { object, material } = this;
  10287. let cacheKey = material.customProgramCacheKey();
  10288. for ( const property of getKeys( material ) ) {
  10289. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  10290. const value = material[ property ];
  10291. let valueKey;
  10292. if ( value !== null ) {
  10293. // some material values require a formatting
  10294. const type = typeof value;
  10295. if ( type === 'number' ) {
  10296. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  10297. } else if ( type === 'object' ) {
  10298. valueKey = '{';
  10299. if ( value.isTexture ) {
  10300. valueKey += value.mapping;
  10301. }
  10302. valueKey += '}';
  10303. } else {
  10304. valueKey = String( value );
  10305. }
  10306. } else {
  10307. valueKey = String( value );
  10308. }
  10309. cacheKey += /*property + ':' +*/ valueKey + ',';
  10310. }
  10311. cacheKey += this.clippingContextCacheKey + ',';
  10312. if ( object.geometry ) {
  10313. cacheKey += this.getGeometryCacheKey();
  10314. }
  10315. if ( object.skeleton ) {
  10316. cacheKey += object.skeleton.bones.length + ',';
  10317. }
  10318. if ( object.morphTargetInfluences ) {
  10319. cacheKey += object.morphTargetInfluences.length + ',';
  10320. }
  10321. if ( object.isBatchedMesh ) {
  10322. cacheKey += object._matricesTexture.uuid + ',';
  10323. if ( object._colorsTexture !== null ) {
  10324. cacheKey += object._colorsTexture.uuid + ',';
  10325. }
  10326. }
  10327. if ( object.count > 1 ) {
  10328. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  10329. cacheKey += object.uuid + ',';
  10330. }
  10331. cacheKey += object.receiveShadow + ',';
  10332. return hashString( cacheKey );
  10333. }
  10334. get needsGeometryUpdate() {
  10335. return this.geometry.id !== this.object.geometry.id;
  10336. }
  10337. get needsUpdate() {
  10338. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  10339. }
  10340. getDynamicCacheKey() {
  10341. // Environment Nodes Cache Key
  10342. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  10343. if ( this.object.receiveShadow ) {
  10344. cacheKey += 1;
  10345. }
  10346. return cacheKey;
  10347. }
  10348. getCacheKey() {
  10349. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  10350. }
  10351. dispose() {
  10352. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  10353. this.onDispose();
  10354. }
  10355. }
  10356. const chainArray = [];
  10357. class RenderObjects {
  10358. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  10359. this.renderer = renderer;
  10360. this.nodes = nodes;
  10361. this.geometries = geometries;
  10362. this.pipelines = pipelines;
  10363. this.bindings = bindings;
  10364. this.info = info;
  10365. this.chainMaps = {};
  10366. }
  10367. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  10368. const chainMap = this.getChainMap( passId );
  10369. // reuse chainArray
  10370. chainArray[ 0 ] = object;
  10371. chainArray[ 1 ] = material;
  10372. chainArray[ 2 ] = renderContext;
  10373. chainArray[ 3 ] = lightsNode;
  10374. let renderObject = chainMap.get( chainArray );
  10375. if ( renderObject === undefined ) {
  10376. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  10377. chainMap.set( chainArray, renderObject );
  10378. } else {
  10379. renderObject.updateClipping( clippingContext );
  10380. if ( renderObject.needsGeometryUpdate ) {
  10381. renderObject.setGeometry( object.geometry );
  10382. }
  10383. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  10384. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  10385. renderObject.dispose();
  10386. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  10387. } else {
  10388. renderObject.version = material.version;
  10389. }
  10390. }
  10391. }
  10392. return renderObject;
  10393. }
  10394. getChainMap( passId = 'default' ) {
  10395. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  10396. }
  10397. dispose() {
  10398. this.chainMaps = {};
  10399. }
  10400. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  10401. const chainMap = this.getChainMap( passId );
  10402. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  10403. renderObject.onDispose = () => {
  10404. this.pipelines.delete( renderObject );
  10405. this.bindings.delete( renderObject );
  10406. this.nodes.delete( renderObject );
  10407. chainMap.delete( renderObject.getChainArray() );
  10408. };
  10409. return renderObject;
  10410. }
  10411. }
  10412. class DataMap {
  10413. constructor() {
  10414. this.data = new WeakMap();
  10415. }
  10416. get( object ) {
  10417. let map = this.data.get( object );
  10418. if ( map === undefined ) {
  10419. map = {};
  10420. this.data.set( object, map );
  10421. }
  10422. return map;
  10423. }
  10424. delete( object ) {
  10425. let map;
  10426. if ( this.data.has( object ) ) {
  10427. map = this.data.get( object );
  10428. this.data.delete( object );
  10429. }
  10430. return map;
  10431. }
  10432. has( object ) {
  10433. return this.data.has( object );
  10434. }
  10435. dispose() {
  10436. this.data = new WeakMap();
  10437. }
  10438. }
  10439. const AttributeType = {
  10440. VERTEX: 1,
  10441. INDEX: 2,
  10442. STORAGE: 3,
  10443. INDIRECT: 4
  10444. };
  10445. // size of a chunk in bytes (STD140 layout)
  10446. const GPU_CHUNK_BYTES = 16;
  10447. // @TODO: Move to src/constants.js
  10448. const BlendColorFactor = 211;
  10449. const OneMinusBlendColorFactor = 212;
  10450. class Attributes extends DataMap {
  10451. constructor( backend ) {
  10452. super();
  10453. this.backend = backend;
  10454. }
  10455. delete( attribute ) {
  10456. const attributeData = super.delete( attribute );
  10457. if ( attributeData !== undefined ) {
  10458. this.backend.destroyAttribute( attribute );
  10459. }
  10460. return attributeData;
  10461. }
  10462. update( attribute, type ) {
  10463. const data = this.get( attribute );
  10464. if ( data.version === undefined ) {
  10465. if ( type === AttributeType.VERTEX ) {
  10466. this.backend.createAttribute( attribute );
  10467. } else if ( type === AttributeType.INDEX ) {
  10468. this.backend.createIndexAttribute( attribute );
  10469. } else if ( type === AttributeType.STORAGE ) {
  10470. this.backend.createStorageAttribute( attribute );
  10471. } else if ( type === AttributeType.INDIRECT ) {
  10472. this.backend.createIndirectStorageAttribute( attribute );
  10473. }
  10474. data.version = this._getBufferAttribute( attribute ).version;
  10475. } else {
  10476. const bufferAttribute = this._getBufferAttribute( attribute );
  10477. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  10478. this.backend.updateAttribute( attribute );
  10479. data.version = bufferAttribute.version;
  10480. }
  10481. }
  10482. }
  10483. _getBufferAttribute( attribute ) {
  10484. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10485. return attribute;
  10486. }
  10487. }
  10488. function arrayNeedsUint32( array ) {
  10489. // assumes larger values usually on last
  10490. for ( let i = array.length - 1; i >= 0; -- i ) {
  10491. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  10492. }
  10493. return false;
  10494. }
  10495. function getWireframeVersion( geometry ) {
  10496. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  10497. }
  10498. function getWireframeIndex( geometry ) {
  10499. const indices = [];
  10500. const geometryIndex = geometry.index;
  10501. const geometryPosition = geometry.attributes.position;
  10502. if ( geometryIndex !== null ) {
  10503. const array = geometryIndex.array;
  10504. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10505. const a = array[ i + 0 ];
  10506. const b = array[ i + 1 ];
  10507. const c = array[ i + 2 ];
  10508. indices.push( a, b, b, c, c, a );
  10509. }
  10510. } else {
  10511. const array = geometryPosition.array;
  10512. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10513. const a = i + 0;
  10514. const b = i + 1;
  10515. const c = i + 2;
  10516. indices.push( a, b, b, c, c, a );
  10517. }
  10518. }
  10519. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10520. attribute.version = getWireframeVersion( geometry );
  10521. return attribute;
  10522. }
  10523. class Geometries extends DataMap {
  10524. constructor( attributes, info ) {
  10525. super();
  10526. this.attributes = attributes;
  10527. this.info = info;
  10528. this.wireframes = new WeakMap();
  10529. this.attributeCall = new WeakMap();
  10530. }
  10531. has( renderObject ) {
  10532. const geometry = renderObject.geometry;
  10533. return super.has( geometry ) && this.get( geometry ).initialized === true;
  10534. }
  10535. updateForRender( renderObject ) {
  10536. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  10537. this.updateAttributes( renderObject );
  10538. }
  10539. initGeometry( renderObject ) {
  10540. const geometry = renderObject.geometry;
  10541. const geometryData = this.get( geometry );
  10542. geometryData.initialized = true;
  10543. this.info.memory.geometries ++;
  10544. const onDispose = () => {
  10545. this.info.memory.geometries --;
  10546. const index = geometry.index;
  10547. const geometryAttributes = renderObject.getAttributes();
  10548. if ( index !== null ) {
  10549. this.attributes.delete( index );
  10550. }
  10551. for ( const geometryAttribute of geometryAttributes ) {
  10552. this.attributes.delete( geometryAttribute );
  10553. }
  10554. const wireframeAttribute = this.wireframes.get( geometry );
  10555. if ( wireframeAttribute !== undefined ) {
  10556. this.attributes.delete( wireframeAttribute );
  10557. }
  10558. geometry.removeEventListener( 'dispose', onDispose );
  10559. };
  10560. geometry.addEventListener( 'dispose', onDispose );
  10561. }
  10562. updateAttributes( renderObject ) {
  10563. // attributes
  10564. const attributes = renderObject.getAttributes();
  10565. for ( const attribute of attributes ) {
  10566. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  10567. this.updateAttribute( attribute, AttributeType.STORAGE );
  10568. } else {
  10569. this.updateAttribute( attribute, AttributeType.VERTEX );
  10570. }
  10571. }
  10572. // indexes
  10573. const index = this.getIndex( renderObject );
  10574. if ( index !== null ) {
  10575. this.updateAttribute( index, AttributeType.INDEX );
  10576. }
  10577. // indirect
  10578. const indirect = renderObject.geometry.indirect;
  10579. if ( indirect !== null ) {
  10580. this.updateAttribute( indirect, AttributeType.INDIRECT );
  10581. }
  10582. }
  10583. updateAttribute( attribute, type ) {
  10584. const callId = this.info.render.calls;
  10585. if ( ! attribute.isInterleavedBufferAttribute ) {
  10586. if ( this.attributeCall.get( attribute ) !== callId ) {
  10587. this.attributes.update( attribute, type );
  10588. this.attributeCall.set( attribute, callId );
  10589. }
  10590. } else {
  10591. if ( this.attributeCall.get( attribute ) === undefined ) {
  10592. this.attributes.update( attribute, type );
  10593. this.attributeCall.set( attribute, callId );
  10594. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  10595. this.attributes.update( attribute, type );
  10596. this.attributeCall.set( attribute.data, callId );
  10597. this.attributeCall.set( attribute, callId );
  10598. }
  10599. }
  10600. }
  10601. getIndirect( renderObject ) {
  10602. return renderObject.geometry.indirect;
  10603. }
  10604. getIndex( renderObject ) {
  10605. const { geometry, material } = renderObject;
  10606. let index = geometry.index;
  10607. if ( material.wireframe === true ) {
  10608. const wireframes = this.wireframes;
  10609. let wireframeAttribute = wireframes.get( geometry );
  10610. if ( wireframeAttribute === undefined ) {
  10611. wireframeAttribute = getWireframeIndex( geometry );
  10612. wireframes.set( geometry, wireframeAttribute );
  10613. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  10614. this.attributes.delete( wireframeAttribute );
  10615. wireframeAttribute = getWireframeIndex( geometry );
  10616. wireframes.set( geometry, wireframeAttribute );
  10617. }
  10618. index = wireframeAttribute;
  10619. }
  10620. return index;
  10621. }
  10622. }
  10623. class Info {
  10624. constructor() {
  10625. this.autoReset = true;
  10626. this.frame = 0;
  10627. this.calls = 0;
  10628. this.render = {
  10629. calls: 0,
  10630. frameCalls: 0,
  10631. drawCalls: 0,
  10632. triangles: 0,
  10633. points: 0,
  10634. lines: 0,
  10635. timestamp: 0,
  10636. previousFrameCalls: 0,
  10637. timestampCalls: 0
  10638. };
  10639. this.compute = {
  10640. calls: 0,
  10641. frameCalls: 0,
  10642. timestamp: 0,
  10643. previousFrameCalls: 0,
  10644. timestampCalls: 0
  10645. };
  10646. this.memory = {
  10647. geometries: 0,
  10648. textures: 0
  10649. };
  10650. }
  10651. update( object, count, instanceCount ) {
  10652. this.render.drawCalls ++;
  10653. if ( object.isMesh || object.isSprite ) {
  10654. this.render.triangles += instanceCount * ( count / 3 );
  10655. } else if ( object.isPoints ) {
  10656. this.render.points += instanceCount * count;
  10657. } else if ( object.isLineSegments ) {
  10658. this.render.lines += instanceCount * ( count / 2 );
  10659. } else if ( object.isLine ) {
  10660. this.render.lines += instanceCount * ( count - 1 );
  10661. } else {
  10662. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  10663. }
  10664. }
  10665. updateTimestamp( type, time ) {
  10666. if ( this[ type ].timestampCalls === 0 ) {
  10667. this[ type ].timestamp = 0;
  10668. }
  10669. this[ type ].timestamp += time;
  10670. this[ type ].timestampCalls ++;
  10671. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  10672. this[ type ].timestampCalls = 0;
  10673. }
  10674. }
  10675. reset() {
  10676. const previousRenderFrameCalls = this.render.frameCalls;
  10677. this.render.previousFrameCalls = previousRenderFrameCalls;
  10678. const previousComputeFrameCalls = this.compute.frameCalls;
  10679. this.compute.previousFrameCalls = previousComputeFrameCalls;
  10680. this.render.drawCalls = 0;
  10681. this.render.frameCalls = 0;
  10682. this.compute.frameCalls = 0;
  10683. this.render.triangles = 0;
  10684. this.render.points = 0;
  10685. this.render.lines = 0;
  10686. }
  10687. dispose() {
  10688. this.reset();
  10689. this.calls = 0;
  10690. this.render.calls = 0;
  10691. this.compute.calls = 0;
  10692. this.render.timestamp = 0;
  10693. this.compute.timestamp = 0;
  10694. this.memory.geometries = 0;
  10695. this.memory.textures = 0;
  10696. }
  10697. }
  10698. class Pipeline {
  10699. constructor( cacheKey ) {
  10700. this.cacheKey = cacheKey;
  10701. this.usedTimes = 0;
  10702. }
  10703. }
  10704. class RenderPipeline extends Pipeline {
  10705. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  10706. super( cacheKey );
  10707. this.vertexProgram = vertexProgram;
  10708. this.fragmentProgram = fragmentProgram;
  10709. }
  10710. }
  10711. class ComputePipeline extends Pipeline {
  10712. constructor( cacheKey, computeProgram ) {
  10713. super( cacheKey );
  10714. this.computeProgram = computeProgram;
  10715. this.isComputePipeline = true;
  10716. }
  10717. }
  10718. let _id$7 = 0;
  10719. class ProgrammableStage {
  10720. constructor( code, type, transforms = null, attributes = null ) {
  10721. this.id = _id$7 ++;
  10722. this.code = code;
  10723. this.stage = type;
  10724. this.transforms = transforms;
  10725. this.attributes = attributes;
  10726. this.usedTimes = 0;
  10727. }
  10728. }
  10729. class Pipelines extends DataMap {
  10730. constructor( backend, nodes ) {
  10731. super();
  10732. this.backend = backend;
  10733. this.nodes = nodes;
  10734. this.bindings = null; // set by the bindings
  10735. this.caches = new Map();
  10736. this.programs = {
  10737. vertex: new Map(),
  10738. fragment: new Map(),
  10739. compute: new Map()
  10740. };
  10741. }
  10742. getForCompute( computeNode, bindings ) {
  10743. const { backend } = this;
  10744. const data = this.get( computeNode );
  10745. if ( this._needsComputeUpdate( computeNode ) ) {
  10746. const previousPipeline = data.pipeline;
  10747. if ( previousPipeline ) {
  10748. previousPipeline.usedTimes --;
  10749. previousPipeline.computeProgram.usedTimes --;
  10750. }
  10751. // get shader
  10752. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  10753. // programmable stage
  10754. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  10755. if ( stageCompute === undefined ) {
  10756. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  10757. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  10758. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  10759. backend.createProgram( stageCompute );
  10760. }
  10761. // determine compute pipeline
  10762. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  10763. let pipeline = this.caches.get( cacheKey );
  10764. if ( pipeline === undefined ) {
  10765. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  10766. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  10767. }
  10768. // keep track of all used times
  10769. pipeline.usedTimes ++;
  10770. stageCompute.usedTimes ++;
  10771. //
  10772. data.version = computeNode.version;
  10773. data.pipeline = pipeline;
  10774. }
  10775. return data.pipeline;
  10776. }
  10777. getForRender( renderObject, promises = null ) {
  10778. const { backend } = this;
  10779. const data = this.get( renderObject );
  10780. if ( this._needsRenderUpdate( renderObject ) ) {
  10781. const previousPipeline = data.pipeline;
  10782. if ( previousPipeline ) {
  10783. previousPipeline.usedTimes --;
  10784. previousPipeline.vertexProgram.usedTimes --;
  10785. previousPipeline.fragmentProgram.usedTimes --;
  10786. }
  10787. // get shader
  10788. const nodeBuilderState = renderObject.getNodeBuilderState();
  10789. // programmable stages
  10790. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  10791. if ( stageVertex === undefined ) {
  10792. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  10793. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  10794. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  10795. backend.createProgram( stageVertex );
  10796. }
  10797. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  10798. if ( stageFragment === undefined ) {
  10799. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  10800. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  10801. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  10802. backend.createProgram( stageFragment );
  10803. }
  10804. // determine render pipeline
  10805. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  10806. let pipeline = this.caches.get( cacheKey );
  10807. if ( pipeline === undefined ) {
  10808. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  10809. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  10810. } else {
  10811. renderObject.pipeline = pipeline;
  10812. }
  10813. // keep track of all used times
  10814. pipeline.usedTimes ++;
  10815. stageVertex.usedTimes ++;
  10816. stageFragment.usedTimes ++;
  10817. //
  10818. data.pipeline = pipeline;
  10819. }
  10820. return data.pipeline;
  10821. }
  10822. delete( object ) {
  10823. const pipeline = this.get( object ).pipeline;
  10824. if ( pipeline ) {
  10825. // pipeline
  10826. pipeline.usedTimes --;
  10827. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  10828. // programs
  10829. if ( pipeline.isComputePipeline ) {
  10830. pipeline.computeProgram.usedTimes --;
  10831. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  10832. } else {
  10833. pipeline.fragmentProgram.usedTimes --;
  10834. pipeline.vertexProgram.usedTimes --;
  10835. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  10836. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  10837. }
  10838. }
  10839. return super.delete( object );
  10840. }
  10841. dispose() {
  10842. super.dispose();
  10843. this.caches = new Map();
  10844. this.programs = {
  10845. vertex: new Map(),
  10846. fragment: new Map(),
  10847. compute: new Map()
  10848. };
  10849. }
  10850. updateForRender( renderObject ) {
  10851. this.getForRender( renderObject );
  10852. }
  10853. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  10854. // check for existing pipeline
  10855. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  10856. let pipeline = this.caches.get( cacheKey );
  10857. if ( pipeline === undefined ) {
  10858. pipeline = new ComputePipeline( cacheKey, stageCompute );
  10859. this.caches.set( cacheKey, pipeline );
  10860. this.backend.createComputePipeline( pipeline, bindings );
  10861. }
  10862. return pipeline;
  10863. }
  10864. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  10865. // check for existing pipeline
  10866. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  10867. let pipeline = this.caches.get( cacheKey );
  10868. if ( pipeline === undefined ) {
  10869. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  10870. this.caches.set( cacheKey, pipeline );
  10871. renderObject.pipeline = pipeline;
  10872. this.backend.createRenderPipeline( renderObject, promises );
  10873. }
  10874. return pipeline;
  10875. }
  10876. _getComputeCacheKey( computeNode, stageCompute ) {
  10877. return computeNode.id + ',' + stageCompute.id;
  10878. }
  10879. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  10880. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  10881. }
  10882. _releasePipeline( pipeline ) {
  10883. this.caches.delete( pipeline.cacheKey );
  10884. }
  10885. _releaseProgram( program ) {
  10886. const code = program.code;
  10887. const stage = program.stage;
  10888. this.programs[ stage ].delete( code );
  10889. }
  10890. _needsComputeUpdate( computeNode ) {
  10891. const data = this.get( computeNode );
  10892. return data.pipeline === undefined || data.version !== computeNode.version;
  10893. }
  10894. _needsRenderUpdate( renderObject ) {
  10895. const data = this.get( renderObject );
  10896. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  10897. }
  10898. }
  10899. class Bindings extends DataMap {
  10900. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  10901. super();
  10902. this.backend = backend;
  10903. this.textures = textures;
  10904. this.pipelines = pipelines;
  10905. this.attributes = attributes;
  10906. this.nodes = nodes;
  10907. this.info = info;
  10908. this.pipelines.bindings = this; // assign bindings to pipelines
  10909. }
  10910. getForRender( renderObject ) {
  10911. const bindings = renderObject.getBindings();
  10912. for ( const bindGroup of bindings ) {
  10913. const groupData = this.get( bindGroup );
  10914. if ( groupData.bindGroup === undefined ) {
  10915. // each object defines an array of bindings (ubos, textures, samplers etc.)
  10916. this._init( bindGroup );
  10917. this.backend.createBindings( bindGroup, bindings, 0 );
  10918. groupData.bindGroup = bindGroup;
  10919. }
  10920. }
  10921. return bindings;
  10922. }
  10923. getForCompute( computeNode ) {
  10924. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  10925. for ( const bindGroup of bindings ) {
  10926. const groupData = this.get( bindGroup );
  10927. if ( groupData.bindGroup === undefined ) {
  10928. this._init( bindGroup );
  10929. this.backend.createBindings( bindGroup, bindings, 0 );
  10930. groupData.bindGroup = bindGroup;
  10931. }
  10932. }
  10933. return bindings;
  10934. }
  10935. updateForCompute( computeNode ) {
  10936. this._updateBindings( this.getForCompute( computeNode ) );
  10937. }
  10938. updateForRender( renderObject ) {
  10939. this._updateBindings( this.getForRender( renderObject ) );
  10940. }
  10941. _updateBindings( bindings ) {
  10942. for ( const bindGroup of bindings ) {
  10943. this._update( bindGroup, bindings );
  10944. }
  10945. }
  10946. _init( bindGroup ) {
  10947. for ( const binding of bindGroup.bindings ) {
  10948. if ( binding.isSampledTexture ) {
  10949. this.textures.updateTexture( binding.texture );
  10950. } else if ( binding.isStorageBuffer ) {
  10951. const attribute = binding.attribute;
  10952. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  10953. this.attributes.update( attribute, attributeType );
  10954. }
  10955. }
  10956. }
  10957. _update( bindGroup, bindings ) {
  10958. const { backend } = this;
  10959. let needsBindingsUpdate = false;
  10960. let cacheBindings = true;
  10961. let cacheIndex = 0;
  10962. let version = 0;
  10963. // iterate over all bindings and check if buffer updates or a new binding group is required
  10964. for ( const binding of bindGroup.bindings ) {
  10965. if ( binding.isNodeUniformsGroup ) {
  10966. const updated = this.nodes.updateGroup( binding );
  10967. if ( ! updated ) continue;
  10968. }
  10969. if ( binding.isUniformBuffer ) {
  10970. const updated = binding.update();
  10971. if ( updated ) {
  10972. backend.updateBinding( binding );
  10973. }
  10974. } else if ( binding.isSampler ) {
  10975. binding.update();
  10976. } else if ( binding.isSampledTexture ) {
  10977. const texturesTextureData = this.textures.get( binding.texture );
  10978. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  10979. const updated = binding.update();
  10980. const texture = binding.texture;
  10981. if ( updated ) {
  10982. this.textures.updateTexture( texture );
  10983. }
  10984. const textureData = backend.get( texture );
  10985. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  10986. cacheBindings = false;
  10987. } else {
  10988. cacheIndex = cacheIndex * 10 + texture.id;
  10989. version += texture.version;
  10990. }
  10991. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  10992. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  10993. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  10994. this.textures.updateTexture( texture );
  10995. needsBindingsUpdate = true;
  10996. }
  10997. if ( texture.isStorageTexture === true ) {
  10998. const textureData = this.get( texture );
  10999. if ( binding.store === true ) {
  11000. textureData.needsMipmap = true;
  11001. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  11002. this.backend.generateMipmaps( texture );
  11003. textureData.needsMipmap = false;
  11004. }
  11005. }
  11006. }
  11007. }
  11008. if ( needsBindingsUpdate === true ) {
  11009. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  11010. }
  11011. }
  11012. }
  11013. function painterSortStable( a, b ) {
  11014. if ( a.groupOrder !== b.groupOrder ) {
  11015. return a.groupOrder - b.groupOrder;
  11016. } else if ( a.renderOrder !== b.renderOrder ) {
  11017. return a.renderOrder - b.renderOrder;
  11018. } else if ( a.material.id !== b.material.id ) {
  11019. return a.material.id - b.material.id;
  11020. } else if ( a.z !== b.z ) {
  11021. return a.z - b.z;
  11022. } else {
  11023. return a.id - b.id;
  11024. }
  11025. }
  11026. function reversePainterSortStable( a, b ) {
  11027. if ( a.groupOrder !== b.groupOrder ) {
  11028. return a.groupOrder - b.groupOrder;
  11029. } else if ( a.renderOrder !== b.renderOrder ) {
  11030. return a.renderOrder - b.renderOrder;
  11031. } else if ( a.z !== b.z ) {
  11032. return b.z - a.z;
  11033. } else {
  11034. return a.id - b.id;
  11035. }
  11036. }
  11037. function needsDoublePass( material ) {
  11038. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  11039. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  11040. }
  11041. class RenderList {
  11042. constructor( lighting, scene, camera ) {
  11043. this.renderItems = [];
  11044. this.renderItemsIndex = 0;
  11045. this.opaque = [];
  11046. this.transparentDoublePass = [];
  11047. this.transparent = [];
  11048. this.bundles = [];
  11049. this.lightsNode = lighting.getNode( scene, camera );
  11050. this.lightsArray = [];
  11051. this.scene = scene;
  11052. this.camera = camera;
  11053. this.occlusionQueryCount = 0;
  11054. }
  11055. begin() {
  11056. this.renderItemsIndex = 0;
  11057. this.opaque.length = 0;
  11058. this.transparentDoublePass.length = 0;
  11059. this.transparent.length = 0;
  11060. this.bundles.length = 0;
  11061. this.lightsArray.length = 0;
  11062. this.occlusionQueryCount = 0;
  11063. return this;
  11064. }
  11065. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11066. let renderItem = this.renderItems[ this.renderItemsIndex ];
  11067. if ( renderItem === undefined ) {
  11068. renderItem = {
  11069. id: object.id,
  11070. object: object,
  11071. geometry: geometry,
  11072. material: material,
  11073. groupOrder: groupOrder,
  11074. renderOrder: object.renderOrder,
  11075. z: z,
  11076. group: group,
  11077. clippingContext: clippingContext
  11078. };
  11079. this.renderItems[ this.renderItemsIndex ] = renderItem;
  11080. } else {
  11081. renderItem.id = object.id;
  11082. renderItem.object = object;
  11083. renderItem.geometry = geometry;
  11084. renderItem.material = material;
  11085. renderItem.groupOrder = groupOrder;
  11086. renderItem.renderOrder = object.renderOrder;
  11087. renderItem.z = z;
  11088. renderItem.group = group;
  11089. renderItem.clippingContext = clippingContext;
  11090. }
  11091. this.renderItemsIndex ++;
  11092. return renderItem;
  11093. }
  11094. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11095. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  11096. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  11097. if ( material.transparent === true || material.transmission > 0 ) {
  11098. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  11099. this.transparent.push( renderItem );
  11100. } else {
  11101. this.opaque.push( renderItem );
  11102. }
  11103. }
  11104. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11105. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  11106. if ( material.transparent === true || material.transmission > 0 ) {
  11107. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  11108. this.transparent.unshift( renderItem );
  11109. } else {
  11110. this.opaque.unshift( renderItem );
  11111. }
  11112. }
  11113. pushBundle( group ) {
  11114. this.bundles.push( group );
  11115. }
  11116. pushLight( light ) {
  11117. this.lightsArray.push( light );
  11118. }
  11119. sort( customOpaqueSort, customTransparentSort ) {
  11120. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  11121. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  11122. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  11123. }
  11124. finish() {
  11125. // update lights
  11126. this.lightsNode.setLights( this.lightsArray );
  11127. // Clear references from inactive renderItems in the list
  11128. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  11129. const renderItem = this.renderItems[ i ];
  11130. if ( renderItem.id === null ) break;
  11131. renderItem.id = null;
  11132. renderItem.object = null;
  11133. renderItem.geometry = null;
  11134. renderItem.material = null;
  11135. renderItem.groupOrder = null;
  11136. renderItem.renderOrder = null;
  11137. renderItem.z = null;
  11138. renderItem.group = null;
  11139. renderItem.clippingContext = null;
  11140. }
  11141. }
  11142. }
  11143. class RenderLists {
  11144. constructor( lighting ) {
  11145. this.lighting = lighting;
  11146. this.lists = new ChainMap();
  11147. }
  11148. get( scene, camera ) {
  11149. const lists = this.lists;
  11150. const keys = [ scene, camera ];
  11151. let list = lists.get( keys );
  11152. if ( list === undefined ) {
  11153. list = new RenderList( this.lighting, scene, camera );
  11154. lists.set( keys, list );
  11155. }
  11156. return list;
  11157. }
  11158. dispose() {
  11159. this.lists = new ChainMap();
  11160. }
  11161. }
  11162. let id = 0;
  11163. class RenderContext {
  11164. constructor() {
  11165. this.id = id ++;
  11166. this.color = true;
  11167. this.clearColor = true;
  11168. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  11169. this.depth = true;
  11170. this.clearDepth = true;
  11171. this.clearDepthValue = 1;
  11172. this.stencil = false;
  11173. this.clearStencil = true;
  11174. this.clearStencilValue = 1;
  11175. this.viewport = false;
  11176. this.viewportValue = new Vector4();
  11177. this.scissor = false;
  11178. this.scissorValue = new Vector4();
  11179. this.textures = null;
  11180. this.depthTexture = null;
  11181. this.activeCubeFace = 0;
  11182. this.sampleCount = 1;
  11183. this.width = 0;
  11184. this.height = 0;
  11185. this.isRenderContext = true;
  11186. }
  11187. getCacheKey() {
  11188. return getCacheKey( this );
  11189. }
  11190. }
  11191. function getCacheKey( renderContext ) {
  11192. const { textures, activeCubeFace } = renderContext;
  11193. const values = [ activeCubeFace ];
  11194. for ( const texture of textures ) {
  11195. values.push( texture.id );
  11196. }
  11197. return hashArray( values );
  11198. }
  11199. class RenderContexts {
  11200. constructor() {
  11201. this.chainMaps = {};
  11202. }
  11203. get( scene, camera, renderTarget = null ) {
  11204. const chainKey = [ scene, camera ];
  11205. let attachmentState;
  11206. if ( renderTarget === null ) {
  11207. attachmentState = 'default';
  11208. } else {
  11209. const format = renderTarget.texture.format;
  11210. const count = renderTarget.textures.length;
  11211. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  11212. }
  11213. const chainMap = this.getChainMap( attachmentState );
  11214. let renderState = chainMap.get( chainKey );
  11215. if ( renderState === undefined ) {
  11216. renderState = new RenderContext();
  11217. chainMap.set( chainKey, renderState );
  11218. }
  11219. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  11220. return renderState;
  11221. }
  11222. getChainMap( attachmentState ) {
  11223. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  11224. }
  11225. dispose() {
  11226. this.chainMaps = {};
  11227. }
  11228. }
  11229. const _size$3 = /*@__PURE__*/ new Vector3();
  11230. class Textures extends DataMap {
  11231. constructor( renderer, backend, info ) {
  11232. super();
  11233. this.renderer = renderer;
  11234. this.backend = backend;
  11235. this.info = info;
  11236. }
  11237. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  11238. const renderTargetData = this.get( renderTarget );
  11239. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  11240. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  11241. const textures = renderTarget.textures;
  11242. const size = this.getSize( textures[ 0 ] );
  11243. const mipWidth = size.width >> activeMipmapLevel;
  11244. const mipHeight = size.height >> activeMipmapLevel;
  11245. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  11246. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  11247. let textureNeedsUpdate = false;
  11248. if ( depthTexture === undefined && useDepthTexture ) {
  11249. depthTexture = new DepthTexture();
  11250. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  11251. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  11252. depthTexture.image.width = mipWidth;
  11253. depthTexture.image.height = mipHeight;
  11254. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  11255. }
  11256. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  11257. textureNeedsUpdate = true;
  11258. if ( depthTexture ) {
  11259. depthTexture.needsUpdate = true;
  11260. depthTexture.image.width = mipWidth;
  11261. depthTexture.image.height = mipHeight;
  11262. }
  11263. }
  11264. renderTargetData.width = size.width;
  11265. renderTargetData.height = size.height;
  11266. renderTargetData.textures = textures;
  11267. renderTargetData.depthTexture = depthTexture || null;
  11268. renderTargetData.depth = renderTarget.depthBuffer;
  11269. renderTargetData.stencil = renderTarget.stencilBuffer;
  11270. renderTargetData.renderTarget = renderTarget;
  11271. if ( renderTargetData.sampleCount !== sampleCount ) {
  11272. textureNeedsUpdate = true;
  11273. if ( depthTexture ) {
  11274. depthTexture.needsUpdate = true;
  11275. }
  11276. renderTargetData.sampleCount = sampleCount;
  11277. }
  11278. //
  11279. const options = { sampleCount };
  11280. for ( let i = 0; i < textures.length; i ++ ) {
  11281. const texture = textures[ i ];
  11282. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  11283. this.updateTexture( texture, options );
  11284. }
  11285. if ( depthTexture ) {
  11286. this.updateTexture( depthTexture, options );
  11287. }
  11288. // dispose handler
  11289. if ( renderTargetData.initialized !== true ) {
  11290. renderTargetData.initialized = true;
  11291. // dispose
  11292. const onDispose = () => {
  11293. renderTarget.removeEventListener( 'dispose', onDispose );
  11294. for ( let i = 0; i < textures.length; i ++ ) {
  11295. this._destroyTexture( textures[ i ] );
  11296. }
  11297. if ( depthTexture ) {
  11298. this._destroyTexture( depthTexture );
  11299. }
  11300. this.delete( renderTarget );
  11301. };
  11302. renderTarget.addEventListener( 'dispose', onDispose );
  11303. }
  11304. }
  11305. updateTexture( texture, options = {} ) {
  11306. const textureData = this.get( texture );
  11307. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  11308. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  11309. const backend = this.backend;
  11310. if ( isRenderTarget && textureData.initialized === true ) {
  11311. // it's an update
  11312. backend.destroySampler( texture );
  11313. backend.destroyTexture( texture );
  11314. }
  11315. //
  11316. if ( texture.isFramebufferTexture ) {
  11317. const renderTarget = this.renderer.getRenderTarget();
  11318. if ( renderTarget ) {
  11319. texture.type = renderTarget.texture.type;
  11320. } else {
  11321. texture.type = UnsignedByteType;
  11322. }
  11323. }
  11324. //
  11325. const { width, height, depth } = this.getSize( texture );
  11326. options.width = width;
  11327. options.height = height;
  11328. options.depth = depth;
  11329. options.needsMipmaps = this.needsMipmaps( texture );
  11330. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  11331. //
  11332. if ( isRenderTarget || texture.isStorageTexture === true ) {
  11333. backend.createSampler( texture );
  11334. backend.createTexture( texture, options );
  11335. textureData.generation = texture.version;
  11336. } else {
  11337. const needsCreate = textureData.initialized !== true;
  11338. if ( needsCreate ) backend.createSampler( texture );
  11339. if ( texture.version > 0 ) {
  11340. const image = texture.image;
  11341. if ( image === undefined ) {
  11342. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  11343. } else if ( image.complete === false ) {
  11344. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  11345. } else {
  11346. if ( texture.images ) {
  11347. const images = [];
  11348. for ( const image of texture.images ) {
  11349. images.push( image );
  11350. }
  11351. options.images = images;
  11352. } else {
  11353. options.image = image;
  11354. }
  11355. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  11356. backend.createTexture( texture, options );
  11357. textureData.isDefaultTexture = false;
  11358. textureData.generation = texture.version;
  11359. }
  11360. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  11361. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  11362. }
  11363. } else {
  11364. // async update
  11365. backend.createDefaultTexture( texture );
  11366. textureData.isDefaultTexture = true;
  11367. textureData.generation = texture.version;
  11368. }
  11369. }
  11370. // dispose handler
  11371. if ( textureData.initialized !== true ) {
  11372. textureData.initialized = true;
  11373. textureData.generation = texture.version;
  11374. //
  11375. this.info.memory.textures ++;
  11376. // dispose
  11377. const onDispose = () => {
  11378. texture.removeEventListener( 'dispose', onDispose );
  11379. this._destroyTexture( texture );
  11380. this.info.memory.textures --;
  11381. };
  11382. texture.addEventListener( 'dispose', onDispose );
  11383. }
  11384. //
  11385. textureData.version = texture.version;
  11386. }
  11387. getSize( texture, target = _size$3 ) {
  11388. let image = texture.images ? texture.images[ 0 ] : texture.image;
  11389. if ( image ) {
  11390. if ( image.image !== undefined ) image = image.image;
  11391. target.width = image.width || 1;
  11392. target.height = image.height || 1;
  11393. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  11394. } else {
  11395. target.width = target.height = target.depth = 1;
  11396. }
  11397. return target;
  11398. }
  11399. getMipLevels( texture, width, height ) {
  11400. let mipLevelCount;
  11401. if ( texture.isCompressedTexture ) {
  11402. if ( texture.mipmaps ) {
  11403. mipLevelCount = texture.mipmaps.length;
  11404. } else {
  11405. mipLevelCount = 1;
  11406. }
  11407. } else {
  11408. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  11409. }
  11410. return mipLevelCount;
  11411. }
  11412. needsMipmaps( texture ) {
  11413. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  11414. }
  11415. isEnvironmentTexture( texture ) {
  11416. const mapping = texture.mapping;
  11417. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  11418. }
  11419. _destroyTexture( texture ) {
  11420. this.backend.destroySampler( texture );
  11421. this.backend.destroyTexture( texture );
  11422. this.delete( texture );
  11423. }
  11424. }
  11425. class Color4 extends Color {
  11426. constructor( r, g, b, a = 1 ) {
  11427. super( r, g, b );
  11428. this.a = a;
  11429. }
  11430. set( r, g, b, a = 1 ) {
  11431. this.a = a;
  11432. return super.set( r, g, b );
  11433. }
  11434. copy( color ) {
  11435. if ( color.a !== undefined ) this.a = color.a;
  11436. return super.copy( color );
  11437. }
  11438. clone() {
  11439. return new this.constructor( this.r, this.g, this.b, this.a );
  11440. }
  11441. }
  11442. /**
  11443. * Special version of {@link PropertyNode} which is used for parameters.
  11444. *
  11445. * @augments PropertyNode
  11446. */
  11447. class ParameterNode extends PropertyNode {
  11448. static get type() {
  11449. return 'ParameterNode';
  11450. }
  11451. /**
  11452. * Constructs a new parameter node.
  11453. *
  11454. * @param {String} nodeType - The type of the node.
  11455. * @param {String?} [name=null] - The name of the parameter in the shader.
  11456. */
  11457. constructor( nodeType, name = null ) {
  11458. super( nodeType, name );
  11459. /**
  11460. * This flag can be used for type testing.
  11461. *
  11462. * @type {Boolean}
  11463. * @readonly
  11464. * @default true
  11465. */
  11466. this.isParameterNode = true;
  11467. }
  11468. getHash() {
  11469. return this.uuid;
  11470. }
  11471. generate() {
  11472. return this.name;
  11473. }
  11474. }
  11475. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  11476. /**
  11477. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  11478. * They are usually needed in cases like `If`, `Else`.
  11479. *
  11480. * @augments Node
  11481. */
  11482. class StackNode extends Node {
  11483. static get type() {
  11484. return 'StackNode';
  11485. }
  11486. /**
  11487. * Constructs a new stack node.
  11488. *
  11489. * @param {StackNode?} [parent=null] - The parent stack node.
  11490. */
  11491. constructor( parent = null ) {
  11492. super();
  11493. /**
  11494. * List of nodes.
  11495. *
  11496. * @type {Array<Node>}
  11497. */
  11498. this.nodes = [];
  11499. /**
  11500. * The output node.
  11501. *
  11502. * @type {Node?}
  11503. * @default null
  11504. */
  11505. this.outputNode = null;
  11506. /**
  11507. * The parent stack node.
  11508. *
  11509. * @type {StackNode}
  11510. * @default null
  11511. */
  11512. this.parent = parent;
  11513. /**
  11514. * The current conditional node.
  11515. *
  11516. * @private
  11517. * @type {ConditionalNode}
  11518. * @default null
  11519. */
  11520. this._currentCond = null;
  11521. /**
  11522. * This flag can be used for type testing.
  11523. *
  11524. * @type {Boolean}
  11525. * @readonly
  11526. * @default true
  11527. */
  11528. this.isStackNode = true;
  11529. }
  11530. getNodeType( builder ) {
  11531. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  11532. }
  11533. /**
  11534. * Adds a node to this stack.
  11535. *
  11536. * @param {Node} node - The node to add.
  11537. * @return {StackNode} A reference to this stack node.
  11538. */
  11539. add( node ) {
  11540. this.nodes.push( node );
  11541. return this;
  11542. }
  11543. /**
  11544. * Represent an `if` statement in TSL.
  11545. *
  11546. * @param {Node} boolNode - Represents the condition.
  11547. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  11548. * @return {StackNode} A reference to this stack node.
  11549. */
  11550. If( boolNode, method ) {
  11551. const methodNode = new ShaderNode( method );
  11552. this._currentCond = select( boolNode, methodNode );
  11553. return this.add( this._currentCond );
  11554. }
  11555. /**
  11556. * Represent an `elseif` statement in TSL.
  11557. *
  11558. * @param {Node} boolNode - Represents the condition.
  11559. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  11560. * @return {StackNode} A reference to this stack node.
  11561. */
  11562. ElseIf( boolNode, method ) {
  11563. const methodNode = new ShaderNode( method );
  11564. const ifNode = select( boolNode, methodNode );
  11565. this._currentCond.elseNode = ifNode;
  11566. this._currentCond = ifNode;
  11567. return this;
  11568. }
  11569. /**
  11570. * Represent an `else` statement in TSL.
  11571. *
  11572. * @param {Function} method - TSL code which is executed in the `else` case.
  11573. * @return {StackNode} A reference to this stack node.
  11574. */
  11575. Else( method ) {
  11576. this._currentCond.elseNode = new ShaderNode( method );
  11577. return this;
  11578. }
  11579. build( builder, ...params ) {
  11580. const previousStack = getCurrentStack();
  11581. setCurrentStack( this );
  11582. for ( const node of this.nodes ) {
  11583. node.build( builder, 'void' );
  11584. }
  11585. setCurrentStack( previousStack );
  11586. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  11587. }
  11588. //
  11589. else( ...params ) { // @deprecated, r168
  11590. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  11591. return this.Else( ...params );
  11592. }
  11593. elseif( ...params ) { // @deprecated, r168
  11594. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  11595. return this.ElseIf( ...params );
  11596. }
  11597. }
  11598. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  11599. /**
  11600. * This node can be used to define multiple outputs in a shader programs.
  11601. *
  11602. * @augments Node
  11603. */
  11604. class OutputStructNode extends Node {
  11605. static get type() {
  11606. return 'OutputStructNode';
  11607. }
  11608. /**
  11609. * Constructs a new output struct node. The constructor can be invoked with an
  11610. * arbitrary number of nodes representing the members.
  11611. *
  11612. * @param {...Node} members - A parameter list of nodes.
  11613. */
  11614. constructor( ...members ) {
  11615. super();
  11616. /**
  11617. * An array of nodes which defines the output.
  11618. *
  11619. * @type {Array<Node>}
  11620. */
  11621. this.members = members;
  11622. /**
  11623. * This flag can be used for type testing.
  11624. *
  11625. * @type {Boolean}
  11626. * @readonly
  11627. * @default true
  11628. */
  11629. this.isOutputStructNode = true;
  11630. }
  11631. setup( builder ) {
  11632. super.setup( builder );
  11633. const members = this.members;
  11634. const types = [];
  11635. for ( let i = 0; i < members.length; i ++ ) {
  11636. types.push( members[ i ].getNodeType( builder ) );
  11637. }
  11638. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  11639. }
  11640. generate( builder, output ) {
  11641. const propertyName = builder.getOutputStructName();
  11642. const members = this.members;
  11643. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  11644. for ( let i = 0; i < members.length; i ++ ) {
  11645. const snippet = members[ i ].build( builder, output );
  11646. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  11647. }
  11648. return propertyName;
  11649. }
  11650. }
  11651. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  11652. /**
  11653. * Returns the MRT texture index for the given name.
  11654. *
  11655. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  11656. * @param {String} name - The name of the MRT texture which index is requested.
  11657. * @return {Number} The texture index.
  11658. */
  11659. function getTextureIndex( textures, name ) {
  11660. for ( let i = 0; i < textures.length; i ++ ) {
  11661. if ( textures[ i ].name === name ) {
  11662. return i;
  11663. }
  11664. }
  11665. return - 1;
  11666. }
  11667. /**
  11668. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  11669. * post-processing is shown below:
  11670. * ```js
  11671. * const mrtNode = mrt( {
  11672. * output: output,
  11673. * normal: normalView
  11674. * } ) );
  11675. * ```
  11676. * The MRT output is defined as a dictionary.
  11677. *
  11678. * @augments OutputStructNode
  11679. */
  11680. class MRTNode extends OutputStructNode {
  11681. static get type() {
  11682. return 'MRTNode';
  11683. }
  11684. /**
  11685. * Constructs a new output struct node.
  11686. *
  11687. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  11688. */
  11689. constructor( outputNodes ) {
  11690. super();
  11691. /**
  11692. * A dictionary representing the MRT outputs. The key
  11693. * is the name of the output, the value the node which produces
  11694. * the output result.
  11695. *
  11696. * @type {Object<String, Node>}
  11697. */
  11698. this.outputNodes = outputNodes;
  11699. /**
  11700. * This flag can be used for type testing.
  11701. *
  11702. * @type {Boolean}
  11703. * @readonly
  11704. * @default true
  11705. */
  11706. this.isMRTNode = true;
  11707. }
  11708. /**
  11709. * Returns `true` if the MRT node has an output with the given name.
  11710. *
  11711. * @param {String} name - The name of the output.
  11712. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  11713. */
  11714. has( name ) {
  11715. return this.outputNodes[ name ] !== undefined;
  11716. }
  11717. /**
  11718. * Returns the output node for the given name.
  11719. *
  11720. * @param {String} name - The name of the output.
  11721. * @return {Node} The output node.
  11722. */
  11723. get( name ) {
  11724. return this.outputNodes[ name ];
  11725. }
  11726. /**
  11727. * Merges the outputs of the given MRT node with the outputs of this node.
  11728. *
  11729. * @param {MRTNode} mrtNode - The MRT to merge.
  11730. * @return {MRTNode} A new MRT node with merged outputs..
  11731. */
  11732. merge( mrtNode ) {
  11733. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  11734. return mrt( outputs );
  11735. }
  11736. setup( builder ) {
  11737. const outputNodes = this.outputNodes;
  11738. const mrt = builder.renderer.getRenderTarget();
  11739. const members = [];
  11740. const textures = mrt.textures;
  11741. for ( const name in outputNodes ) {
  11742. const index = getTextureIndex( textures, name );
  11743. members[ index ] = vec4( outputNodes[ name ] );
  11744. }
  11745. this.members = members;
  11746. return super.setup( builder );
  11747. }
  11748. }
  11749. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  11750. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  11751. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  11752. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  11753. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  11754. const result = word.shiftRight( 22 ).bitXor( word );
  11755. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  11756. } );
  11757. // remapping functions https://iquilezles.org/articles/functions/
  11758. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  11759. 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 ) );
  11760. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  11761. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  11762. // https://github.com/cabbibo/glsl-tri-noise-3d
  11763. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  11764. return x.fract().sub( .5 ).abs();
  11765. } ).setLayout( {
  11766. name: 'tri',
  11767. type: 'float',
  11768. inputs: [
  11769. { name: 'x', type: 'float' }
  11770. ]
  11771. } );
  11772. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  11773. 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. ) ) ) ) );
  11774. } ).setLayout( {
  11775. name: 'tri3',
  11776. type: 'vec3',
  11777. inputs: [
  11778. { name: 'p', type: 'vec3' }
  11779. ]
  11780. } );
  11781. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  11782. const p = vec3( p_immutable ).toVar();
  11783. const z = float( 1.4 ).toVar();
  11784. const rz = float( 0.0 ).toVar();
  11785. const bp = vec3( p ).toVar();
  11786. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  11787. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  11788. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  11789. bp.mulAssign( 1.8 );
  11790. z.mulAssign( 1.5 );
  11791. p.mulAssign( 1.2 );
  11792. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  11793. rz.addAssign( t.div( z ) );
  11794. bp.addAssign( 0.14 );
  11795. } );
  11796. return rz;
  11797. } ).setLayout( {
  11798. name: 'triNoise3D',
  11799. type: 'float',
  11800. inputs: [
  11801. { name: 'p', type: 'vec3' },
  11802. { name: 'spd', type: 'float' },
  11803. { name: 'time', type: 'float' }
  11804. ]
  11805. } );
  11806. class FunctionOverloadingNode extends Node {
  11807. static get type() {
  11808. return 'FunctionOverloadingNode';
  11809. }
  11810. constructor( functionNodes = [], ...parametersNodes ) {
  11811. super();
  11812. this.functionNodes = functionNodes;
  11813. this.parametersNodes = parametersNodes;
  11814. this._candidateFnCall = null;
  11815. this.global = true;
  11816. }
  11817. getNodeType() {
  11818. return this.functionNodes[ 0 ].shaderNode.layout.type;
  11819. }
  11820. setup( builder ) {
  11821. const params = this.parametersNodes;
  11822. let candidateFnCall = this._candidateFnCall;
  11823. if ( candidateFnCall === null ) {
  11824. let candidateFn = null;
  11825. let candidateScore = - 1;
  11826. for ( const functionNode of this.functionNodes ) {
  11827. const shaderNode = functionNode.shaderNode;
  11828. const layout = shaderNode.layout;
  11829. if ( layout === null ) {
  11830. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  11831. }
  11832. const inputs = layout.inputs;
  11833. if ( params.length === inputs.length ) {
  11834. let score = 0;
  11835. for ( let i = 0; i < params.length; i ++ ) {
  11836. const param = params[ i ];
  11837. const input = inputs[ i ];
  11838. if ( param.getNodeType( builder ) === input.type ) {
  11839. score ++;
  11840. } else {
  11841. score = 0;
  11842. }
  11843. }
  11844. if ( score > candidateScore ) {
  11845. candidateFn = functionNode;
  11846. candidateScore = score;
  11847. }
  11848. }
  11849. }
  11850. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  11851. }
  11852. return candidateFnCall;
  11853. }
  11854. }
  11855. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  11856. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  11857. /** @module Timer **/
  11858. /**
  11859. * Represents the elapsed time in seconds.
  11860. *
  11861. * @type {UniformNode<float>}
  11862. */
  11863. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  11864. /**
  11865. * Represents the delta time in seconds.
  11866. *
  11867. * @type {UniformNode<float>}
  11868. */
  11869. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  11870. /**
  11871. * Represents the current frame ID.
  11872. *
  11873. * @type {UniformNode<uint>}
  11874. */
  11875. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  11876. // Deprecated
  11877. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  11878. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  11879. return time.mul( timeScale );
  11880. };
  11881. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  11882. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  11883. return time.mul( timeScale );
  11884. };
  11885. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  11886. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  11887. return deltaTime.mul( timeScale );
  11888. };
  11889. /** @module Oscillators **/
  11890. /**
  11891. * Generates a sine wave oscillation based on a timer.
  11892. *
  11893. * @method
  11894. * @param {Node<float>} time - The timer to generate the oscillation with.
  11895. * @return {Node<float>} The oscillation node.
  11896. */
  11897. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  11898. /**
  11899. * Generates a square wave oscillation based on a timer.
  11900. *
  11901. * @method
  11902. * @param {Node<float>} time - The timer to generate the oscillation with.
  11903. * @return {Node<float>} The oscillation node.
  11904. */
  11905. const oscSquare = ( t = time ) => t.fract().round();
  11906. /**
  11907. * Generates a triangle wave oscillation based on a timer.
  11908. *
  11909. * @method
  11910. * @param {Node<float>} time - The timer to generate the oscillation with.
  11911. * @return {Node<float>} The oscillation node.
  11912. */
  11913. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  11914. /**
  11915. * Generates a sawtooth wave oscillation based on a timer.
  11916. *
  11917. * @method
  11918. * @param {Node<float>} time - The timer to generate the oscillation with.
  11919. * @return {Node<float>} The oscillation node.
  11920. */
  11921. const oscSawtooth = ( t = time ) => t.fract();
  11922. /** @module UVUtils **/
  11923. /**
  11924. * Rotates the given uv coordinates around a center point
  11925. *
  11926. * @method
  11927. * @param {Node<vec2>} uv - The uv coordinates.
  11928. * @param {Node<float>} rotation - The rotation defined in radians.
  11929. * @param {Node<vec2>} center - The center of rotation
  11930. * @return {Node<vec2>} The rotated uv coordinates.
  11931. */
  11932. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  11933. return rotate( uv.sub( center ), rotation ).add( center );
  11934. } );
  11935. /**
  11936. * Applies a spherical warping effect to the given uv coordinates.
  11937. *
  11938. * @method
  11939. * @param {Node<vec2>} uv - The uv coordinates.
  11940. * @param {Node<float>} strength - The strength of the effect.
  11941. * @param {Node<vec2>} center - The center point
  11942. * @return {Node<vec2>} The updated uv coordinates.
  11943. */
  11944. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  11945. const delta = uv.sub( center );
  11946. const delta2 = delta.dot( delta );
  11947. const delta4 = delta2.mul( delta2 );
  11948. const deltaOffset = delta4.mul( strength );
  11949. return uv.add( delta.mul( deltaOffset ) );
  11950. } );
  11951. /** @module SpriteUtils **/
  11952. /**
  11953. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  11954. * oriented always towards the camera.
  11955. *
  11956. * ```js
  11957. * material.vertexNode = billboarding();
  11958. * ```
  11959. *
  11960. * @method
  11961. * @param {Object} config - The configuration object.
  11962. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  11963. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  11964. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  11965. * @return {Node<vec3>} The updated vertex position in clip space.
  11966. */
  11967. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  11968. let worldMatrix;
  11969. if ( position !== null ) {
  11970. worldMatrix = modelWorldMatrix.toVar();
  11971. worldMatrix[ 3 ][ 0 ] = position.x;
  11972. worldMatrix[ 3 ][ 1 ] = position.y;
  11973. worldMatrix[ 3 ][ 2 ] = position.z;
  11974. } else {
  11975. worldMatrix = modelWorldMatrix;
  11976. }
  11977. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  11978. if ( defined( horizontal ) ) {
  11979. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  11980. modelViewMatrix[ 0 ][ 1 ] = 0;
  11981. modelViewMatrix[ 0 ][ 2 ] = 0;
  11982. }
  11983. if ( defined( vertical ) ) {
  11984. modelViewMatrix[ 1 ][ 0 ] = 0;
  11985. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  11986. modelViewMatrix[ 1 ][ 2 ] = 0;
  11987. }
  11988. modelViewMatrix[ 2 ][ 0 ] = 0;
  11989. modelViewMatrix[ 2 ][ 1 ] = 0;
  11990. modelViewMatrix[ 2 ][ 2 ] = 1;
  11991. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  11992. } );
  11993. /** @module ViewportUtils **/
  11994. /**
  11995. * A special version of a screen uv function that involves a depth comparison
  11996. * when computing the final uvs. The function mitigates visual erros when
  11997. * using viewport texture nodes for refraction purposes. Without this function
  11998. * objects in front of a refractive surface might appear on the refractive surface
  11999. * which is incorrect.
  12000. *
  12001. * @method
  12002. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  12003. * @return {Node<vec2>} The update uv coordinates.
  12004. */
  12005. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  12006. const depth = linearDepth();
  12007. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  12008. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  12009. return finalUV;
  12010. } );
  12011. /**
  12012. * Can be used to compute texture coordinates for animated sprite sheets.
  12013. *
  12014. * ```js
  12015. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  12016. *
  12017. * material.colorNode = texture( spriteSheet, uvNode );
  12018. * ```
  12019. *
  12020. * @augments Node
  12021. */
  12022. class SpriteSheetUVNode extends Node {
  12023. static get type() {
  12024. return 'SpriteSheetUVNode';
  12025. }
  12026. /**
  12027. * Constructs a new sprite sheet uv node.
  12028. *
  12029. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  12030. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  12031. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  12032. */
  12033. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  12034. super( 'vec2' );
  12035. /**
  12036. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  12037. *
  12038. * @type {Node<vec2>}
  12039. */
  12040. this.countNode = countNode;
  12041. /**
  12042. * The uv node.
  12043. *
  12044. * @type {Node<vec2>}
  12045. */
  12046. this.uvNode = uvNode;
  12047. /**
  12048. * The node that defines the current frame/sprite.
  12049. *
  12050. * @type {Node<float>}
  12051. */
  12052. this.frameNode = frameNode;
  12053. }
  12054. setup() {
  12055. const { frameNode, uvNode, countNode } = this;
  12056. const { width, height } = countNode;
  12057. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  12058. const column = frameNum.mod( width );
  12059. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  12060. const scale = countNode.reciprocal();
  12061. const uvFrameOffset = vec2( column, row );
  12062. return uvNode.add( uvFrameOffset ).mul( scale );
  12063. }
  12064. }
  12065. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  12066. /**
  12067. * Can be used for triplanar texture mapping.
  12068. *
  12069. * ```js
  12070. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  12071. * ```
  12072. *
  12073. * @augments Node
  12074. */
  12075. class TriplanarTexturesNode extends Node {
  12076. static get type() {
  12077. return 'TriplanarTexturesNode';
  12078. }
  12079. /**
  12080. * Constructs a new triplanar textures node.
  12081. *
  12082. * @param {Node} textureXNode - First texture node.
  12083. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  12084. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  12085. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  12086. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  12087. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  12088. */
  12089. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  12090. super( 'vec4' );
  12091. /**
  12092. * First texture node.
  12093. *
  12094. * @type {Node}
  12095. */
  12096. this.textureXNode = textureXNode;
  12097. /**
  12098. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  12099. *
  12100. * @type {Node}
  12101. * @default null
  12102. */
  12103. this.textureYNode = textureYNode;
  12104. /**
  12105. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  12106. *
  12107. * @type {Node}
  12108. * @default null
  12109. */
  12110. this.textureZNode = textureZNode;
  12111. /**
  12112. * The scale node.
  12113. *
  12114. * @type {Node<float>}
  12115. * @default float(1)
  12116. */
  12117. this.scaleNode = scaleNode;
  12118. /**
  12119. * Vertex positions in local space.
  12120. *
  12121. * @type {Node<vec3>}
  12122. * @default positionLocal
  12123. */
  12124. this.positionNode = positionNode;
  12125. /**
  12126. * Normals in local space.
  12127. *
  12128. * @type {Node<vec3>}
  12129. * @default normalLocal
  12130. */
  12131. this.normalNode = normalNode;
  12132. }
  12133. setup() {
  12134. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  12135. // Ref: https://github.com/keijiro/StandardTriplanar
  12136. // Blending factor of triplanar mapping
  12137. let bf = normalNode.abs().normalize();
  12138. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  12139. // Triplanar mapping
  12140. const tx = positionNode.yz.mul( scaleNode );
  12141. const ty = positionNode.zx.mul( scaleNode );
  12142. const tz = positionNode.xy.mul( scaleNode );
  12143. // Base color
  12144. const textureX = textureXNode.value;
  12145. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  12146. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  12147. const cx = texture( textureX, tx ).mul( bf.x );
  12148. const cy = texture( textureY, ty ).mul( bf.y );
  12149. const cz = texture( textureZ, tz ).mul( bf.z );
  12150. return add( cx, cy, cz );
  12151. }
  12152. }
  12153. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  12154. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  12155. const _reflectorPlane = new Plane();
  12156. const _normal = new Vector3();
  12157. const _reflectorWorldPosition = new Vector3();
  12158. const _cameraWorldPosition = new Vector3();
  12159. const _rotationMatrix = new Matrix4();
  12160. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  12161. const clipPlane = new Vector4();
  12162. const _view = new Vector3();
  12163. const _target = new Vector3();
  12164. const _q = new Vector4();
  12165. const _size$2 = new Vector2();
  12166. const _defaultRT = new RenderTarget();
  12167. const _defaultUV = screenUV.flipX();
  12168. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  12169. let _inReflector = false;
  12170. /**
  12171. * This node can be used to implement mirror-like flat reflective surfaces.
  12172. *
  12173. * ```js
  12174. * const groundReflector = reflector();
  12175. * material.colorNode = groundReflector;
  12176. *
  12177. * const plane = new Mesh( geometry, material );
  12178. * plane.add( groundReflector.target );
  12179. * ```
  12180. *
  12181. * @augments TextureNode
  12182. */
  12183. class ReflectorNode extends TextureNode {
  12184. static get type() {
  12185. return 'ReflectorNode';
  12186. }
  12187. /**
  12188. * Constructs a new reflector node.
  12189. *
  12190. * @param {Object} [parameters={}] - An object holding configuration parameters.
  12191. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  12192. * @param {Number} [parameters.resolution=1] - The resolution scale.
  12193. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  12194. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  12195. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  12196. */
  12197. constructor( parameters = {} ) {
  12198. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  12199. /**
  12200. * A reference to the internal reflector base node which holds the actual implementation.
  12201. *
  12202. * @private
  12203. * @type {Node?}
  12204. * @default null
  12205. */
  12206. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  12207. /**
  12208. * A reference to the internal depth node.
  12209. *
  12210. * @private
  12211. * @type {Node?}
  12212. * @default null
  12213. */
  12214. this._depthNode = null;
  12215. this.setUpdateMatrix( false );
  12216. }
  12217. /**
  12218. * A reference to the internal reflector node.
  12219. *
  12220. * @type {Node}
  12221. */
  12222. get reflector() {
  12223. return this._reflectorBaseNode;
  12224. }
  12225. /**
  12226. * A reference to 3D object the reflector is linked to.
  12227. *
  12228. * @type {Object3D}
  12229. */
  12230. get target() {
  12231. return this._reflectorBaseNode.target;
  12232. }
  12233. /**
  12234. * Returns a node representing the mirror's depth. That can be used
  12235. * to implement more advanced reflection effects like distance attenuation.
  12236. *
  12237. * @return {Node} The depth node.
  12238. */
  12239. getDepthNode() {
  12240. if ( this._depthNode === null ) {
  12241. if ( this._reflectorBaseNode.depth !== true ) {
  12242. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  12243. }
  12244. this._depthNode = nodeObject( new ReflectorNode( {
  12245. defaultTexture: _defaultRT.depthTexture,
  12246. reflector: this._reflectorBaseNode
  12247. } ) );
  12248. }
  12249. return this._depthNode;
  12250. }
  12251. setup( builder ) {
  12252. // ignore if used in post-processing
  12253. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  12254. return super.setup( builder );
  12255. }
  12256. clone() {
  12257. const texture = new this.constructor( this.reflectorNode );
  12258. texture._reflectorBaseNode = this._reflectorBaseNode;
  12259. return texture;
  12260. }
  12261. }
  12262. /**
  12263. * Holds the actual implementation of the reflector.
  12264. *
  12265. * TOOD: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  12266. * in `ReflectorNode`, see #29619.
  12267. *
  12268. * @private
  12269. * @augments Node
  12270. */
  12271. class ReflectorBaseNode extends Node {
  12272. static get type() {
  12273. return 'ReflectorBaseNode';
  12274. }
  12275. /**
  12276. * Constructs a new reflector base node.
  12277. *
  12278. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  12279. * @param {Object} [parameters={}] - An object holding configuration parameters.
  12280. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  12281. * @param {Number} [parameters.resolution=1] - The resolution scale.
  12282. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  12283. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  12284. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  12285. */
  12286. constructor( textureNode, parameters = {} ) {
  12287. super();
  12288. const {
  12289. target = new Object3D(),
  12290. resolution = 1,
  12291. generateMipmaps = false,
  12292. bounces = true,
  12293. depth = false
  12294. } = parameters;
  12295. /**
  12296. * Represents the rendered reflections as a texture node.
  12297. *
  12298. * @type {TextureNode}
  12299. */
  12300. this.textureNode = textureNode;
  12301. /**
  12302. * The 3D object the reflector is linked to.
  12303. *
  12304. * @type {Object3D}
  12305. * @default {new Object3D()}
  12306. */
  12307. this.target = target;
  12308. /**
  12309. * The resolution scale.
  12310. *
  12311. * @type {Number}
  12312. * @default {1}
  12313. */
  12314. this.resolution = resolution;
  12315. /**
  12316. * Whether mipmaps should be generated or not.
  12317. *
  12318. * @type {Boolean}
  12319. * @default {false}
  12320. */
  12321. this.generateMipmaps = generateMipmaps;
  12322. /**
  12323. * Whether reflectors can render other reflector nodes or not.
  12324. *
  12325. * @type {Boolean}
  12326. * @default {true}
  12327. */
  12328. this.bounces = bounces;
  12329. /**
  12330. * Whether depth data should be generated or not.
  12331. *
  12332. * @type {Boolean}
  12333. * @default {false}
  12334. */
  12335. this.depth = depth;
  12336. /**
  12337. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  12338. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  12339. *
  12340. * @type {String}
  12341. * @default 'render'
  12342. */
  12343. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  12344. /**
  12345. * Weak map for managing virtual cameras.
  12346. *
  12347. * @type {WeakMap<Camera,Camera>}
  12348. */
  12349. this.virtualCameras = new WeakMap();
  12350. /**
  12351. * Weak map for managing render targets.
  12352. *
  12353. * @type {WeakMap}
  12354. */
  12355. this.renderTargets = new WeakMap();
  12356. }
  12357. /**
  12358. * Updates the resolution of the internal render target.
  12359. *
  12360. * @private
  12361. * @param {RenderTarget} renderTarget - The render target to resize.
  12362. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  12363. */
  12364. _updateResolution( renderTarget, renderer ) {
  12365. const resolution = this.resolution;
  12366. renderer.getDrawingBufferSize( _size$2 );
  12367. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  12368. }
  12369. setup( builder ) {
  12370. this._updateResolution( _defaultRT, builder.renderer );
  12371. return super.setup( builder );
  12372. }
  12373. /**
  12374. * Returns a virtual camera for the given camera. The virutal camera is used to
  12375. * render the scene from the reflector's view so correct reflections can be produced.
  12376. *
  12377. * @param {Camera} camera - The scene's camera.
  12378. * @return {Camera} The corresponding virtual camera.
  12379. */
  12380. getVirtualCamera( camera ) {
  12381. let virtualCamera = this.virtualCameras.get( camera );
  12382. if ( virtualCamera === undefined ) {
  12383. virtualCamera = camera.clone();
  12384. this.virtualCameras.set( camera, virtualCamera );
  12385. }
  12386. return virtualCamera;
  12387. }
  12388. /**
  12389. * Returns a render target for the given camera. The reflections are rendered
  12390. * into this render target.
  12391. *
  12392. * @param {Camera} camera - The scene's camera.
  12393. * @return {RenderTarget} The render target.
  12394. */
  12395. getRenderTarget( camera ) {
  12396. let renderTarget = this.renderTargets.get( camera );
  12397. if ( renderTarget === undefined ) {
  12398. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  12399. if ( this.generateMipmaps === true ) {
  12400. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  12401. renderTarget.texture.generateMipmaps = true;
  12402. }
  12403. if ( this.depth === true ) {
  12404. renderTarget.depthTexture = new DepthTexture();
  12405. }
  12406. this.renderTargets.set( camera, renderTarget );
  12407. }
  12408. return renderTarget;
  12409. }
  12410. updateBefore( frame ) {
  12411. if ( this.bounces === false && _inReflector ) return;
  12412. _inReflector = true;
  12413. const { scene, camera, renderer, material } = frame;
  12414. const { target } = this;
  12415. const virtualCamera = this.getVirtualCamera( camera );
  12416. const renderTarget = this.getRenderTarget( virtualCamera );
  12417. renderer.getDrawingBufferSize( _size$2 );
  12418. this._updateResolution( renderTarget, renderer );
  12419. //
  12420. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  12421. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  12422. _rotationMatrix.extractRotation( target.matrixWorld );
  12423. _normal.set( 0, 0, 1 );
  12424. _normal.applyMatrix4( _rotationMatrix );
  12425. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  12426. // Avoid rendering when reflector is facing away
  12427. if ( _view.dot( _normal ) > 0 ) return;
  12428. _view.reflect( _normal ).negate();
  12429. _view.add( _reflectorWorldPosition );
  12430. _rotationMatrix.extractRotation( camera.matrixWorld );
  12431. _lookAtPosition.set( 0, 0, - 1 );
  12432. _lookAtPosition.applyMatrix4( _rotationMatrix );
  12433. _lookAtPosition.add( _cameraWorldPosition );
  12434. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  12435. _target.reflect( _normal ).negate();
  12436. _target.add( _reflectorWorldPosition );
  12437. //
  12438. virtualCamera.coordinateSystem = camera.coordinateSystem;
  12439. virtualCamera.position.copy( _view );
  12440. virtualCamera.up.set( 0, 1, 0 );
  12441. virtualCamera.up.applyMatrix4( _rotationMatrix );
  12442. virtualCamera.up.reflect( _normal );
  12443. virtualCamera.lookAt( _target );
  12444. virtualCamera.near = camera.near;
  12445. virtualCamera.far = camera.far;
  12446. virtualCamera.updateMatrixWorld();
  12447. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  12448. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  12449. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  12450. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  12451. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  12452. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  12453. const projectionMatrix = virtualCamera.projectionMatrix;
  12454. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  12455. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  12456. _q.z = - 1.0;
  12457. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  12458. // Calculate the scaled plane vector
  12459. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  12460. const clipBias = 0;
  12461. // Replacing the third row of the projection matrix
  12462. projectionMatrix.elements[ 2 ] = clipPlane.x;
  12463. projectionMatrix.elements[ 6 ] = clipPlane.y;
  12464. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  12465. projectionMatrix.elements[ 14 ] = clipPlane.w;
  12466. //
  12467. this.textureNode.value = renderTarget.texture;
  12468. if ( this.depth === true ) {
  12469. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  12470. }
  12471. material.visible = false;
  12472. const currentRenderTarget = renderer.getRenderTarget();
  12473. const currentMRT = renderer.getMRT();
  12474. renderer.setMRT( null );
  12475. renderer.setRenderTarget( renderTarget );
  12476. renderer.render( scene, virtualCamera );
  12477. renderer.setMRT( currentMRT );
  12478. renderer.setRenderTarget( currentRenderTarget );
  12479. material.visible = true;
  12480. _inReflector = false;
  12481. }
  12482. }
  12483. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  12484. // Helper for passes that need to fill the viewport with a single quad.
  12485. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  12486. // https://github.com/mrdoob/three.js/pull/21358
  12487. class QuadGeometry extends BufferGeometry {
  12488. constructor( flipY = false ) {
  12489. super();
  12490. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  12491. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  12492. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  12493. }
  12494. }
  12495. const _geometry = /*@__PURE__*/ new QuadGeometry();
  12496. class QuadMesh extends Mesh {
  12497. constructor( material = null ) {
  12498. super( _geometry, material );
  12499. this.camera = _camera;
  12500. this.isQuadMesh = true;
  12501. }
  12502. renderAsync( renderer ) {
  12503. return renderer.renderAsync( this, _camera );
  12504. }
  12505. render( renderer ) {
  12506. renderer.render( this, _camera );
  12507. }
  12508. }
  12509. const _size$1 = /*@__PURE__*/ new Vector2();
  12510. /**
  12511. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  12512. * This module is especially relevant in context of post processing where certain nodes require
  12513. * texture input for their effects. With the helper function `convertToTexture()` which is based
  12514. * on this module, the node system can automatically ensure texture input if required.
  12515. *
  12516. * @augments Node
  12517. */
  12518. class RTTNode extends TextureNode {
  12519. static get type() {
  12520. return 'RTTNode';
  12521. }
  12522. /**
  12523. * Constructs a new RTT node.
  12524. *
  12525. * @param {Node} node - The node to render a texture with.
  12526. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  12527. * @param {Number?} [height=null] - The height of the internal render target.
  12528. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  12529. */
  12530. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  12531. const renderTarget = new RenderTarget( width, height, options );
  12532. super( renderTarget.texture, uv() );
  12533. /**
  12534. * The node to render a texture with.
  12535. *
  12536. * @type {Node}
  12537. */
  12538. this.node = node;
  12539. /**
  12540. * The width of the internal render target.
  12541. * If not width is applied, the render target is automatically resized.
  12542. *
  12543. * @type {Number?}
  12544. * @default null
  12545. */
  12546. this.width = width;
  12547. /**
  12548. * The height of the internal render target.
  12549. *
  12550. * @type {Number?}
  12551. * @default null
  12552. */
  12553. this.height = height;
  12554. /**
  12555. * The pixel ratio
  12556. *
  12557. * @type {Number}
  12558. * @default 1
  12559. */
  12560. this.pixelRatio = 1;
  12561. /**
  12562. * The render target
  12563. *
  12564. * @type {RenderTarget}
  12565. */
  12566. this.renderTarget = renderTarget;
  12567. /**
  12568. * Whether the texture requires an update or not.
  12569. *
  12570. * @type {Boolean}
  12571. * @default true
  12572. */
  12573. this.textureNeedsUpdate = true;
  12574. /**
  12575. * Whether the texture should automatically be updated or not.
  12576. *
  12577. * @type {Boolean}
  12578. * @default true
  12579. */
  12580. this.autoUpdate = true;
  12581. /**
  12582. * The node which is used with the quad mesh for RTT.
  12583. *
  12584. * @private
  12585. * @type {Node}
  12586. * @default null
  12587. */
  12588. this._rttNode = null;
  12589. /**
  12590. * The internal quad mesh for RTT.
  12591. *
  12592. * @private
  12593. * @type {QuadMesh}
  12594. */
  12595. this._quadMesh = new QuadMesh( new NodeMaterial() );
  12596. /**
  12597. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12598. * the texture once per render in its {@link RTTNode#updateBefore} method.
  12599. *
  12600. * @type {String}
  12601. * @default 'render'
  12602. */
  12603. this.updateBeforeType = NodeUpdateType.RENDER;
  12604. }
  12605. /**
  12606. * Whether the internal render target should automatically be resized or not.
  12607. *
  12608. * @type {Boolean}
  12609. * @readonly
  12610. * @default true
  12611. */
  12612. get autoSize() {
  12613. return this.width === null;
  12614. }
  12615. setup( builder ) {
  12616. this._rttNode = this.node.context( builder.getSharedContext() );
  12617. this._quadMesh.material.name = 'RTT';
  12618. this._quadMesh.material.needsUpdate = true;
  12619. return super.setup( builder );
  12620. }
  12621. /**
  12622. * Sets the size of the internal render target
  12623. *
  12624. * @param {Number} width - The width to set.
  12625. * @param {Number} height - The width to set.
  12626. */
  12627. setSize( width, height ) {
  12628. this.width = width;
  12629. this.height = height;
  12630. const effectiveWidth = width * this.pixelRatio;
  12631. const effectiveHeight = height * this.pixelRatio;
  12632. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  12633. this.textureNeedsUpdate = true;
  12634. }
  12635. /**
  12636. * Sets the pixel ratio. This will also resize the render target.
  12637. *
  12638. * @param {Number} pixelRatio - The pixel ratio to set.
  12639. */
  12640. setPixelRatio( pixelRatio ) {
  12641. this.pixelRatio = pixelRatio;
  12642. this.setSize( this.width, this.height );
  12643. }
  12644. updateBefore( { renderer } ) {
  12645. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  12646. this.textureNeedsUpdate = false;
  12647. //
  12648. if ( this.autoSize === true ) {
  12649. this.pixelRatio = renderer.getPixelRatio();
  12650. const size = renderer.getSize( _size$1 );
  12651. this.setSize( size.width, size.height );
  12652. }
  12653. //
  12654. this._quadMesh.material.fragmentNode = this._rttNode;
  12655. //
  12656. const currentRenderTarget = renderer.getRenderTarget();
  12657. renderer.setRenderTarget( this.renderTarget );
  12658. this._quadMesh.render( renderer );
  12659. renderer.setRenderTarget( currentRenderTarget );
  12660. }
  12661. clone() {
  12662. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  12663. newNode.sampler = this.sampler;
  12664. newNode.referenceNode = this;
  12665. return newNode;
  12666. }
  12667. }
  12668. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  12669. const convertToTexture = ( node, ...params ) => {
  12670. if ( node.isTextureNode ) return node;
  12671. if ( node.isPassNode ) return node.getTextureNode();
  12672. return rtt( node, ...params );
  12673. };
  12674. /** @module PostProcessingUtils **/
  12675. /**
  12676. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  12677. * depth value and the camera's inverse projection matrix.
  12678. *
  12679. * @method
  12680. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  12681. * @param {Node<float>} depth - The fragment's depth value.
  12682. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  12683. * @return {Node<vec3>} The fragments position in view space.
  12684. */
  12685. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  12686. let clipSpacePosition;
  12687. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  12688. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  12689. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  12690. } else {
  12691. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  12692. }
  12693. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  12694. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  12695. } );
  12696. /**
  12697. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  12698. * and the camera's projection matrix
  12699. *
  12700. * @method
  12701. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  12702. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  12703. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  12704. */
  12705. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  12706. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  12707. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  12708. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  12709. } );
  12710. /**
  12711. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  12712. * target is available or if flat surface normals are required.
  12713. *
  12714. * @method
  12715. * @param {Node<vec2>} uv - The texture coordinate.
  12716. * @param {DepthTexture} depthTexture - The depth texture.
  12717. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  12718. * @return {Node<vec3>} The computed normal vector.
  12719. */
  12720. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  12721. const size = textureSize( textureLoad( depthTexture ) );
  12722. const p = ivec2( uv.mul( size ) ).toVar();
  12723. const c0 = textureLoad( depthTexture, p ).toVar();
  12724. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  12725. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  12726. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  12727. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  12728. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  12729. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  12730. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  12731. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  12732. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  12733. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  12734. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  12735. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  12736. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  12737. 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 ) ) );
  12738. 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 ) ) );
  12739. return normalize( cross( dpdx, dpdy ) );
  12740. } );
  12741. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  12742. constructor( array, itemSize, typeClass = Float32Array ) {
  12743. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  12744. super( array, itemSize );
  12745. this.isStorageInstancedBufferAttribute = true;
  12746. }
  12747. }
  12748. class StorageBufferAttribute extends BufferAttribute {
  12749. constructor( array, itemSize, typeClass = Float32Array ) {
  12750. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  12751. super( array, itemSize );
  12752. this.isStorageBufferAttribute = true;
  12753. }
  12754. }
  12755. /**
  12756. * This class enables element access on instances of {@link StorageBufferNode}.
  12757. * In most cases, it is indirectly used when accessing elements with the
  12758. * {@link StorageBufferNode#element} method.
  12759. *
  12760. * ```js
  12761. * const position = positionStorage.element( instanceIndex );
  12762. * ```
  12763. *
  12764. * @augments ArrayElementNode
  12765. */
  12766. class StorageArrayElementNode extends ArrayElementNode {
  12767. static get type() {
  12768. return 'StorageArrayElementNode';
  12769. }
  12770. /**
  12771. * Constructs storage buffer element node.
  12772. *
  12773. * @param {StorageBufferNode} node - The storage buffer node.
  12774. * @param {Node} indexNode - The index node that defines the element access.
  12775. */
  12776. constructor( storageBufferNode, indexNode ) {
  12777. super( storageBufferNode, indexNode );
  12778. /**
  12779. * This flag can be used for type testing.
  12780. *
  12781. * @type {Boolean}
  12782. * @readonly
  12783. * @default true
  12784. */
  12785. this.isStorageArrayElementNode = true;
  12786. }
  12787. /**
  12788. * The storage buffer node.
  12789. *
  12790. * @type {StorageBufferNode}
  12791. */
  12792. set storageBufferNode( value ) {
  12793. this.node = value;
  12794. }
  12795. get storageBufferNode() {
  12796. return this.node;
  12797. }
  12798. setup( builder ) {
  12799. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12800. if ( this.node.isPBO === true ) {
  12801. builder.setupPBO( this.node );
  12802. }
  12803. }
  12804. return super.setup( builder );
  12805. }
  12806. generate( builder, output ) {
  12807. let snippet;
  12808. const isAssignContext = builder.context.assign;
  12809. //
  12810. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12811. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  12812. snippet = builder.generatePBO( this );
  12813. } else {
  12814. snippet = this.node.build( builder );
  12815. }
  12816. } else {
  12817. snippet = super.generate( builder );
  12818. }
  12819. if ( isAssignContext !== true ) {
  12820. const type = this.getNodeType( builder );
  12821. snippet = builder.format( snippet, type, output );
  12822. }
  12823. return snippet;
  12824. }
  12825. }
  12826. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  12827. class StorageBufferNode extends BufferNode {
  12828. static get type() {
  12829. return 'StorageBufferNode';
  12830. }
  12831. constructor( value, bufferType = null, bufferCount = 0 ) {
  12832. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  12833. bufferType = getTypeFromLength( value.itemSize );
  12834. bufferCount = value.count;
  12835. }
  12836. super( value, bufferType, bufferCount );
  12837. this.isStorageBufferNode = true;
  12838. this.access = NodeAccess.READ_WRITE;
  12839. this.isAtomic = false;
  12840. this.isPBO = false;
  12841. this.bufferCount = bufferCount;
  12842. this._attribute = null;
  12843. this._varying = null;
  12844. this.global = true;
  12845. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12846. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12847. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12848. else value.isStorageBufferAttribute = true;
  12849. }
  12850. }
  12851. getHash( builder ) {
  12852. if ( this.bufferCount === 0 ) {
  12853. let bufferData = builder.globalCache.getData( this.value );
  12854. if ( bufferData === undefined ) {
  12855. bufferData = {
  12856. node: this
  12857. };
  12858. builder.globalCache.setData( this.value, bufferData );
  12859. }
  12860. return bufferData.node.uuid;
  12861. }
  12862. return this.uuid;
  12863. }
  12864. getInputType( /*builder*/ ) {
  12865. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12866. }
  12867. element( indexNode ) {
  12868. return storageElement( this, indexNode );
  12869. }
  12870. setPBO( value ) {
  12871. this.isPBO = value;
  12872. return this;
  12873. }
  12874. getPBO() {
  12875. return this.isPBO;
  12876. }
  12877. setAccess( value ) {
  12878. this.access = value;
  12879. return this;
  12880. }
  12881. toReadOnly() {
  12882. return this.setAccess( NodeAccess.READ_ONLY );
  12883. }
  12884. setAtomic( value ) {
  12885. this.isAtomic = value;
  12886. return this;
  12887. }
  12888. toAtomic() {
  12889. return this.setAtomic( true );
  12890. }
  12891. getAttributeData() {
  12892. if ( this._attribute === null ) {
  12893. this._attribute = bufferAttribute( this.value );
  12894. this._varying = varying( this._attribute );
  12895. }
  12896. return {
  12897. attribute: this._attribute,
  12898. varying: this._varying
  12899. };
  12900. }
  12901. getNodeType( builder ) {
  12902. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12903. return super.getNodeType( builder );
  12904. }
  12905. const { attribute } = this.getAttributeData();
  12906. return attribute.getNodeType( builder );
  12907. }
  12908. generate( builder ) {
  12909. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12910. return super.generate( builder );
  12911. }
  12912. const { attribute, varying } = this.getAttributeData();
  12913. const output = varying.build( builder );
  12914. builder.registerTransform( output, attribute );
  12915. return output;
  12916. }
  12917. }
  12918. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12919. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12920. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12921. return storage( value, type, count ).setPBO( true );
  12922. };
  12923. const attributeArray = ( count, type = 'float' ) => {
  12924. const itemSize = getLengthFromType( type );
  12925. const buffer = new StorageBufferAttribute( count, itemSize );
  12926. const node = storage( buffer, type, count );
  12927. return node;
  12928. };
  12929. const instancedArray = ( count, type = 'float' ) => {
  12930. const itemSize = getLengthFromType( type );
  12931. const buffer = new StorageInstancedBufferAttribute( count, itemSize );
  12932. const node = storage( buffer, type, count );
  12933. return node;
  12934. };
  12935. class VertexColorNode extends AttributeNode {
  12936. static get type() {
  12937. return 'VertexColorNode';
  12938. }
  12939. constructor( index = 0 ) {
  12940. super( null, 'vec4' );
  12941. this.isVertexColorNode = true;
  12942. this.index = index;
  12943. }
  12944. getAttributeName( /*builder*/ ) {
  12945. const index = this.index;
  12946. return 'color' + ( index > 0 ? index : '' );
  12947. }
  12948. generate( builder ) {
  12949. const attributeName = this.getAttributeName( builder );
  12950. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12951. let result;
  12952. if ( geometryAttribute === true ) {
  12953. result = super.generate( builder );
  12954. } else {
  12955. // Vertex color fallback should be white
  12956. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12957. }
  12958. return result;
  12959. }
  12960. serialize( data ) {
  12961. super.serialize( data );
  12962. data.index = this.index;
  12963. }
  12964. deserialize( data ) {
  12965. super.deserialize( data );
  12966. this.index = data.index;
  12967. }
  12968. }
  12969. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  12970. class PointUVNode extends Node {
  12971. static get type() {
  12972. return 'PointUVNode';
  12973. }
  12974. constructor() {
  12975. super( 'vec2' );
  12976. this.isPointUVNode = true;
  12977. }
  12978. generate( /*builder*/ ) {
  12979. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  12980. }
  12981. }
  12982. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  12983. const _e1 = /*@__PURE__*/ new Euler();
  12984. const _m1 = /*@__PURE__*/ new Matrix4();
  12985. class SceneNode extends Node {
  12986. static get type() {
  12987. return 'SceneNode';
  12988. }
  12989. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  12990. super();
  12991. this.scope = scope;
  12992. this.scene = scene;
  12993. }
  12994. setup( builder ) {
  12995. const scope = this.scope;
  12996. const scene = this.scene !== null ? this.scene : builder.scene;
  12997. let output;
  12998. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  12999. output = reference( 'backgroundBlurriness', 'float', scene );
  13000. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  13001. output = reference( 'backgroundIntensity', 'float', scene );
  13002. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  13003. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  13004. const background = scene.background;
  13005. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  13006. _e1.copy( scene.backgroundRotation );
  13007. // accommodate left-handed frame
  13008. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  13009. _m1.makeRotationFromEuler( _e1 );
  13010. } else {
  13011. _m1.identity();
  13012. }
  13013. return _m1;
  13014. } );
  13015. } else {
  13016. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  13017. }
  13018. return output;
  13019. }
  13020. }
  13021. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  13022. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  13023. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  13024. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  13025. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  13026. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  13027. class StorageTextureNode extends TextureNode {
  13028. static get type() {
  13029. return 'StorageTextureNode';
  13030. }
  13031. constructor( value, uvNode, storeNode = null ) {
  13032. super( value, uvNode );
  13033. this.storeNode = storeNode;
  13034. this.isStorageTextureNode = true;
  13035. this.access = NodeAccess.WRITE_ONLY;
  13036. }
  13037. getInputType( /*builder*/ ) {
  13038. return 'storageTexture';
  13039. }
  13040. setup( builder ) {
  13041. super.setup( builder );
  13042. const properties = builder.getNodeProperties( this );
  13043. properties.storeNode = this.storeNode;
  13044. }
  13045. setAccess( value ) {
  13046. this.access = value;
  13047. return this;
  13048. }
  13049. generate( builder, output ) {
  13050. let snippet;
  13051. if ( this.storeNode !== null ) {
  13052. snippet = this.generateStore( builder );
  13053. } else {
  13054. snippet = super.generate( builder, output );
  13055. }
  13056. return snippet;
  13057. }
  13058. toReadWrite() {
  13059. return this.setAccess( NodeAccess.READ_WRITE );
  13060. }
  13061. toReadOnly() {
  13062. return this.setAccess( NodeAccess.READ_ONLY );
  13063. }
  13064. toWriteOnly() {
  13065. return this.setAccess( NodeAccess.WRITE_ONLY );
  13066. }
  13067. generateStore( builder ) {
  13068. const properties = builder.getNodeProperties( this );
  13069. const { uvNode, storeNode } = properties;
  13070. const textureProperty = super.generate( builder, 'property' );
  13071. const uvSnippet = uvNode.build( builder, 'uvec2' );
  13072. const storeSnippet = storeNode.build( builder, 'vec4' );
  13073. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  13074. builder.addLineFlowCode( snippet, this );
  13075. }
  13076. }
  13077. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  13078. const textureStore = ( value, uvNode, storeNode ) => {
  13079. const node = storageTexture( value, uvNode, storeNode );
  13080. if ( storeNode !== null ) node.append();
  13081. return node;
  13082. };
  13083. class UserDataNode extends ReferenceNode {
  13084. static get type() {
  13085. return 'UserDataNode';
  13086. }
  13087. constructor( property, inputType, userData = null ) {
  13088. super( property, inputType, userData );
  13089. this.userData = userData;
  13090. }
  13091. updateReference( state ) {
  13092. this.reference = this.userData !== null ? this.userData : state.object.userData;
  13093. return this.reference;
  13094. }
  13095. }
  13096. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  13097. const _objectData = new WeakMap();
  13098. class VelocityNode extends TempNode {
  13099. static get type() {
  13100. return 'VelocityNode';
  13101. }
  13102. constructor() {
  13103. super( 'vec2' );
  13104. this.projectionMatrix = null;
  13105. this.updateType = NodeUpdateType.OBJECT;
  13106. this.updateAfterType = NodeUpdateType.OBJECT;
  13107. this.previousModelWorldMatrix = uniform( new Matrix4() );
  13108. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  13109. this.previousCameraViewMatrix = uniform( new Matrix4() );
  13110. }
  13111. setProjectionMatrix( projectionMatrix ) {
  13112. this.projectionMatrix = projectionMatrix;
  13113. }
  13114. update( { frameId, camera, object } ) {
  13115. const previousModelMatrix = getPreviousMatrix( object );
  13116. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  13117. //
  13118. const cameraData = getData( camera );
  13119. if ( cameraData.frameId !== frameId ) {
  13120. cameraData.frameId = frameId;
  13121. if ( cameraData.previousProjectionMatrix === undefined ) {
  13122. cameraData.previousProjectionMatrix = new Matrix4();
  13123. cameraData.previousCameraViewMatrix = new Matrix4();
  13124. cameraData.currentProjectionMatrix = new Matrix4();
  13125. cameraData.currentCameraViewMatrix = new Matrix4();
  13126. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  13127. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  13128. } else {
  13129. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  13130. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  13131. }
  13132. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  13133. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  13134. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  13135. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  13136. }
  13137. }
  13138. updateAfter( { object } ) {
  13139. getPreviousMatrix( object ).copy( object.matrixWorld );
  13140. }
  13141. setup( /*builder*/ ) {
  13142. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  13143. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  13144. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  13145. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  13146. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  13147. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  13148. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  13149. return velocity;
  13150. }
  13151. }
  13152. function getData( object ) {
  13153. let objectData = _objectData.get( object );
  13154. if ( objectData === undefined ) {
  13155. objectData = {};
  13156. _objectData.set( object, objectData );
  13157. }
  13158. return objectData;
  13159. }
  13160. function getPreviousMatrix( object, index = 0 ) {
  13161. const objectData = getData( object );
  13162. let matrix = objectData[ index ];
  13163. if ( matrix === undefined ) {
  13164. objectData[ index ] = matrix = new Matrix4();
  13165. }
  13166. return matrix;
  13167. }
  13168. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  13169. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13170. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13171. } ).setLayout( {
  13172. name: 'blendBurn',
  13173. type: 'vec3',
  13174. inputs: [
  13175. { name: 'base', type: 'vec3' },
  13176. { name: 'blend', type: 'vec3' }
  13177. ]
  13178. } );
  13179. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13180. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13181. } ).setLayout( {
  13182. name: 'blendDodge',
  13183. type: 'vec3',
  13184. inputs: [
  13185. { name: 'base', type: 'vec3' },
  13186. { name: 'blend', type: 'vec3' }
  13187. ]
  13188. } );
  13189. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13190. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13191. } ).setLayout( {
  13192. name: 'blendScreen',
  13193. type: 'vec3',
  13194. inputs: [
  13195. { name: 'base', type: 'vec3' },
  13196. { name: 'blend', type: 'vec3' }
  13197. ]
  13198. } );
  13199. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13200. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13201. } ).setLayout( {
  13202. name: 'blendOverlay',
  13203. type: 'vec3',
  13204. inputs: [
  13205. { name: 'base', type: 'vec3' },
  13206. { name: 'blend', type: 'vec3' }
  13207. ]
  13208. } );
  13209. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13210. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13211. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13212. } ).setLayout( {
  13213. name: 'blendColor',
  13214. type: 'vec4',
  13215. inputs: [
  13216. { name: 'base', type: 'vec4' },
  13217. { name: 'blend', type: 'vec4' }
  13218. ]
  13219. } );
  13220. // deprecated
  13221. const burn = ( ...params ) => { // @deprecated, r171
  13222. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13223. return blendBurn( params );
  13224. };
  13225. const dodge = ( ...params ) => { // @deprecated, r171
  13226. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13227. return blendDodge( params );
  13228. };
  13229. const screen = ( ...params ) => { // @deprecated, r171
  13230. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13231. return blendScreen( params );
  13232. };
  13233. const overlay = ( ...params ) => { // @deprecated, r171
  13234. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13235. return blendOverlay( params );
  13236. };
  13237. /** @module ColorAdjustment **/
  13238. /**
  13239. * Computes a grayscale value for the given RGB color value.
  13240. *
  13241. * @method
  13242. * @param {vec3} color - The color value to compute the grayscale for.
  13243. * @return {vec3} The grayscale color.
  13244. */
  13245. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13246. return luminance( color.rgb );
  13247. } );
  13248. /**
  13249. * Super-saturates or desaturates the given RGB color.
  13250. *
  13251. * @method
  13252. * @param {vec3} color - The input color.
  13253. * @param {float} [adjustment=1] - Specifies the amount of the conversion. A value under `1` desaturates the color, a value over `1` super-saturates it.
  13254. * @return {vec3} The saturated color.
  13255. */
  13256. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13257. return adjustment.mix( luminance( color.rgb ), color.rgb );
  13258. } );
  13259. /**
  13260. * Selectively enhance the intensity of less saturated RGB colors. Can result
  13261. * in a more natural and visually appealing image with enhanced color depth
  13262. * compared to {@link ColorAdjustment#saturation}.
  13263. *
  13264. * @method
  13265. * @param {vec3} color - The input color.
  13266. * @param {float} [adjustment=1] - Controls the intensity of the vibrance effect.
  13267. * @return {vec3} The updated color.
  13268. */
  13269. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13270. const average = add( color.r, color.g, color.b ).div( 3.0 );
  13271. const mx = color.r.max( color.g.max( color.b ) );
  13272. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  13273. return mix( color.rgb, mx, amt );
  13274. } );
  13275. /**
  13276. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  13277. *
  13278. * @method
  13279. * @param {vec3} color - The input color.
  13280. * @param {float} [adjustment=1] - Defines the degree of hue rotation in radians. A positive value rotates the hue clockwise, while a negative value rotates it counterclockwise.
  13281. * @return {vec3} The updated color.
  13282. */
  13283. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13284. const k = vec3( 0.57735, 0.57735, 0.57735 );
  13285. const cosAngle = adjustment.cos();
  13286. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  13287. } );
  13288. /**
  13289. * Computes the luminance for the given RGB color value.
  13290. *
  13291. * @method
  13292. * @param {vec3} color - The color value to compute the luminance for.
  13293. * @param {vec3?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  13294. * @return {vec3} The luminance.
  13295. */
  13296. const luminance = (
  13297. color,
  13298. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  13299. ) => dot( color, luminanceCoefficients );
  13300. /**
  13301. * Color Decision List (CDL) v1.2
  13302. *
  13303. * Compact representation of color grading information, defined by slope, offset, power, and
  13304. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  13305. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  13306. *
  13307. * @method
  13308. * @param {vec4} color Input (-Infinity < input < +Infinity)
  13309. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  13310. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  13311. * @param {number | vec3} power Power (0 < power < +Infinity)
  13312. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  13313. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  13314. * @return Output, -Infinity < output < +Infinity
  13315. *
  13316. * References:
  13317. * - ASC CDL v1.2
  13318. * - {@link https://blender.stackexchange.com/a/55239/43930}
  13319. * - {@link https://docs.acescentral.com/specifications/acescc/}
  13320. */
  13321. const cdl = /*@__PURE__*/ Fn( ( [
  13322. color,
  13323. slope = vec3( 1 ),
  13324. offset = vec3( 0 ),
  13325. power = vec3( 1 ),
  13326. saturation = float( 1 ),
  13327. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  13328. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  13329. ] ) => {
  13330. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  13331. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  13332. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  13333. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  13334. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  13335. const pv = v.pow( power ).toVar();
  13336. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  13337. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  13338. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  13339. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  13340. return vec4( v.rgb, color.a );
  13341. } );
  13342. /**
  13343. * Represents a posterize effect which reduces the number of colors
  13344. * in an image, resulting in a more blocky and stylized appearance.
  13345. *
  13346. * @augments TempNode
  13347. */
  13348. class PosterizeNode extends TempNode {
  13349. static get type() {
  13350. return 'PosterizeNode';
  13351. }
  13352. /**
  13353. * Constructs a new posterize node.
  13354. *
  13355. * @param {Node} sourceNode - The input color.
  13356. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  13357. */
  13358. constructor( sourceNode, stepsNode ) {
  13359. super();
  13360. /**
  13361. * The input color.
  13362. *
  13363. * @type {Node}
  13364. */
  13365. this.sourceNode = sourceNode;
  13366. /**
  13367. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  13368. *
  13369. * @type {Node}
  13370. */
  13371. this.stepsNode = stepsNode;
  13372. }
  13373. setup() {
  13374. const { sourceNode, stepsNode } = this;
  13375. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  13376. }
  13377. }
  13378. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  13379. const _size = /*@__PURE__*/ new Vector2();
  13380. /**
  13381. * Represents the texture of a pass node.
  13382. *
  13383. * @augments TextureNode
  13384. * @private
  13385. */
  13386. class PassTextureNode extends TextureNode {
  13387. static get type() {
  13388. return 'PassTextureNode';
  13389. }
  13390. /**
  13391. * Constructs a new pass texture node.
  13392. *
  13393. * @param {PassNode} passNode - The pass node.
  13394. * @param {Texture} texture - The output texture.
  13395. */
  13396. constructor( passNode, texture ) {
  13397. super( texture );
  13398. /**
  13399. * A reference to the pass node.
  13400. *
  13401. * @type {PassNode}
  13402. */
  13403. this.passNode = passNode;
  13404. this.setUpdateMatrix( false );
  13405. }
  13406. setup( builder ) {
  13407. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  13408. return super.setup( builder );
  13409. }
  13410. clone() {
  13411. return new this.constructor( this.passNode, this.value );
  13412. }
  13413. }
  13414. /**
  13415. * An extension of `PassTextureNode` which allows to manage more than one
  13416. * internal texture. Relevant for the `getPreviousTexture()` related API.
  13417. *
  13418. * @augments PassTextureNode
  13419. * @private
  13420. */
  13421. class PassMultipleTextureNode extends PassTextureNode {
  13422. static get type() {
  13423. return 'PassMultipleTextureNode';
  13424. }
  13425. /**
  13426. * Constructs a new pass texture node.
  13427. *
  13428. * @param {PassNode} passNode - The pass node.
  13429. * @param {String} textureName - The output texture name.
  13430. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  13431. */
  13432. constructor( passNode, textureName, previousTexture = false ) {
  13433. // null is passed to the super call since this class does not
  13434. // use an external texture for rendering pass data into. Instead
  13435. // the texture is managed by the pass node itself
  13436. super( passNode, null );
  13437. /**
  13438. * The output texture name.
  13439. *
  13440. * @type {String}
  13441. */
  13442. this.textureName = textureName;
  13443. /**
  13444. * Whether previous frame data should be used or not.
  13445. *
  13446. * @type {Boolean}
  13447. */
  13448. this.previousTexture = previousTexture;
  13449. }
  13450. /**
  13451. * Updates the texture reference of this node.
  13452. */
  13453. updateTexture() {
  13454. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  13455. }
  13456. setup( builder ) {
  13457. this.updateTexture();
  13458. return super.setup( builder );
  13459. }
  13460. clone() {
  13461. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  13462. }
  13463. }
  13464. /**
  13465. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  13466. * This pass produces a render for the given scene and camera and can provide multiple outputs
  13467. * via MRT for further processing.
  13468. *
  13469. * ```js
  13470. * const postProcessing = new PostProcessing( renderer );
  13471. *
  13472. * const scenePass = pass( scene, camera );
  13473. *
  13474. * postProcessing.outputNode = scenePass;
  13475. * ```
  13476. *
  13477. * @augments TempNode
  13478. */
  13479. class PassNode extends TempNode {
  13480. static get type() {
  13481. return 'PassNode';
  13482. }
  13483. /**
  13484. * Constructs a new pass node.
  13485. *
  13486. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  13487. * @param {Scene} scene - A reference to the scene.
  13488. * @param {Camera} camera - A reference to the camera.
  13489. * @param {Object} options - Options for the internal render target.
  13490. */
  13491. constructor( scope, scene, camera, options = {} ) {
  13492. super( 'vec4' );
  13493. /**
  13494. * The scope of the pass. The scope determines whether the node outputs color or depth.
  13495. *
  13496. * @type {('color'|'depth')}
  13497. */
  13498. this.scope = scope;
  13499. /**
  13500. * A reference to the scene.
  13501. *
  13502. * @type {Scene}
  13503. */
  13504. this.scene = scene;
  13505. /**
  13506. * A reference to the camera.
  13507. *
  13508. * @type {camera}
  13509. */
  13510. this.camera = camera;
  13511. /**
  13512. * Options for the internal render target.
  13513. *
  13514. * @type {Object}
  13515. */
  13516. this.options = options;
  13517. /**
  13518. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  13519. *
  13520. * @private
  13521. * @type {Number}
  13522. * @default 1
  13523. */
  13524. this._pixelRatio = 1;
  13525. /**
  13526. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  13527. * @private
  13528. * @type {Number}
  13529. * @default 1
  13530. */
  13531. this._width = 1;
  13532. /**
  13533. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  13534. * @private
  13535. * @type {Number}
  13536. * @default 1
  13537. */
  13538. this._height = 1;
  13539. const depthTexture = new DepthTexture();
  13540. depthTexture.isRenderTargetTexture = true;
  13541. //depthTexture.type = FloatType;
  13542. depthTexture.name = 'depth';
  13543. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  13544. renderTarget.texture.name = 'output';
  13545. renderTarget.depthTexture = depthTexture;
  13546. /**
  13547. * The pass's render target.
  13548. *
  13549. * @type {RenderTarget}
  13550. */
  13551. this.renderTarget = renderTarget;
  13552. /**
  13553. * A dictionary holding the internal result textures.
  13554. *
  13555. * @private
  13556. * @type {Object}
  13557. */
  13558. this._textures = {
  13559. output: renderTarget.texture,
  13560. depth: depthTexture
  13561. };
  13562. /**
  13563. * A dictionary holding the internal texture nodes.
  13564. *
  13565. * @private
  13566. * @type {Object}
  13567. */
  13568. this._textureNodes = {};
  13569. /**
  13570. * A dictionary holding the internal depth nodes.
  13571. *
  13572. * @private
  13573. * @type {Object}
  13574. */
  13575. this._linearDepthNodes = {};
  13576. /**
  13577. * A dictionary holding the internal viewZ nodes.
  13578. *
  13579. * @private
  13580. * @type {Object}
  13581. */
  13582. this._viewZNodes = {};
  13583. /**
  13584. * A dictionary holding the texture data of the previous frame.
  13585. * Used for computing velocity/motion vectors.
  13586. *
  13587. * @private
  13588. * @type {Object}
  13589. */
  13590. this._previousTextures = {};
  13591. /**
  13592. * A dictionary holding the texture nodes of the previous frame.
  13593. * Used for computing velocity/motion vectors.
  13594. *
  13595. * @private
  13596. * @type {Object}
  13597. */
  13598. this._previousTextureNodes = {};
  13599. /**
  13600. * The `near` property of the camera as a uniform.
  13601. *
  13602. * @private
  13603. * @type {UniformNode}
  13604. */
  13605. this._cameraNear = uniform( 0 );
  13606. /**
  13607. * The `far` property of the camera as a uniform.
  13608. *
  13609. * @private
  13610. * @type {UniformNode}
  13611. */
  13612. this._cameraFar = uniform( 0 );
  13613. /**
  13614. * A MRT node configuring the MRT settings.
  13615. *
  13616. * @private
  13617. * @type {MRTNode?}
  13618. * @default null
  13619. */
  13620. this._mrt = null;
  13621. /**
  13622. * This flag can be used for type testing.
  13623. *
  13624. * @type {Boolean}
  13625. * @readonly
  13626. * @default true
  13627. */
  13628. this.isPassNode = true;
  13629. /**
  13630. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13631. * scene once per frame in its {@link PassNode#updateBefore} method.
  13632. *
  13633. * @type {String}
  13634. * @default 'frame'
  13635. */
  13636. this.updateBeforeType = NodeUpdateType.FRAME;
  13637. }
  13638. /**
  13639. * Sets the given MRT node to setup MRT for this pass.
  13640. *
  13641. * @param {MRTNode} mrt - The MRT object.
  13642. * @return {PassNode} A reference to this pass.
  13643. */
  13644. setMRT( mrt ) {
  13645. this._mrt = mrt;
  13646. return this;
  13647. }
  13648. /**
  13649. * Returns the current MRT node.
  13650. *
  13651. * @return {MRTNode} The current MRT node.
  13652. */
  13653. getMRT() {
  13654. return this._mrt;
  13655. }
  13656. /**
  13657. * The method is overwritten so it always returns `true`.
  13658. *
  13659. * @return {Boolean} Whether this node is global or not.
  13660. */
  13661. isGlobal() {
  13662. return true;
  13663. }
  13664. /**
  13665. * Returns the texture for the given output name.
  13666. *
  13667. * @param {String} name - The output name to get the texture for.
  13668. * @return {Texture} The texture.
  13669. */
  13670. getTexture( name ) {
  13671. let texture = this._textures[ name ];
  13672. if ( texture === undefined ) {
  13673. const refTexture = this.renderTarget.texture;
  13674. texture = refTexture.clone();
  13675. texture.name = name;
  13676. this._textures[ name ] = texture;
  13677. this.renderTarget.textures.push( texture );
  13678. }
  13679. return texture;
  13680. }
  13681. /**
  13682. * Returns the texture holding the data of the previous frame for the given output name.
  13683. *
  13684. * @param {String} name - The output name to get the texture for.
  13685. * @return {Texture} The texture holding the data of the previous frame.
  13686. */
  13687. getPreviousTexture( name ) {
  13688. let texture = this._previousTextures[ name ];
  13689. if ( texture === undefined ) {
  13690. texture = this.getTexture( name ).clone();
  13691. this._previousTextures[ name ] = texture;
  13692. }
  13693. return texture;
  13694. }
  13695. /**
  13696. * Switches current and previous textures for the given output name.
  13697. *
  13698. * @param {String} name - The output name.
  13699. */
  13700. toggleTexture( name ) {
  13701. const prevTexture = this._previousTextures[ name ];
  13702. if ( prevTexture !== undefined ) {
  13703. const texture = this._textures[ name ];
  13704. const index = this.renderTarget.textures.indexOf( texture );
  13705. this.renderTarget.textures[ index ] = prevTexture;
  13706. this._textures[ name ] = prevTexture;
  13707. this._previousTextures[ name ] = texture;
  13708. this._textureNodes[ name ].updateTexture();
  13709. this._previousTextureNodes[ name ].updateTexture();
  13710. }
  13711. }
  13712. /**
  13713. * Returns the texture node for the given output name.
  13714. *
  13715. * @param {String} [name='output'] - The output name to get the texture node for.
  13716. * @return {TextureNode} The texture node.
  13717. */
  13718. getTextureNode( name = 'output' ) {
  13719. let textureNode = this._textureNodes[ name ];
  13720. if ( textureNode === undefined ) {
  13721. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  13722. textureNode.updateTexture();
  13723. this._textureNodes[ name ] = textureNode;
  13724. }
  13725. return textureNode;
  13726. }
  13727. /**
  13728. * Returns the previous texture node for the given output name.
  13729. *
  13730. * @param {String} [name='output'] - The output name to get the previous texture node for.
  13731. * @return {TextureNode} The previous texture node.
  13732. */
  13733. getPreviousTextureNode( name = 'output' ) {
  13734. let textureNode = this._previousTextureNodes[ name ];
  13735. if ( textureNode === undefined ) {
  13736. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  13737. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  13738. textureNode.updateTexture();
  13739. this._previousTextureNodes[ name ] = textureNode;
  13740. }
  13741. return textureNode;
  13742. }
  13743. /**
  13744. * Returns a viewZ node of this pass.
  13745. *
  13746. * @param {String} [name='depth'] - The output name to get the viewZ node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  13747. * @return {Node} The viewZ node.
  13748. */
  13749. getViewZNode( name = 'depth' ) {
  13750. let viewZNode = this._viewZNodes[ name ];
  13751. if ( viewZNode === undefined ) {
  13752. const cameraNear = this._cameraNear;
  13753. const cameraFar = this._cameraFar;
  13754. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  13755. }
  13756. return viewZNode;
  13757. }
  13758. /**
  13759. * Returns a linear depth node of this pass.
  13760. *
  13761. * @param {String} [name='depth'] - The output name to get the linear depth node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  13762. * @return {Node} The linear depth node.
  13763. */
  13764. getLinearDepthNode( name = 'depth' ) {
  13765. let linearDepthNode = this._linearDepthNodes[ name ];
  13766. if ( linearDepthNode === undefined ) {
  13767. const cameraNear = this._cameraNear;
  13768. const cameraFar = this._cameraFar;
  13769. const viewZNode = this.getViewZNode( name );
  13770. // TODO: just if ( builder.camera.isPerspectiveCamera )
  13771. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  13772. }
  13773. return linearDepthNode;
  13774. }
  13775. setup( { renderer } ) {
  13776. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  13777. // Disable MSAA for WebGL backend for now
  13778. if ( renderer.backend.isWebGLBackend === true ) {
  13779. this.renderTarget.samples = 0;
  13780. }
  13781. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  13782. }
  13783. updateBefore( frame ) {
  13784. const { renderer } = frame;
  13785. const { scene, camera } = this;
  13786. this._pixelRatio = renderer.getPixelRatio();
  13787. const size = renderer.getSize( _size );
  13788. this.setSize( size.width, size.height );
  13789. const currentRenderTarget = renderer.getRenderTarget();
  13790. const currentMRT = renderer.getMRT();
  13791. this._cameraNear.value = camera.near;
  13792. this._cameraFar.value = camera.far;
  13793. for ( const name in this._previousTextures ) {
  13794. this.toggleTexture( name );
  13795. }
  13796. renderer.setRenderTarget( this.renderTarget );
  13797. renderer.setMRT( this._mrt );
  13798. renderer.render( scene, camera );
  13799. renderer.setRenderTarget( currentRenderTarget );
  13800. renderer.setMRT( currentMRT );
  13801. }
  13802. /**
  13803. * Sets the size of the pass's render target. Honors the pixel ratio.
  13804. *
  13805. * @param {Number} width - The width to set.
  13806. * @param {Number} height - The height to set.
  13807. */
  13808. setSize( width, height ) {
  13809. this._width = width;
  13810. this._height = height;
  13811. const effectiveWidth = this._width * this._pixelRatio;
  13812. const effectiveHeight = this._height * this._pixelRatio;
  13813. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  13814. }
  13815. /**
  13816. * Sets the pixel ratio the pass's render target and updates the size.
  13817. *
  13818. * @param {Number} pixelRatio - The pixel ratio to set.
  13819. */
  13820. setPixelRatio( pixelRatio ) {
  13821. this._pixelRatio = pixelRatio;
  13822. this.setSize( this._width, this._height );
  13823. }
  13824. /**
  13825. * Frees internal resources. Should be called when the node is no longer in use.
  13826. */
  13827. dispose() {
  13828. this.renderTarget.dispose();
  13829. }
  13830. }
  13831. PassNode.COLOR = 'color';
  13832. PassNode.DEPTH = 'depth';
  13833. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  13834. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  13835. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  13836. /**
  13837. * Represents a render pass for producing a toon outline effect on compatible objects.
  13838. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  13839. * will receive the outline.
  13840. *
  13841. * ```js
  13842. * const postProcessing = new PostProcessing( renderer );
  13843. *
  13844. * const scenePass = toonOutlinePass( scene, camera );
  13845. *
  13846. * postProcessing.outputNode = scenePass;
  13847. * ```
  13848. * @augments PassNode
  13849. */
  13850. class ToonOutlinePassNode extends PassNode {
  13851. static get type() {
  13852. return 'ToonOutlinePassNode';
  13853. }
  13854. /**
  13855. * Constructs a new outline pass node.
  13856. *
  13857. * @param {Scene} scene - A reference to the scene.
  13858. * @param {Camera} camera - A reference to the camera.
  13859. * @param {Node} colorNode - Defines the outline's color.
  13860. * @param {Node} thicknessNode - Defines the outline's thickness.
  13861. * @param {Node} alphaNode - Defines the outline's alpha.
  13862. */
  13863. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  13864. super( PassNode.COLOR, scene, camera );
  13865. /**
  13866. * Defines the outline's color.
  13867. *
  13868. * @type {Node}
  13869. */
  13870. this.colorNode = colorNode;
  13871. /**
  13872. * Defines the outline's thickness.
  13873. *
  13874. * @type {Node}
  13875. */
  13876. this.thicknessNode = thicknessNode;
  13877. /**
  13878. * Defines the outline's alpha.
  13879. *
  13880. * @type {Node}
  13881. */
  13882. this.alphaNode = alphaNode;
  13883. /**
  13884. * An internal material cache.
  13885. *
  13886. * @private
  13887. * @type {WeakMap}
  13888. */
  13889. this._materialCache = new WeakMap();
  13890. }
  13891. updateBefore( frame ) {
  13892. const { renderer } = frame;
  13893. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  13894. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  13895. // only render outline for supported materials
  13896. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  13897. if ( material.wireframe === false ) {
  13898. const outlineMaterial = this._getOutlineMaterial( material );
  13899. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  13900. }
  13901. }
  13902. // default
  13903. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  13904. } );
  13905. super.updateBefore( frame );
  13906. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  13907. }
  13908. /**
  13909. * Creates the material used for outline rendering.
  13910. *
  13911. * @private
  13912. * @return {NodeMaterial} The outline material.
  13913. */
  13914. _createMaterial() {
  13915. const material = new NodeMaterial();
  13916. material.isMeshToonOutlineMaterial = true;
  13917. material.name = 'Toon_Outline';
  13918. material.side = BackSide;
  13919. // vertex node
  13920. const outlineNormal = normalLocal.negate();
  13921. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  13922. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  13923. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  13924. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  13925. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  13926. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  13927. // color node
  13928. material.colorNode = vec4( this.colorNode, this.alphaNode );
  13929. return material;
  13930. }
  13931. /**
  13932. * For the given toon material, this method returns a correspoding
  13933. * outline material.
  13934. *
  13935. * @private
  13936. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  13937. * @return {NodeMaterial} The outline material.
  13938. */
  13939. _getOutlineMaterial( originalMaterial ) {
  13940. let outlineMaterial = this._materialCache.get( originalMaterial );
  13941. if ( outlineMaterial === undefined ) {
  13942. outlineMaterial = this._createMaterial();
  13943. this._materialCache.set( originalMaterial, outlineMaterial );
  13944. }
  13945. return outlineMaterial;
  13946. }
  13947. }
  13948. 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 ) ) );
  13949. /** @module ToneMappingFunctions **/
  13950. /**
  13951. * Linear tone mapping, exposure only.
  13952. *
  13953. * @method
  13954. * @param {vec3} color - The color that should be tone mapped.
  13955. * @param {float} exposure - The exposure.
  13956. * @return {vec3} The tone mapped color.
  13957. */
  13958. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  13959. return color.mul( exposure ).clamp();
  13960. } ).setLayout( {
  13961. name: 'linearToneMapping',
  13962. type: 'vec3',
  13963. inputs: [
  13964. { name: 'color', type: 'vec3' },
  13965. { name: 'exposure', type: 'float' }
  13966. ]
  13967. } );
  13968. /**
  13969. * Reinhard tone mapping.
  13970. *
  13971. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  13972. *
  13973. * @method
  13974. * @param {vec3} color - The color that should be tone mapped.
  13975. * @param {float} exposure - The exposure.
  13976. * @return {vec3} The tone mapped color.
  13977. */
  13978. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  13979. color = color.mul( exposure );
  13980. return color.div( color.add( 1.0 ) ).clamp();
  13981. } ).setLayout( {
  13982. name: 'reinhardToneMapping',
  13983. type: 'vec3',
  13984. inputs: [
  13985. { name: 'color', type: 'vec3' },
  13986. { name: 'exposure', type: 'float' }
  13987. ]
  13988. } );
  13989. /**
  13990. * Cineon tone mapping.
  13991. *
  13992. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  13993. *
  13994. * @method
  13995. * @param {vec3} color - The color that should be tone mapped.
  13996. * @param {float} exposure - The exposure.
  13997. * @return {vec3} The tone mapped color.
  13998. */
  13999. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14000. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  14001. color = color.mul( exposure );
  14002. color = color.sub( 0.004 ).max( 0.0 );
  14003. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  14004. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  14005. return a.div( b ).pow( 2.2 );
  14006. } ).setLayout( {
  14007. name: 'cineonToneMapping',
  14008. type: 'vec3',
  14009. inputs: [
  14010. { name: 'color', type: 'vec3' },
  14011. { name: 'exposure', type: 'float' }
  14012. ]
  14013. } );
  14014. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  14015. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14016. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  14017. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  14018. return a.div( b );
  14019. } );
  14020. /**
  14021. * ACESFilmic tone mapping.
  14022. *
  14023. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  14024. *
  14025. * @method
  14026. * @param {vec3} color - The color that should be tone mapped.
  14027. * @param {float} exposure - The exposure.
  14028. * @return {vec3} The tone mapped color.
  14029. */
  14030. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14031. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  14032. const ACESInputMat = mat3(
  14033. 0.59719, 0.35458, 0.04823,
  14034. 0.07600, 0.90834, 0.01566,
  14035. 0.02840, 0.13383, 0.83777
  14036. );
  14037. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  14038. const ACESOutputMat = mat3(
  14039. 1.60475, - 0.53108, - 0.07367,
  14040. - 0.10208, 1.10813, - 0.00605,
  14041. - 0.00327, - 0.07276, 1.07602
  14042. );
  14043. color = color.mul( exposure ).div( 0.6 );
  14044. color = ACESInputMat.mul( color );
  14045. // Apply RRT and ODT
  14046. color = RRTAndODTFit( color );
  14047. color = ACESOutputMat.mul( color );
  14048. // Clamp to [0, 1]
  14049. return color.clamp();
  14050. } ).setLayout( {
  14051. name: 'acesFilmicToneMapping',
  14052. type: 'vec3',
  14053. inputs: [
  14054. { name: 'color', type: 'vec3' },
  14055. { name: 'exposure', type: 'float' }
  14056. ]
  14057. } );
  14058. 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 ) );
  14059. 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 ) );
  14060. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  14061. const x = vec3( x_immutable ).toVar();
  14062. const x2 = vec3( x.mul( x ) ).toVar();
  14063. const x4 = vec3( x2.mul( x2 ) ).toVar();
  14064. 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 ) ) ) );
  14065. } );
  14066. /**
  14067. * AgX tone mapping.
  14068. *
  14069. * @method
  14070. * @param {vec3} color - The color that should be tone mapped.
  14071. * @param {float} exposure - The exposure.
  14072. * @return {vec3} The tone mapped color.
  14073. */
  14074. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14075. const colortone = vec3( color ).toVar();
  14076. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  14077. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  14078. const AgxMinEv = float( - 12.47393 );
  14079. const AgxMaxEv = float( 4.026069 );
  14080. colortone.mulAssign( exposure );
  14081. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  14082. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  14083. colortone.assign( max$1( colortone, 1e-10 ) );
  14084. colortone.assign( log2( colortone ) );
  14085. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  14086. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  14087. colortone.assign( agxDefaultContrastApprox( colortone ) );
  14088. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  14089. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  14090. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  14091. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  14092. return colortone;
  14093. } ).setLayout( {
  14094. name: 'agxToneMapping',
  14095. type: 'vec3',
  14096. inputs: [
  14097. { name: 'color', type: 'vec3' },
  14098. { name: 'exposure', type: 'float' }
  14099. ]
  14100. } );
  14101. /**
  14102. * Neutral tone mapping.
  14103. *
  14104. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  14105. *
  14106. * @method
  14107. * @param {vec3} color - The color that should be tone mapped.
  14108. * @param {float} exposure - The exposure.
  14109. * @return {vec3} The tone mapped color.
  14110. */
  14111. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14112. const StartCompression = float( 0.8 - 0.04 );
  14113. const Desaturation = float( 0.15 );
  14114. color = color.mul( exposure );
  14115. const x = min$1( color.r, min$1( color.g, color.b ) );
  14116. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  14117. color.subAssign( offset );
  14118. const peak = max$1( color.r, max$1( color.g, color.b ) );
  14119. If( peak.lessThan( StartCompression ), () => {
  14120. return color;
  14121. } );
  14122. const d = sub( 1, StartCompression );
  14123. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  14124. color.mulAssign( newPeak.div( peak ) );
  14125. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  14126. return mix( color, vec3( newPeak ), g );
  14127. } ).setLayout( {
  14128. name: 'neutralToneMapping',
  14129. type: 'vec3',
  14130. inputs: [
  14131. { name: 'color', type: 'vec3' },
  14132. { name: 'exposure', type: 'float' }
  14133. ]
  14134. } );
  14135. /**
  14136. * This class represents native code sections. It is the base
  14137. * class for modules like {@link FunctionNode} which allows to implement
  14138. * functions with native shader languages.
  14139. *
  14140. * @augments Node
  14141. */
  14142. class CodeNode extends Node {
  14143. static get type() {
  14144. return 'CodeNode';
  14145. }
  14146. /**
  14147. * Constructs a new code node.
  14148. *
  14149. * @param {String} [code=''] - The native code.
  14150. * @param {Array<Node>} [includes=[]] - An array of includes.
  14151. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  14152. */
  14153. constructor( code = '', includes = [], language = '' ) {
  14154. super( 'code' );
  14155. /**
  14156. * This flag can be used for type testing.
  14157. *
  14158. * @type {Boolean}
  14159. * @readonly
  14160. * @default true
  14161. */
  14162. this.isCodeNode = true;
  14163. /**
  14164. * The native code.
  14165. *
  14166. * @type {String}
  14167. * @default ''
  14168. */
  14169. this.code = code;
  14170. /**
  14171. * An array of includes
  14172. *
  14173. * @type {Array<Node>}
  14174. * @default []
  14175. */
  14176. this.includes = includes;
  14177. /**
  14178. * The used language.
  14179. *
  14180. * @type {('js'|'wgsl'|'glsl')}
  14181. * @default ''
  14182. */
  14183. this.language = language;
  14184. }
  14185. /**
  14186. * The method is overwritten so it always returns `true`.
  14187. *
  14188. * @return {Boolean} Whether this node is global or not.
  14189. */
  14190. isGlobal() {
  14191. return true;
  14192. }
  14193. /**
  14194. * Sets the includes of this code node.
  14195. *
  14196. * @param {Array<Node>} includes - The includes to set.
  14197. * @return {CodeNode} A reference to this node.
  14198. */
  14199. setIncludes( includes ) {
  14200. this.includes = includes;
  14201. return this;
  14202. }
  14203. /**
  14204. * Returns the includes of this code node.
  14205. *
  14206. * @param {NodeBuilder} builder - The current node builder.
  14207. * @return {Array<Node>} The includes.
  14208. */
  14209. getIncludes( /*builder*/ ) {
  14210. return this.includes;
  14211. }
  14212. generate( builder ) {
  14213. const includes = this.getIncludes( builder );
  14214. for ( const include of includes ) {
  14215. include.build( builder );
  14216. }
  14217. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  14218. nodeCode.code = this.code;
  14219. return nodeCode.code;
  14220. }
  14221. serialize( data ) {
  14222. super.serialize( data );
  14223. data.code = this.code;
  14224. data.language = this.language;
  14225. }
  14226. deserialize( data ) {
  14227. super.deserialize( data );
  14228. this.code = data.code;
  14229. this.language = data.language;
  14230. }
  14231. }
  14232. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  14233. const js = ( src, includes ) => code( src, includes, 'js' );
  14234. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  14235. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  14236. /**
  14237. * This class represents a native shader function. It can be used to implement
  14238. * certain aspects of a node material with native shader code. There are two predefined
  14239. * TSL functions for easier usage.
  14240. *
  14241. * - `wgslFn`: Creates a WGSL function node.
  14242. * - `glslFn`: Creates a GLSL function node.
  14243. *
  14244. * A basic example with one include looks like so:
  14245. *
  14246. * ```js
  14247. * const desaturateWGSLFn = wgslFn( `
  14248. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  14249. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  14250. * return vec3<f32>( dot( lum, color ) );
  14251. * }`
  14252. *);
  14253. * const someWGSLFn = wgslFn( `
  14254. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  14255. * return desaturate( color );
  14256. * }
  14257. * `, [ desaturateWGSLFn ] );
  14258. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  14259. *```
  14260. * @augments CodeNode
  14261. */
  14262. class FunctionNode extends CodeNode {
  14263. static get type() {
  14264. return 'FunctionNode';
  14265. }
  14266. /**
  14267. * Constructs a new function node.
  14268. *
  14269. * @param {String} [code=''] - The native code.
  14270. * @param {Array<Node>} [includes=[]] - An array of includes.
  14271. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  14272. */
  14273. constructor( code = '', includes = [], language = '' ) {
  14274. super( code, includes, language );
  14275. }
  14276. getNodeType( builder ) {
  14277. return this.getNodeFunction( builder ).type;
  14278. }
  14279. /**
  14280. * Returns the inputs of this function node.
  14281. *
  14282. * @param {NodeBuilder} builder - The current node builder.
  14283. * @return {Array<NodeFunctionInput>} The inputs.
  14284. */
  14285. getInputs( builder ) {
  14286. return this.getNodeFunction( builder ).inputs;
  14287. }
  14288. /**
  14289. * Returns the node function for this function node.
  14290. *
  14291. * @param {NodeBuilder} builder - The current node builder.
  14292. * @return {NodeFunction} The node function.
  14293. */
  14294. getNodeFunction( builder ) {
  14295. const nodeData = builder.getDataFromNode( this );
  14296. let nodeFunction = nodeData.nodeFunction;
  14297. if ( nodeFunction === undefined ) {
  14298. nodeFunction = builder.parser.parseFunction( this.code );
  14299. nodeData.nodeFunction = nodeFunction;
  14300. }
  14301. return nodeFunction;
  14302. }
  14303. generate( builder, output ) {
  14304. super.generate( builder );
  14305. const nodeFunction = this.getNodeFunction( builder );
  14306. const name = nodeFunction.name;
  14307. const type = nodeFunction.type;
  14308. const nodeCode = builder.getCodeFromNode( this, type );
  14309. if ( name !== '' ) {
  14310. // use a custom property name
  14311. nodeCode.name = name;
  14312. }
  14313. const propertyName = builder.getPropertyName( nodeCode );
  14314. const code = this.getNodeFunction( builder ).getCode( propertyName );
  14315. nodeCode.code = code + '\n';
  14316. if ( output === 'property' ) {
  14317. return propertyName;
  14318. } else {
  14319. return builder.format( `${ propertyName }()`, type, output );
  14320. }
  14321. }
  14322. }
  14323. const nativeFn = ( code, includes = [], language = '' ) => {
  14324. for ( let i = 0; i < includes.length; i ++ ) {
  14325. const include = includes[ i ];
  14326. // TSL Function: glslFn, wgslFn
  14327. if ( typeof include === 'function' ) {
  14328. includes[ i ] = include.functionNode;
  14329. }
  14330. }
  14331. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  14332. const fn = ( ...params ) => functionNode.call( ...params );
  14333. fn.functionNode = functionNode;
  14334. return fn;
  14335. };
  14336. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  14337. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  14338. class ScriptableValueNode extends Node {
  14339. static get type() {
  14340. return 'ScriptableValueNode';
  14341. }
  14342. constructor( value = null ) {
  14343. super();
  14344. this._value = value;
  14345. this._cache = null;
  14346. this.inputType = null;
  14347. this.outputType = null;
  14348. this.events = new EventDispatcher();
  14349. this.isScriptableValueNode = true;
  14350. }
  14351. get isScriptableOutputNode() {
  14352. return this.outputType !== null;
  14353. }
  14354. set value( val ) {
  14355. if ( this._value === val ) return;
  14356. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  14357. URL.revokeObjectURL( this._cache );
  14358. this._cache = null;
  14359. }
  14360. this._value = val;
  14361. this.events.dispatchEvent( { type: 'change' } );
  14362. this.refresh();
  14363. }
  14364. get value() {
  14365. return this._value;
  14366. }
  14367. refresh() {
  14368. this.events.dispatchEvent( { type: 'refresh' } );
  14369. }
  14370. getValue() {
  14371. const value = this.value;
  14372. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  14373. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  14374. } else if ( value && value.value !== null && value.value !== undefined && (
  14375. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  14376. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  14377. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  14378. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  14379. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  14380. ( this.inputType === 'Color' && value.value.isColor ) ||
  14381. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  14382. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  14383. ) ) {
  14384. return value.value;
  14385. }
  14386. return this._cache || value;
  14387. }
  14388. getNodeType( builder ) {
  14389. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  14390. }
  14391. setup() {
  14392. return this.value && this.value.isNode ? this.value : float();
  14393. }
  14394. serialize( data ) {
  14395. super.serialize( data );
  14396. if ( this.value !== null ) {
  14397. if ( this.inputType === 'ArrayBuffer' ) {
  14398. data.value = arrayBufferToBase64( this.value );
  14399. } else {
  14400. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  14401. }
  14402. } else {
  14403. data.value = null;
  14404. }
  14405. data.inputType = this.inputType;
  14406. data.outputType = this.outputType;
  14407. }
  14408. deserialize( data ) {
  14409. super.deserialize( data );
  14410. let value = null;
  14411. if ( data.value !== null ) {
  14412. if ( data.inputType === 'ArrayBuffer' ) {
  14413. value = base64ToArrayBuffer( data.value );
  14414. } else if ( data.inputType === 'Texture' ) {
  14415. value = data.meta.textures[ data.value ];
  14416. } else {
  14417. value = data.meta.nodes[ data.value ] || null;
  14418. }
  14419. }
  14420. this.value = value;
  14421. this.inputType = data.inputType;
  14422. this.outputType = data.outputType;
  14423. }
  14424. }
  14425. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  14426. class Resources extends Map {
  14427. get( key, callback = null, ...params ) {
  14428. if ( this.has( key ) ) return super.get( key );
  14429. if ( callback !== null ) {
  14430. const value = callback( ...params );
  14431. this.set( key, value );
  14432. return value;
  14433. }
  14434. }
  14435. }
  14436. class Parameters {
  14437. constructor( scriptableNode ) {
  14438. this.scriptableNode = scriptableNode;
  14439. }
  14440. get parameters() {
  14441. return this.scriptableNode.parameters;
  14442. }
  14443. get layout() {
  14444. return this.scriptableNode.getLayout();
  14445. }
  14446. getInputLayout( id ) {
  14447. return this.scriptableNode.getInputLayout( id );
  14448. }
  14449. get( name ) {
  14450. const param = this.parameters[ name ];
  14451. const value = param ? param.getValue() : null;
  14452. return value;
  14453. }
  14454. }
  14455. const ScriptableNodeResources = new Resources();
  14456. class ScriptableNode extends Node {
  14457. static get type() {
  14458. return 'ScriptableNode';
  14459. }
  14460. constructor( codeNode = null, parameters = {} ) {
  14461. super();
  14462. this.codeNode = codeNode;
  14463. this.parameters = parameters;
  14464. this._local = new Resources();
  14465. this._output = scriptableValue();
  14466. this._outputs = {};
  14467. this._source = this.source;
  14468. this._method = null;
  14469. this._object = null;
  14470. this._value = null;
  14471. this._needsOutputUpdate = true;
  14472. this.onRefresh = this.onRefresh.bind( this );
  14473. this.isScriptableNode = true;
  14474. }
  14475. get source() {
  14476. return this.codeNode ? this.codeNode.code : '';
  14477. }
  14478. setLocal( name, value ) {
  14479. return this._local.set( name, value );
  14480. }
  14481. getLocal( name ) {
  14482. return this._local.get( name );
  14483. }
  14484. onRefresh() {
  14485. this._refresh();
  14486. }
  14487. getInputLayout( id ) {
  14488. for ( const element of this.getLayout() ) {
  14489. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  14490. return element;
  14491. }
  14492. }
  14493. }
  14494. getOutputLayout( id ) {
  14495. for ( const element of this.getLayout() ) {
  14496. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  14497. return element;
  14498. }
  14499. }
  14500. }
  14501. setOutput( name, value ) {
  14502. const outputs = this._outputs;
  14503. if ( outputs[ name ] === undefined ) {
  14504. outputs[ name ] = scriptableValue( value );
  14505. } else {
  14506. outputs[ name ].value = value;
  14507. }
  14508. return this;
  14509. }
  14510. getOutput( name ) {
  14511. return this._outputs[ name ];
  14512. }
  14513. getParameter( name ) {
  14514. return this.parameters[ name ];
  14515. }
  14516. setParameter( name, value ) {
  14517. const parameters = this.parameters;
  14518. if ( value && value.isScriptableNode ) {
  14519. this.deleteParameter( name );
  14520. parameters[ name ] = value;
  14521. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  14522. } else if ( value && value.isScriptableValueNode ) {
  14523. this.deleteParameter( name );
  14524. parameters[ name ] = value;
  14525. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  14526. } else if ( parameters[ name ] === undefined ) {
  14527. parameters[ name ] = scriptableValue( value );
  14528. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  14529. } else {
  14530. parameters[ name ].value = value;
  14531. }
  14532. return this;
  14533. }
  14534. getValue() {
  14535. return this.getDefaultOutput().getValue();
  14536. }
  14537. deleteParameter( name ) {
  14538. let valueNode = this.parameters[ name ];
  14539. if ( valueNode ) {
  14540. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  14541. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  14542. }
  14543. return this;
  14544. }
  14545. clearParameters() {
  14546. for ( const name of Object.keys( this.parameters ) ) {
  14547. this.deleteParameter( name );
  14548. }
  14549. this.needsUpdate = true;
  14550. return this;
  14551. }
  14552. call( name, ...params ) {
  14553. const object = this.getObject();
  14554. const method = object[ name ];
  14555. if ( typeof method === 'function' ) {
  14556. return method( ...params );
  14557. }
  14558. }
  14559. async callAsync( name, ...params ) {
  14560. const object = this.getObject();
  14561. const method = object[ name ];
  14562. if ( typeof method === 'function' ) {
  14563. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  14564. }
  14565. }
  14566. getNodeType( builder ) {
  14567. return this.getDefaultOutputNode().getNodeType( builder );
  14568. }
  14569. refresh( output = null ) {
  14570. if ( output !== null ) {
  14571. this.getOutput( output ).refresh();
  14572. } else {
  14573. this._refresh();
  14574. }
  14575. }
  14576. getObject() {
  14577. if ( this.needsUpdate ) this.dispose();
  14578. if ( this._object !== null ) return this._object;
  14579. //
  14580. const refresh = () => this.refresh();
  14581. const setOutput = ( id, value ) => this.setOutput( id, value );
  14582. const parameters = new Parameters( this );
  14583. const THREE = ScriptableNodeResources.get( 'THREE' );
  14584. const TSL = ScriptableNodeResources.get( 'TSL' );
  14585. const method = this.getMethod( this.codeNode );
  14586. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  14587. this._object = method( ...params );
  14588. const layout = this._object.layout;
  14589. if ( layout ) {
  14590. if ( layout.cache === false ) {
  14591. this._local.clear();
  14592. }
  14593. // default output
  14594. this._output.outputType = layout.outputType || null;
  14595. if ( Array.isArray( layout.elements ) ) {
  14596. for ( const element of layout.elements ) {
  14597. const id = element.id || element.name;
  14598. if ( element.inputType ) {
  14599. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  14600. this.getParameter( id ).inputType = element.inputType;
  14601. }
  14602. if ( element.outputType ) {
  14603. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  14604. this.getOutput( id ).outputType = element.outputType;
  14605. }
  14606. }
  14607. }
  14608. }
  14609. return this._object;
  14610. }
  14611. deserialize( data ) {
  14612. super.deserialize( data );
  14613. for ( const name in this.parameters ) {
  14614. let valueNode = this.parameters[ name ];
  14615. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  14616. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  14617. }
  14618. }
  14619. getLayout() {
  14620. return this.getObject().layout;
  14621. }
  14622. getDefaultOutputNode() {
  14623. const output = this.getDefaultOutput().value;
  14624. if ( output && output.isNode ) {
  14625. return output;
  14626. }
  14627. return float();
  14628. }
  14629. getDefaultOutput() {
  14630. return this._exec()._output;
  14631. }
  14632. getMethod() {
  14633. if ( this.needsUpdate ) this.dispose();
  14634. if ( this._method !== null ) return this._method;
  14635. //
  14636. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  14637. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  14638. const properties = interfaceProps.join( ', ' );
  14639. const declarations = 'var ' + properties + '; var output = {};\n';
  14640. const returns = '\nreturn { ...output, ' + properties + ' };';
  14641. const code = declarations + this.codeNode.code + returns;
  14642. //
  14643. this._method = new Function( ...parametersProps, code );
  14644. return this._method;
  14645. }
  14646. dispose() {
  14647. if ( this._method === null ) return;
  14648. if ( this._object && typeof this._object.dispose === 'function' ) {
  14649. this._object.dispose();
  14650. }
  14651. this._method = null;
  14652. this._object = null;
  14653. this._source = null;
  14654. this._value = null;
  14655. this._needsOutputUpdate = true;
  14656. this._output.value = null;
  14657. this._outputs = {};
  14658. }
  14659. setup() {
  14660. return this.getDefaultOutputNode();
  14661. }
  14662. getCacheKey( force ) {
  14663. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  14664. for ( const param in this.parameters ) {
  14665. values.push( this.parameters[ param ].getCacheKey( force ) );
  14666. }
  14667. return hashArray( values );
  14668. }
  14669. set needsUpdate( value ) {
  14670. if ( value === true ) this.dispose();
  14671. }
  14672. get needsUpdate() {
  14673. return this.source !== this._source;
  14674. }
  14675. _exec() {
  14676. if ( this.codeNode === null ) return this;
  14677. if ( this._needsOutputUpdate === true ) {
  14678. this._value = this.call( 'main' );
  14679. this._needsOutputUpdate = false;
  14680. }
  14681. this._output.value = this._value;
  14682. return this;
  14683. }
  14684. _refresh() {
  14685. this.needsUpdate = true;
  14686. this._exec();
  14687. this._output.refresh();
  14688. }
  14689. }
  14690. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  14691. /**
  14692. * This class can be used to configure a fog for the scene.
  14693. * Nodes of this type are assigned to `Scene.fogNode`.
  14694. *
  14695. * @augments Node
  14696. */
  14697. class FogNode extends Node {
  14698. static get type() {
  14699. return 'FogNode';
  14700. }
  14701. /**
  14702. * Constructs a new fog node.
  14703. *
  14704. * @param {Node} colorNode - Defines the color of the fog.
  14705. * @param {Node} factorNode - Defines how the fog is factored in the scene.
  14706. */
  14707. constructor( colorNode, factorNode ) {
  14708. super( 'float' );
  14709. /**
  14710. * This flag can be used for type testing.
  14711. *
  14712. * @type {Boolean}
  14713. * @readonly
  14714. * @default true
  14715. */
  14716. this.isFogNode = true;
  14717. /**
  14718. * Defines the color of the fog.
  14719. *
  14720. * @type {Node?}
  14721. */
  14722. this.colorNode = colorNode;
  14723. /**
  14724. * Defines how the fog is factored in the scene.
  14725. *
  14726. * @type {Node?}
  14727. */
  14728. this.factorNode = factorNode;
  14729. }
  14730. /**
  14731. * Returns a node that represents the `z` coordinate in view space
  14732. * for the current fragment. It's a different representation of the
  14733. * default depth value.
  14734. *
  14735. * This value can be part of a computation that defines how the fog
  14736. * density increases when moving away from the camera.
  14737. *
  14738. * @param {NodeBuilder} builder - The current node builder.
  14739. * @return {Node} The viewZ node.
  14740. */
  14741. getViewZNode( builder ) {
  14742. let viewZ;
  14743. const getViewZ = builder.context.getViewZ;
  14744. if ( getViewZ !== undefined ) {
  14745. viewZ = getViewZ( this );
  14746. }
  14747. return ( viewZ || positionView.z ).negate();
  14748. }
  14749. setup() {
  14750. return this.factorNode;
  14751. }
  14752. }
  14753. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  14754. /**
  14755. * Represents a range fog. The fog is smoothly interpolated
  14756. * between a range defined via near and far values.
  14757. *
  14758. * @augments FogNode
  14759. */
  14760. class FogRangeNode extends FogNode {
  14761. static get type() {
  14762. return 'FogRangeNode';
  14763. }
  14764. /**
  14765. * Constructs a new range node.
  14766. *
  14767. * @param {Node} colorNode - Defines the color of the fog.
  14768. * @param {Node} nearNode - Defines the near value.
  14769. * @param {Node} farNode - Defines the far value.
  14770. */
  14771. constructor( colorNode, nearNode, farNode ) {
  14772. super( colorNode, null );
  14773. /**
  14774. * This flag can be used for type testing.
  14775. *
  14776. * @type {Boolean}
  14777. * @readonly
  14778. * @default true
  14779. */
  14780. this.isFogRangeNode = true;
  14781. /**
  14782. * Defines the near value.
  14783. *
  14784. * @type {Node}
  14785. */
  14786. this.nearNode = nearNode;
  14787. /**
  14788. * Defines the far value.
  14789. *
  14790. * @type {Node}
  14791. */
  14792. this.farNode = farNode;
  14793. }
  14794. setup( builder ) {
  14795. const viewZ = this.getViewZNode( builder );
  14796. return smoothstep( this.nearNode, this.farNode, viewZ );
  14797. }
  14798. }
  14799. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  14800. /**
  14801. * Represents an exponential squared fog. This type of fog gives
  14802. * a clear view near the camera and a faster than exponentially
  14803. * densening fog farther from the camera.
  14804. *
  14805. * @augments FogNode
  14806. */
  14807. class FogExp2Node extends FogNode {
  14808. static get type() {
  14809. return 'FogExp2Node';
  14810. }
  14811. /**
  14812. * Constructs a new exponential squared fog node.
  14813. *
  14814. * @param {Node} colorNode - Defines the color of the fog.
  14815. * @param {Node} densityNode - Defines the fog density.
  14816. */
  14817. constructor( colorNode, densityNode ) {
  14818. super( colorNode, null );
  14819. /**
  14820. * This flag can be used for type testing.
  14821. *
  14822. * @type {Boolean}
  14823. * @readonly
  14824. * @default true
  14825. */
  14826. this.isFogExp2Node = true;
  14827. /**
  14828. * Defines the fog density.
  14829. *
  14830. * @type {Node}
  14831. */
  14832. this.densityNode = densityNode;
  14833. }
  14834. setup( builder ) {
  14835. const viewZ = this.getViewZNode( builder );
  14836. const density = this.densityNode;
  14837. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  14838. }
  14839. }
  14840. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  14841. let min = null;
  14842. let max = null;
  14843. class RangeNode extends Node {
  14844. static get type() {
  14845. return 'RangeNode';
  14846. }
  14847. constructor( minNode = float(), maxNode = float() ) {
  14848. super();
  14849. this.minNode = minNode;
  14850. this.maxNode = maxNode;
  14851. }
  14852. getVectorLength( builder ) {
  14853. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  14854. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  14855. return minLength > maxLength ? minLength : maxLength;
  14856. }
  14857. getNodeType( builder ) {
  14858. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  14859. }
  14860. setup( builder ) {
  14861. const object = builder.object;
  14862. let output = null;
  14863. if ( object.count > 1 ) {
  14864. const minValue = this.minNode.value;
  14865. const maxValue = this.maxNode.value;
  14866. const minLength = builder.getTypeLength( getValueType( minValue ) );
  14867. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  14868. min = min || new Vector4();
  14869. max = max || new Vector4();
  14870. min.setScalar( 0 );
  14871. max.setScalar( 0 );
  14872. if ( minLength === 1 ) min.setScalar( minValue );
  14873. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  14874. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  14875. if ( maxLength === 1 ) max.setScalar( maxValue );
  14876. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  14877. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  14878. const stride = 4;
  14879. const length = stride * object.count;
  14880. const array = new Float32Array( length );
  14881. for ( let i = 0; i < length; i ++ ) {
  14882. const index = i % stride;
  14883. const minElementValue = min.getComponent( index );
  14884. const maxElementValue = max.getComponent( index );
  14885. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  14886. }
  14887. const nodeType = this.getNodeType( builder );
  14888. if ( object.count <= 4096 ) {
  14889. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  14890. } else {
  14891. // TODO: Improve anonymous buffer attribute creation removing this part
  14892. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  14893. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  14894. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  14895. }
  14896. } else {
  14897. output = float( 0 );
  14898. }
  14899. return output;
  14900. }
  14901. }
  14902. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  14903. class ComputeBuiltinNode extends Node {
  14904. static get type() {
  14905. return 'ComputeBuiltinNode';
  14906. }
  14907. constructor( builtinName, nodeType ) {
  14908. super( nodeType );
  14909. this._builtinName = builtinName;
  14910. }
  14911. getHash( builder ) {
  14912. return this.getBuiltinName( builder );
  14913. }
  14914. getNodeType( /*builder*/ ) {
  14915. return this.nodeType;
  14916. }
  14917. setBuiltinName( builtinName ) {
  14918. this._builtinName = builtinName;
  14919. return this;
  14920. }
  14921. getBuiltinName( /*builder*/ ) {
  14922. return this._builtinName;
  14923. }
  14924. hasBuiltin( builder ) {
  14925. builder.hasBuiltin( this._builtinName );
  14926. }
  14927. generate( builder, output ) {
  14928. const builtinName = this.getBuiltinName( builder );
  14929. const nodeType = this.getNodeType( builder );
  14930. if ( builder.shaderStage === 'compute' ) {
  14931. return builder.format( builtinName, nodeType, output );
  14932. } else {
  14933. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  14934. return builder.generateConst( nodeType );
  14935. }
  14936. }
  14937. serialize( data ) {
  14938. super.serialize( data );
  14939. data.global = this.global;
  14940. data._builtinName = this._builtinName;
  14941. }
  14942. deserialize( data ) {
  14943. super.deserialize( data );
  14944. this.global = data.global;
  14945. this._builtinName = data._builtinName;
  14946. }
  14947. }
  14948. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  14949. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  14950. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  14951. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  14952. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  14953. class BarrierNode extends Node {
  14954. constructor( scope ) {
  14955. super();
  14956. this.scope = scope;
  14957. }
  14958. generate( builder ) {
  14959. const { scope } = this;
  14960. const { renderer } = builder;
  14961. if ( renderer.backend.isWebGLBackend === true ) {
  14962. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  14963. } else {
  14964. builder.addLineFlowCode( `${scope}Barrier()`, this );
  14965. }
  14966. }
  14967. }
  14968. const barrier = nodeProxy( BarrierNode );
  14969. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  14970. const storageBarrier = () => barrier( 'storage' ).append();
  14971. const textureBarrier = () => barrier( 'texture' ).append();
  14972. class WorkgroupInfoElementNode extends ArrayElementNode {
  14973. constructor( workgroupInfoNode, indexNode ) {
  14974. super( workgroupInfoNode, indexNode );
  14975. this.isWorkgroupInfoElementNode = true;
  14976. }
  14977. generate( builder, output ) {
  14978. let snippet;
  14979. const isAssignContext = builder.context.assign;
  14980. snippet = super.generate( builder );
  14981. if ( isAssignContext !== true ) {
  14982. const type = this.getNodeType( builder );
  14983. snippet = builder.format( snippet, type, output );
  14984. }
  14985. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  14986. return snippet;
  14987. }
  14988. }
  14989. class WorkgroupInfoNode extends Node {
  14990. constructor( scope, bufferType, bufferCount = 0 ) {
  14991. super( bufferType );
  14992. this.bufferType = bufferType;
  14993. this.bufferCount = bufferCount;
  14994. this.isWorkgroupInfoNode = true;
  14995. this.scope = scope;
  14996. }
  14997. label( name ) {
  14998. this.name = name;
  14999. return this;
  15000. }
  15001. getHash() {
  15002. return this.uuid;
  15003. }
  15004. setScope( scope ) {
  15005. this.scope = scope;
  15006. return this;
  15007. }
  15008. getInputType( /*builder*/ ) {
  15009. return `${this.scope}Array`;
  15010. }
  15011. element( indexNode ) {
  15012. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  15013. }
  15014. generate( builder ) {
  15015. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  15016. }
  15017. }
  15018. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  15019. class AtomicFunctionNode extends TempNode {
  15020. static get type() {
  15021. return 'AtomicFunctionNode';
  15022. }
  15023. constructor( method, pointerNode, valueNode, storeNode = null ) {
  15024. super( 'uint' );
  15025. this.method = method;
  15026. this.pointerNode = pointerNode;
  15027. this.valueNode = valueNode;
  15028. this.storeNode = storeNode;
  15029. }
  15030. getInputType( builder ) {
  15031. return this.pointerNode.getNodeType( builder );
  15032. }
  15033. getNodeType( builder ) {
  15034. return this.getInputType( builder );
  15035. }
  15036. generate( builder ) {
  15037. const method = this.method;
  15038. const type = this.getNodeType( builder );
  15039. const inputType = this.getInputType( builder );
  15040. const a = this.pointerNode;
  15041. const b = this.valueNode;
  15042. const params = [];
  15043. params.push( `&${ a.build( builder, inputType ) }` );
  15044. params.push( b.build( builder, inputType ) );
  15045. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  15046. if ( this.storeNode !== null ) {
  15047. const varSnippet = this.storeNode.build( builder, inputType );
  15048. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  15049. } else {
  15050. builder.addLineFlowCode( methodSnippet, this );
  15051. }
  15052. }
  15053. }
  15054. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  15055. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  15056. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  15057. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  15058. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  15059. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  15060. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  15061. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  15062. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  15063. const atomicNode = nodeProxy( AtomicFunctionNode );
  15064. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  15065. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  15066. node.append();
  15067. return node;
  15068. };
  15069. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  15070. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  15071. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  15072. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  15073. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  15074. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  15075. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  15076. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  15077. let uniformsLib;
  15078. function getLightData( light ) {
  15079. uniformsLib = uniformsLib || new WeakMap();
  15080. let uniforms = uniformsLib.get( light );
  15081. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  15082. return uniforms;
  15083. }
  15084. function lightShadowMatrix( light ) {
  15085. const data = getLightData( light );
  15086. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  15087. light.shadow.updateMatrices( light );
  15088. return light.shadow.matrix;
  15089. } ) );
  15090. }
  15091. function lightProjectionUV( light ) {
  15092. const data = getLightData( light );
  15093. if ( data.projectionUV === undefined ) {
  15094. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  15095. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  15096. }
  15097. return data.projectionUV;
  15098. }
  15099. function lightPosition( light ) {
  15100. const data = getLightData( light );
  15101. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  15102. }
  15103. function lightTargetPosition( light ) {
  15104. const data = getLightData( light );
  15105. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  15106. }
  15107. function lightViewPosition( light ) {
  15108. const data = getLightData( light );
  15109. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  15110. self.value = self.value || new Vector3();
  15111. self.value.setFromMatrixPosition( light.matrixWorld );
  15112. self.value.applyMatrix4( camera.matrixWorldInverse );
  15113. } ) );
  15114. }
  15115. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  15116. const sortLights = ( lights ) => {
  15117. return lights.sort( ( a, b ) => a.id - b.id );
  15118. };
  15119. const getLightNodeById = ( id, lightNodes ) => {
  15120. for ( const lightNode of lightNodes ) {
  15121. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  15122. return lightNode;
  15123. }
  15124. }
  15125. return null;
  15126. };
  15127. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  15128. class LightsNode extends Node {
  15129. static get type() {
  15130. return 'LightsNode';
  15131. }
  15132. constructor() {
  15133. super( 'vec3' );
  15134. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  15135. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  15136. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  15137. this._lights = [];
  15138. this._lightNodes = null;
  15139. this._lightNodesHash = null;
  15140. this.global = true;
  15141. }
  15142. /**
  15143. * Overwrites the default `customCacheKey()` implementation by including the
  15144. * light IDs into the cache key.
  15145. *
  15146. * @return {Number} The hash.
  15147. */
  15148. customCacheKey() {
  15149. const lightIDs = [];
  15150. for ( let i = 0; i < lights.length; i ++ ) {
  15151. lightIDs.push( lights[ i ].id );
  15152. }
  15153. return hashArray( lightIDs );
  15154. }
  15155. getHash( builder ) {
  15156. if ( this._lightNodesHash === null ) {
  15157. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  15158. const hash = [];
  15159. for ( const lightNode of this._lightNodes ) {
  15160. hash.push( lightNode.getSelf().getHash() );
  15161. }
  15162. this._lightNodesHash = 'lights-' + hash.join( ',' );
  15163. }
  15164. return this._lightNodesHash;
  15165. }
  15166. analyze( builder ) {
  15167. const properties = builder.getDataFromNode( this );
  15168. for ( const node of properties.nodes ) {
  15169. node.build( builder );
  15170. }
  15171. }
  15172. setupLightsNode( builder ) {
  15173. const lightNodes = [];
  15174. const previousLightNodes = this._lightNodes;
  15175. const lights = sortLights( this._lights );
  15176. const nodeLibrary = builder.renderer.library;
  15177. for ( const light of lights ) {
  15178. if ( light.isNode ) {
  15179. lightNodes.push( nodeObject( light ) );
  15180. } else {
  15181. let lightNode = null;
  15182. if ( previousLightNodes !== null ) {
  15183. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  15184. }
  15185. if ( lightNode === null ) {
  15186. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  15187. if ( lightNodeClass === null ) {
  15188. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  15189. continue;
  15190. }
  15191. let lightNode = null;
  15192. if ( ! _lightsNodeRef.has( light ) ) {
  15193. lightNode = nodeObject( new lightNodeClass( light ) );
  15194. _lightsNodeRef.set( light, lightNode );
  15195. } else {
  15196. lightNode = _lightsNodeRef.get( light );
  15197. }
  15198. lightNodes.push( lightNode );
  15199. }
  15200. }
  15201. }
  15202. this._lightNodes = lightNodes;
  15203. }
  15204. setupLights( builder, lightNodes ) {
  15205. for ( const lightNode of lightNodes ) {
  15206. lightNode.build( builder );
  15207. }
  15208. }
  15209. setup( builder ) {
  15210. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  15211. const context = builder.context;
  15212. const lightingModel = context.lightingModel;
  15213. let outgoingLightNode = this.outgoingLightNode;
  15214. if ( lightingModel ) {
  15215. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  15216. context.outgoingLight = outgoingLightNode;
  15217. const stack = builder.addStack();
  15218. //
  15219. const properties = builder.getDataFromNode( this );
  15220. properties.nodes = stack.nodes;
  15221. //
  15222. lightingModel.start( context, stack, builder );
  15223. // lights
  15224. this.setupLights( builder, _lightNodes );
  15225. //
  15226. lightingModel.indirect( context, stack, builder );
  15227. //
  15228. const { backdrop, backdropAlpha } = context;
  15229. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  15230. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  15231. if ( backdrop !== null ) {
  15232. if ( backdropAlpha !== null ) {
  15233. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  15234. } else {
  15235. totalDiffuse = vec3( backdrop );
  15236. }
  15237. context.material.transparent = true;
  15238. }
  15239. totalDiffuseNode.assign( totalDiffuse );
  15240. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  15241. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  15242. //
  15243. lightingModel.finish( context, stack, builder );
  15244. //
  15245. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  15246. }
  15247. return outgoingLightNode;
  15248. }
  15249. setLights( lights ) {
  15250. this._lights = lights;
  15251. this._lightNodes = null;
  15252. this._lightNodesHash = null;
  15253. return this;
  15254. }
  15255. getLights() {
  15256. return this._lights;
  15257. }
  15258. get hasLights() {
  15259. return this._lights.length > 0;
  15260. }
  15261. }
  15262. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  15263. class ShadowBaseNode extends Node {
  15264. static get type() {
  15265. return 'ShadowBaseNode';
  15266. }
  15267. constructor( light ) {
  15268. super();
  15269. this.light = light;
  15270. this.updateBeforeType = NodeUpdateType.RENDER;
  15271. this.isShadowBaseNode = true;
  15272. }
  15273. setupShadowPosition( { material } ) {
  15274. // Use assign inside an Fn()
  15275. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  15276. }
  15277. dispose() {
  15278. this.updateBeforeType = NodeUpdateType.NONE;
  15279. }
  15280. }
  15281. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  15282. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  15283. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  15284. let dist = positionWorld.sub( position ).length();
  15285. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  15286. dist = dist.saturate(); // clamp to [ 0, 1 ]
  15287. return dist;
  15288. } );
  15289. const linearShadowDistance = ( light ) => {
  15290. const camera = light.shadow.camera;
  15291. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  15292. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  15293. const referencePosition = objectPosition( light );
  15294. return linearDistance( referencePosition, nearDistance, farDistance );
  15295. };
  15296. const getShadowMaterial = ( light ) => {
  15297. let material = shadowMaterialLib.get( light );
  15298. if ( material === undefined ) {
  15299. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  15300. material = new NodeMaterial();
  15301. material.colorNode = vec4( 0, 0, 0, 1 );
  15302. material.depthNode = depthNode;
  15303. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  15304. material.blending = NoBlending;
  15305. material.name = 'ShadowMaterial';
  15306. shadowMaterialLib.set( light, material );
  15307. }
  15308. return material;
  15309. };
  15310. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  15311. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  15312. } );
  15313. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  15314. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  15315. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  15316. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  15317. const texelSize = vec2( 1 ).div( mapSize );
  15318. const dx0 = texelSize.x.negate().mul( radius );
  15319. const dy0 = texelSize.y.negate().mul( radius );
  15320. const dx1 = texelSize.x.mul( radius );
  15321. const dy1 = texelSize.y.mul( radius );
  15322. const dx2 = dx0.div( 2 );
  15323. const dy2 = dy0.div( 2 );
  15324. const dx3 = dx1.div( 2 );
  15325. const dy3 = dy1.div( 2 );
  15326. return add(
  15327. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  15328. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  15329. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  15330. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  15331. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  15332. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  15333. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  15334. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  15335. depthCompare( shadowCoord.xy, shadowCoord.z ),
  15336. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  15337. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  15338. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  15339. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  15340. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  15341. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  15342. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  15343. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  15344. ).mul( 1 / 17 );
  15345. } );
  15346. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  15347. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  15348. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  15349. const texelSize = vec2( 1 ).div( mapSize );
  15350. const dx = texelSize.x;
  15351. const dy = texelSize.y;
  15352. const uv = shadowCoord.xy;
  15353. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  15354. uv.subAssign( f.mul( texelSize ) );
  15355. return add(
  15356. depthCompare( uv, shadowCoord.z ),
  15357. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  15358. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  15359. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  15360. mix(
  15361. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  15362. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  15363. f.x
  15364. ),
  15365. mix(
  15366. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  15367. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  15368. f.x
  15369. ),
  15370. mix(
  15371. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  15372. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  15373. f.y
  15374. ),
  15375. mix(
  15376. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  15377. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  15378. f.y
  15379. ),
  15380. mix(
  15381. mix(
  15382. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  15383. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  15384. f.x
  15385. ),
  15386. mix(
  15387. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  15388. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  15389. f.x
  15390. ),
  15391. f.y
  15392. )
  15393. ).mul( 1 / 9 );
  15394. } );
  15395. // VSM
  15396. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  15397. const occlusion = float( 1 ).toVar();
  15398. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  15399. const hardShadow = step( shadowCoord.z, distribution.x );
  15400. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  15401. const distance = shadowCoord.z.sub( distribution.x );
  15402. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  15403. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  15404. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  15405. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  15406. } );
  15407. return occlusion;
  15408. } );
  15409. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  15410. const mean = float( 0 ).toVar();
  15411. const squaredMean = float( 0 ).toVar();
  15412. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  15413. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  15414. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  15415. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  15416. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  15417. mean.addAssign( depth );
  15418. squaredMean.addAssign( depth.mul( depth ) );
  15419. } );
  15420. mean.divAssign( samples );
  15421. squaredMean.divAssign( samples );
  15422. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  15423. return vec2( mean, std_dev );
  15424. } );
  15425. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  15426. const mean = float( 0 ).toVar();
  15427. const squaredMean = float( 0 ).toVar();
  15428. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  15429. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  15430. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  15431. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  15432. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  15433. mean.addAssign( distribution.x );
  15434. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  15435. } );
  15436. mean.divAssign( samples );
  15437. squaredMean.divAssign( samples );
  15438. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  15439. return vec2( mean, std_dev );
  15440. } );
  15441. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  15442. //
  15443. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  15444. class ShadowNode extends ShadowBaseNode {
  15445. static get type() {
  15446. return 'ShadowNode';
  15447. }
  15448. constructor( light, shadow = null ) {
  15449. super( light );
  15450. this.shadow = shadow || light.shadow;
  15451. this.shadowMap = null;
  15452. this.vsmShadowMapVertical = null;
  15453. this.vsmShadowMapHorizontal = null;
  15454. this.vsmMaterialVertical = null;
  15455. this.vsmMaterialHorizontal = null;
  15456. this._node = null;
  15457. this.isShadowNode = true;
  15458. }
  15459. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  15460. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  15461. .and( shadowCoord.x.lessThanEqual( 1 ) )
  15462. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  15463. .and( shadowCoord.y.lessThanEqual( 1 ) )
  15464. .and( shadowCoord.z.lessThanEqual( 1 ) );
  15465. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  15466. return frustumTest.select( shadowNode, float( 1 ) );
  15467. }
  15468. setupShadowCoord( builder, shadowPosition ) {
  15469. const { shadow } = this;
  15470. const { renderer } = builder;
  15471. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  15472. let shadowCoord = shadowPosition;
  15473. let coordZ;
  15474. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  15475. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  15476. coordZ = shadowCoord.z;
  15477. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  15478. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  15479. }
  15480. } else {
  15481. const w = shadowCoord.w;
  15482. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  15483. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  15484. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  15485. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  15486. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  15487. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  15488. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  15489. }
  15490. shadowCoord = vec3(
  15491. shadowCoord.x,
  15492. shadowCoord.y.oneMinus(), // follow webgpu standards
  15493. coordZ.add( bias )
  15494. );
  15495. return shadowCoord;
  15496. }
  15497. getShadowFilterFn( type ) {
  15498. return _shadowFilterLib[ type ];
  15499. }
  15500. setupShadow( builder ) {
  15501. const { renderer } = builder;
  15502. const { light, shadow } = this;
  15503. const shadowMapType = renderer.shadowMap.type;
  15504. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  15505. depthTexture.compareFunction = LessCompare;
  15506. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  15507. shadowMap.depthTexture = depthTexture;
  15508. shadow.camera.updateProjectionMatrix();
  15509. // VSM
  15510. if ( shadowMapType === VSMShadowMap ) {
  15511. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  15512. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  15513. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  15514. const shadowPassVertical = texture( depthTexture );
  15515. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  15516. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  15517. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  15518. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  15519. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  15520. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  15521. material.name = 'VSMVertical';
  15522. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  15523. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  15524. material.name = 'VSMHorizontal';
  15525. }
  15526. //
  15527. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  15528. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  15529. const shadowPosition = lightShadowMatrix( light ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  15530. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  15531. //
  15532. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  15533. if ( filterFn === null ) {
  15534. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  15535. }
  15536. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  15537. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  15538. const shadowColor = texture( shadowMap.texture, shadowCoord );
  15539. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  15540. this.shadowMap = shadowMap;
  15541. this.shadow.map = shadowMap;
  15542. return shadowOutput;
  15543. }
  15544. setup( builder ) {
  15545. if ( builder.renderer.shadowMap.enabled === false ) return;
  15546. return Fn( () => {
  15547. let node = this._node;
  15548. this.setupShadowPosition( builder );
  15549. if ( node === null ) {
  15550. this._node = node = this.setupShadow( builder );
  15551. }
  15552. if ( builder.material.shadowNode ) { // @deprecated, r171
  15553. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  15554. }
  15555. if ( builder.material.receivedShadowNode ) {
  15556. node = builder.material.receivedShadowNode( node );
  15557. }
  15558. return node;
  15559. } )();
  15560. }
  15561. renderShadow( frame ) {
  15562. const { shadow, shadowMap } = this;
  15563. const { renderer, scene } = frame;
  15564. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  15565. renderer.render( scene, shadow.camera );
  15566. }
  15567. updateShadow( frame ) {
  15568. const { shadowMap, light, shadow } = this;
  15569. const { renderer, scene, camera } = frame;
  15570. const shadowType = renderer.shadowMap.type;
  15571. const depthVersion = shadowMap.depthTexture.version;
  15572. this._depthVersionCached = depthVersion;
  15573. const currentOverrideMaterial = scene.overrideMaterial;
  15574. scene.overrideMaterial = getShadowMaterial( light );
  15575. shadow.camera.layers.mask = camera.layers.mask;
  15576. const currentRenderTarget = renderer.getRenderTarget();
  15577. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  15578. const currentMRT = renderer.getMRT();
  15579. renderer.setMRT( null );
  15580. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  15581. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  15582. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  15583. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  15584. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  15585. }
  15586. } );
  15587. renderer.setRenderTarget( shadowMap );
  15588. this.renderShadow( frame );
  15589. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  15590. // vsm blur pass
  15591. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  15592. this.vsmPass( renderer );
  15593. }
  15594. renderer.setRenderTarget( currentRenderTarget );
  15595. renderer.setMRT( currentMRT );
  15596. scene.overrideMaterial = currentOverrideMaterial;
  15597. }
  15598. vsmPass( renderer ) {
  15599. const { shadow } = this;
  15600. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  15601. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  15602. renderer.setRenderTarget( this.vsmShadowMapVertical );
  15603. _quadMesh$1.material = this.vsmMaterialVertical;
  15604. _quadMesh$1.render( renderer );
  15605. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  15606. _quadMesh$1.material = this.vsmMaterialHorizontal;
  15607. _quadMesh$1.render( renderer );
  15608. }
  15609. dispose() {
  15610. this.shadowMap.dispose();
  15611. this.shadowMap = null;
  15612. if ( this.vsmShadowMapVertical !== null ) {
  15613. this.vsmShadowMapVertical.dispose();
  15614. this.vsmShadowMapVertical = null;
  15615. this.vsmMaterialVertical.dispose();
  15616. this.vsmMaterialVertical = null;
  15617. }
  15618. if ( this.vsmShadowMapHorizontal !== null ) {
  15619. this.vsmShadowMapHorizontal.dispose();
  15620. this.vsmShadowMapHorizontal = null;
  15621. this.vsmMaterialHorizontal.dispose();
  15622. this.vsmMaterialHorizontal = null;
  15623. }
  15624. super.dispose();
  15625. }
  15626. updateBefore( frame ) {
  15627. const { shadow } = this;
  15628. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  15629. if ( needsUpdate ) {
  15630. this.updateShadow( frame );
  15631. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  15632. shadow.needsUpdate = false;
  15633. }
  15634. }
  15635. }
  15636. }
  15637. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  15638. class AnalyticLightNode extends LightingNode {
  15639. static get type() {
  15640. return 'AnalyticLightNode';
  15641. }
  15642. constructor( light = null ) {
  15643. super();
  15644. this.light = light;
  15645. this.color = new Color();
  15646. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  15647. this.baseColorNode = null;
  15648. this.shadowNode = null;
  15649. this.shadowColorNode = null;
  15650. this.isAnalyticLightNode = true;
  15651. this.updateType = NodeUpdateType.FRAME;
  15652. }
  15653. /**
  15654. * Overwrites the default `customCacheKey()` implementation by including the
  15655. * light.id and light.castShadow into the cache key.
  15656. *
  15657. * @return {Number} The hash.
  15658. */
  15659. customCacheKey() {
  15660. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  15661. }
  15662. getHash() {
  15663. return this.light.uuid;
  15664. }
  15665. setupShadowNode() {
  15666. return shadow( this.light );
  15667. }
  15668. setupShadow( builder ) {
  15669. const { renderer } = builder;
  15670. if ( renderer.shadowMap.enabled === false ) return;
  15671. let shadowColorNode = this.shadowColorNode;
  15672. if ( shadowColorNode === null ) {
  15673. const customShadowNode = this.light.shadow.shadowNode;
  15674. let shadowNode;
  15675. if ( customShadowNode !== undefined ) {
  15676. shadowNode = nodeObject( customShadowNode );
  15677. } else {
  15678. shadowNode = this.setupShadowNode( builder );
  15679. }
  15680. this.shadowNode = shadowNode;
  15681. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  15682. this.baseColorNode = this.colorNode;
  15683. }
  15684. //
  15685. this.colorNode = shadowColorNode;
  15686. }
  15687. setup( builder ) {
  15688. this.colorNode = this.baseColorNode || this.colorNode;
  15689. if ( this.light.castShadow ) {
  15690. if ( builder.object.receiveShadow ) {
  15691. this.setupShadow( builder );
  15692. }
  15693. } else if ( this.shadowNode !== null ) {
  15694. this.shadowNode.dispose();
  15695. this.shadowNode = null;
  15696. this.shadowColorNode = null;
  15697. }
  15698. }
  15699. update( /*frame*/ ) {
  15700. const { light } = this;
  15701. this.color.copy( light.color ).multiplyScalar( light.intensity );
  15702. }
  15703. }
  15704. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  15705. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  15706. // based upon Frostbite 3 Moving to Physically-based Rendering
  15707. // page 32, equation 26: E[window1]
  15708. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15709. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  15710. return cutoffDistance.greaterThan( 0 ).select(
  15711. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  15712. distanceFalloff
  15713. );
  15714. } ); // validated
  15715. const _clearColor$2 = /*@__PURE__*/ new Color();
  15716. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  15717. // vector suitable for 2D texture mapping. This code uses the following layout for the
  15718. // 2D texture:
  15719. //
  15720. // xzXZ
  15721. // y Y
  15722. //
  15723. // Y - Positive y direction
  15724. // y - Negative y direction
  15725. // X - Positive x direction
  15726. // x - Negative x direction
  15727. // Z - Positive z direction
  15728. // z - Negative z direction
  15729. //
  15730. // Source and test bed:
  15731. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  15732. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  15733. const v = pos.toVar();
  15734. // Number of texels to avoid at the edge of each square
  15735. const absV = abs( v );
  15736. // Intersect unit cube
  15737. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  15738. absV.mulAssign( scaleToCube );
  15739. // Apply scale to avoid seams
  15740. // two texels less per square (one texel will do for NEAREST)
  15741. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  15742. // Unwrap
  15743. // space: -1 ... 1 range for each square
  15744. //
  15745. // #X## dim := ( 4 , 2 )
  15746. // # # center := ( 1 , 1 )
  15747. const planar = vec2( v.xy ).toVar();
  15748. const almostATexel = texelSizeY.mul( 1.5 );
  15749. const almostOne = almostATexel.oneMinus();
  15750. If( absV.z.greaterThanEqual( almostOne ), () => {
  15751. If( v.z.greaterThan( 0.0 ), () => {
  15752. planar.x.assign( sub( 4.0, v.x ) );
  15753. } );
  15754. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  15755. const signX = sign( v.x );
  15756. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  15757. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  15758. const signY = sign( v.y );
  15759. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  15760. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  15761. } );
  15762. // Transform to UV space
  15763. // scale := 0.5 / dim
  15764. // translate := ( center + 0.5 ) / dim
  15765. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  15766. } ).setLayout( {
  15767. name: 'cubeToUV',
  15768. type: 'vec2',
  15769. inputs: [
  15770. { name: 'pos', type: 'vec3' },
  15771. { name: 'texelSizeY', type: 'float' }
  15772. ]
  15773. } );
  15774. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  15775. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  15776. } );
  15777. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  15778. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  15779. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  15780. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  15781. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  15782. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  15783. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  15784. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  15785. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  15786. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  15787. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  15788. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  15789. .mul( 1.0 / 9.0 );
  15790. } );
  15791. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  15792. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  15793. // the vector from the light to the world-space position of the fragment.
  15794. const lightToPosition = shadowCoord.xyz.toVar();
  15795. const lightToPositionLength = lightToPosition.length();
  15796. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  15797. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  15798. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  15799. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  15800. const result = float( 1.0 ).toVar();
  15801. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  15802. // dp = normalized distance from light to fragment position
  15803. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  15804. dp.addAssign( bias );
  15805. // bd3D = base direction 3D
  15806. const bd3D = lightToPosition.normalize();
  15807. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  15808. // percentage-closer filtering
  15809. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  15810. } );
  15811. return result;
  15812. } );
  15813. const _viewport = /*@__PURE__*/ new Vector4();
  15814. const _viewportSize = /*@__PURE__*/ new Vector2();
  15815. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  15816. //
  15817. class PointShadowNode extends ShadowNode {
  15818. static get type() {
  15819. return 'PointShadowNode';
  15820. }
  15821. constructor( light, shadow = null ) {
  15822. super( light, shadow );
  15823. }
  15824. getShadowFilterFn( type ) {
  15825. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  15826. }
  15827. setupShadowCoord( builder, shadowPosition ) {
  15828. return shadowPosition;
  15829. }
  15830. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  15831. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  15832. }
  15833. renderShadow( frame ) {
  15834. const { shadow, shadowMap, light } = this;
  15835. const { renderer, scene } = frame;
  15836. const shadowFrameExtents = shadow.getFrameExtents();
  15837. _shadowMapSize.copy( shadow.mapSize );
  15838. _shadowMapSize.multiply( shadowFrameExtents );
  15839. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  15840. _viewportSize.copy( shadow.mapSize );
  15841. //
  15842. const previousAutoClear = renderer.autoClear;
  15843. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  15844. const previousClearAlpha = renderer.getClearAlpha();
  15845. renderer.autoClear = false;
  15846. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  15847. renderer.clear();
  15848. const viewportCount = shadow.getViewportCount();
  15849. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  15850. const viewport = shadow.getViewport( vp );
  15851. const x = _viewportSize.x * viewport.x;
  15852. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  15853. _viewport.set(
  15854. x,
  15855. y,
  15856. _viewportSize.x * viewport.z,
  15857. _viewportSize.y * viewport.w
  15858. );
  15859. shadowMap.viewport.copy( _viewport );
  15860. shadow.updateMatrices( light, vp );
  15861. renderer.render( scene, shadow.camera );
  15862. }
  15863. //
  15864. renderer.autoClear = previousAutoClear;
  15865. renderer.setClearColor( previousClearColor, previousClearAlpha );
  15866. }
  15867. }
  15868. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  15869. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  15870. const lightingModel = builder.context.lightingModel;
  15871. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  15872. const lightDirection = lVector.normalize();
  15873. const lightDistance = lVector.length();
  15874. const lightAttenuation = getDistanceAttenuation( {
  15875. lightDistance,
  15876. cutoffDistance,
  15877. decayExponent
  15878. } );
  15879. const lightColor = color.mul( lightAttenuation );
  15880. const reflectedLight = builder.context.reflectedLight;
  15881. lightingModel.direct( {
  15882. lightDirection,
  15883. lightColor,
  15884. reflectedLight
  15885. }, builder.stack, builder );
  15886. } );
  15887. class PointLightNode extends AnalyticLightNode {
  15888. static get type() {
  15889. return 'PointLightNode';
  15890. }
  15891. constructor( light = null ) {
  15892. super( light );
  15893. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  15894. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  15895. }
  15896. update( frame ) {
  15897. const { light } = this;
  15898. super.update( frame );
  15899. this.cutoffDistanceNode.value = light.distance;
  15900. this.decayExponentNode.value = light.decay;
  15901. }
  15902. setupShadowNode() {
  15903. return pointShadow( this.light );
  15904. }
  15905. setup( builder ) {
  15906. super.setup( builder );
  15907. directPointLight( {
  15908. color: this.colorNode,
  15909. lightViewPosition: lightViewPosition( this.light ),
  15910. cutoffDistance: this.cutoffDistanceNode,
  15911. decayExponent: this.decayExponentNode
  15912. } ).append();
  15913. }
  15914. }
  15915. /** @module Procedural **/
  15916. /**
  15917. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  15918. *
  15919. * @method
  15920. * @param {Node<vec2>} uv - The uv coordinates.
  15921. * @return {Node<float>} The result data.
  15922. */
  15923. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  15924. const uv = coord.mul( 2.0 );
  15925. const cx = uv.x.floor();
  15926. const cy = uv.y.floor();
  15927. const result = cx.add( cy ).mod( 2.0 );
  15928. return result.sign();
  15929. } );
  15930. // Three.js Transpiler
  15931. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  15932. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  15933. const f = float( f_immutable ).toVar();
  15934. const t = float( t_immutable ).toVar();
  15935. const b = bool( b_immutable ).toVar();
  15936. return select( b, t, f );
  15937. } ).setLayout( {
  15938. name: 'mx_select',
  15939. type: 'float',
  15940. inputs: [
  15941. { name: 'b', type: 'bool' },
  15942. { name: 't', type: 'float' },
  15943. { name: 'f', type: 'float' }
  15944. ]
  15945. } );
  15946. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  15947. const b = bool( b_immutable ).toVar();
  15948. const val = float( val_immutable ).toVar();
  15949. return select( b, val.negate(), val );
  15950. } ).setLayout( {
  15951. name: 'mx_negate_if',
  15952. type: 'float',
  15953. inputs: [
  15954. { name: 'val', type: 'float' },
  15955. { name: 'b', type: 'bool' }
  15956. ]
  15957. } );
  15958. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  15959. const x = float( x_immutable ).toVar();
  15960. return int( floor( x ) );
  15961. } ).setLayout( {
  15962. name: 'mx_floor',
  15963. type: 'int',
  15964. inputs: [
  15965. { name: 'x', type: 'float' }
  15966. ]
  15967. } );
  15968. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  15969. const x = float( x_immutable ).toVar();
  15970. i.assign( mx_floor( x ) );
  15971. return x.sub( float( i ) );
  15972. } );
  15973. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  15974. const t = float( t_immutable ).toVar();
  15975. const s = float( s_immutable ).toVar();
  15976. const v3 = float( v3_immutable ).toVar();
  15977. const v2 = float( v2_immutable ).toVar();
  15978. const v1 = float( v1_immutable ).toVar();
  15979. const v0 = float( v0_immutable ).toVar();
  15980. const s1 = float( sub( 1.0, s ) ).toVar();
  15981. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  15982. } ).setLayout( {
  15983. name: 'mx_bilerp_0',
  15984. type: 'float',
  15985. inputs: [
  15986. { name: 'v0', type: 'float' },
  15987. { name: 'v1', type: 'float' },
  15988. { name: 'v2', type: 'float' },
  15989. { name: 'v3', type: 'float' },
  15990. { name: 's', type: 'float' },
  15991. { name: 't', type: 'float' }
  15992. ]
  15993. } );
  15994. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  15995. const t = float( t_immutable ).toVar();
  15996. const s = float( s_immutable ).toVar();
  15997. const v3 = vec3( v3_immutable ).toVar();
  15998. const v2 = vec3( v2_immutable ).toVar();
  15999. const v1 = vec3( v1_immutable ).toVar();
  16000. const v0 = vec3( v0_immutable ).toVar();
  16001. const s1 = float( sub( 1.0, s ) ).toVar();
  16002. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  16003. } ).setLayout( {
  16004. name: 'mx_bilerp_1',
  16005. type: 'vec3',
  16006. inputs: [
  16007. { name: 'v0', type: 'vec3' },
  16008. { name: 'v1', type: 'vec3' },
  16009. { name: 'v2', type: 'vec3' },
  16010. { name: 'v3', type: 'vec3' },
  16011. { name: 's', type: 'float' },
  16012. { name: 't', type: 'float' }
  16013. ]
  16014. } );
  16015. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  16016. 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 ] ) => {
  16017. const r = float( r_immutable ).toVar();
  16018. const t = float( t_immutable ).toVar();
  16019. const s = float( s_immutable ).toVar();
  16020. const v7 = float( v7_immutable ).toVar();
  16021. const v6 = float( v6_immutable ).toVar();
  16022. const v5 = float( v5_immutable ).toVar();
  16023. const v4 = float( v4_immutable ).toVar();
  16024. const v3 = float( v3_immutable ).toVar();
  16025. const v2 = float( v2_immutable ).toVar();
  16026. const v1 = float( v1_immutable ).toVar();
  16027. const v0 = float( v0_immutable ).toVar();
  16028. const s1 = float( sub( 1.0, s ) ).toVar();
  16029. const t1 = float( sub( 1.0, t ) ).toVar();
  16030. const r1 = float( sub( 1.0, r ) ).toVar();
  16031. 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 ) ) ) ) ) );
  16032. } ).setLayout( {
  16033. name: 'mx_trilerp_0',
  16034. type: 'float',
  16035. inputs: [
  16036. { name: 'v0', type: 'float' },
  16037. { name: 'v1', type: 'float' },
  16038. { name: 'v2', type: 'float' },
  16039. { name: 'v3', type: 'float' },
  16040. { name: 'v4', type: 'float' },
  16041. { name: 'v5', type: 'float' },
  16042. { name: 'v6', type: 'float' },
  16043. { name: 'v7', type: 'float' },
  16044. { name: 's', type: 'float' },
  16045. { name: 't', type: 'float' },
  16046. { name: 'r', type: 'float' }
  16047. ]
  16048. } );
  16049. 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 ] ) => {
  16050. const r = float( r_immutable ).toVar();
  16051. const t = float( t_immutable ).toVar();
  16052. const s = float( s_immutable ).toVar();
  16053. const v7 = vec3( v7_immutable ).toVar();
  16054. const v6 = vec3( v6_immutable ).toVar();
  16055. const v5 = vec3( v5_immutable ).toVar();
  16056. const v4 = vec3( v4_immutable ).toVar();
  16057. const v3 = vec3( v3_immutable ).toVar();
  16058. const v2 = vec3( v2_immutable ).toVar();
  16059. const v1 = vec3( v1_immutable ).toVar();
  16060. const v0 = vec3( v0_immutable ).toVar();
  16061. const s1 = float( sub( 1.0, s ) ).toVar();
  16062. const t1 = float( sub( 1.0, t ) ).toVar();
  16063. const r1 = float( sub( 1.0, r ) ).toVar();
  16064. 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 ) ) ) ) ) );
  16065. } ).setLayout( {
  16066. name: 'mx_trilerp_1',
  16067. type: 'vec3',
  16068. inputs: [
  16069. { name: 'v0', type: 'vec3' },
  16070. { name: 'v1', type: 'vec3' },
  16071. { name: 'v2', type: 'vec3' },
  16072. { name: 'v3', type: 'vec3' },
  16073. { name: 'v4', type: 'vec3' },
  16074. { name: 'v5', type: 'vec3' },
  16075. { name: 'v6', type: 'vec3' },
  16076. { name: 'v7', type: 'vec3' },
  16077. { name: 's', type: 'float' },
  16078. { name: 't', type: 'float' },
  16079. { name: 'r', type: 'float' }
  16080. ]
  16081. } );
  16082. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  16083. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  16084. const y = float( y_immutable ).toVar();
  16085. const x = float( x_immutable ).toVar();
  16086. const hash = uint( hash_immutable ).toVar();
  16087. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  16088. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  16089. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  16090. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  16091. } ).setLayout( {
  16092. name: 'mx_gradient_float_0',
  16093. type: 'float',
  16094. inputs: [
  16095. { name: 'hash', type: 'uint' },
  16096. { name: 'x', type: 'float' },
  16097. { name: 'y', type: 'float' }
  16098. ]
  16099. } );
  16100. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  16101. const z = float( z_immutable ).toVar();
  16102. const y = float( y_immutable ).toVar();
  16103. const x = float( x_immutable ).toVar();
  16104. const hash = uint( hash_immutable ).toVar();
  16105. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  16106. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  16107. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  16108. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  16109. } ).setLayout( {
  16110. name: 'mx_gradient_float_1',
  16111. type: 'float',
  16112. inputs: [
  16113. { name: 'hash', type: 'uint' },
  16114. { name: 'x', type: 'float' },
  16115. { name: 'y', type: 'float' },
  16116. { name: 'z', type: 'float' }
  16117. ]
  16118. } );
  16119. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  16120. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  16121. const y = float( y_immutable ).toVar();
  16122. const x = float( x_immutable ).toVar();
  16123. const hash = uvec3( hash_immutable ).toVar();
  16124. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  16125. } ).setLayout( {
  16126. name: 'mx_gradient_vec3_0',
  16127. type: 'vec3',
  16128. inputs: [
  16129. { name: 'hash', type: 'uvec3' },
  16130. { name: 'x', type: 'float' },
  16131. { name: 'y', type: 'float' }
  16132. ]
  16133. } );
  16134. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  16135. const z = float( z_immutable ).toVar();
  16136. const y = float( y_immutable ).toVar();
  16137. const x = float( x_immutable ).toVar();
  16138. const hash = uvec3( hash_immutable ).toVar();
  16139. 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 ) );
  16140. } ).setLayout( {
  16141. name: 'mx_gradient_vec3_1',
  16142. type: 'vec3',
  16143. inputs: [
  16144. { name: 'hash', type: 'uvec3' },
  16145. { name: 'x', type: 'float' },
  16146. { name: 'y', type: 'float' },
  16147. { name: 'z', type: 'float' }
  16148. ]
  16149. } );
  16150. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  16151. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16152. const v = float( v_immutable ).toVar();
  16153. return mul( 0.6616, v );
  16154. } ).setLayout( {
  16155. name: 'mx_gradient_scale2d_0',
  16156. type: 'float',
  16157. inputs: [
  16158. { name: 'v', type: 'float' }
  16159. ]
  16160. } );
  16161. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16162. const v = float( v_immutable ).toVar();
  16163. return mul( 0.9820, v );
  16164. } ).setLayout( {
  16165. name: 'mx_gradient_scale3d_0',
  16166. type: 'float',
  16167. inputs: [
  16168. { name: 'v', type: 'float' }
  16169. ]
  16170. } );
  16171. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16172. const v = vec3( v_immutable ).toVar();
  16173. return mul( 0.6616, v );
  16174. } ).setLayout( {
  16175. name: 'mx_gradient_scale2d_1',
  16176. type: 'vec3',
  16177. inputs: [
  16178. { name: 'v', type: 'vec3' }
  16179. ]
  16180. } );
  16181. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  16182. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16183. const v = vec3( v_immutable ).toVar();
  16184. return mul( 0.9820, v );
  16185. } ).setLayout( {
  16186. name: 'mx_gradient_scale3d_1',
  16187. type: 'vec3',
  16188. inputs: [
  16189. { name: 'v', type: 'vec3' }
  16190. ]
  16191. } );
  16192. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  16193. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  16194. const k = int( k_immutable ).toVar();
  16195. const x = uint( x_immutable ).toVar();
  16196. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  16197. } ).setLayout( {
  16198. name: 'mx_rotl32',
  16199. type: 'uint',
  16200. inputs: [
  16201. { name: 'x', type: 'uint' },
  16202. { name: 'k', type: 'int' }
  16203. ]
  16204. } );
  16205. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  16206. a.subAssign( c );
  16207. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  16208. c.addAssign( b );
  16209. b.subAssign( a );
  16210. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  16211. a.addAssign( c );
  16212. c.subAssign( b );
  16213. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  16214. b.addAssign( a );
  16215. a.subAssign( c );
  16216. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  16217. c.addAssign( b );
  16218. b.subAssign( a );
  16219. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  16220. a.addAssign( c );
  16221. c.subAssign( b );
  16222. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  16223. b.addAssign( a );
  16224. } );
  16225. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  16226. const c = uint( c_immutable ).toVar();
  16227. const b = uint( b_immutable ).toVar();
  16228. const a = uint( a_immutable ).toVar();
  16229. c.bitXorAssign( b );
  16230. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  16231. a.bitXorAssign( c );
  16232. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  16233. b.bitXorAssign( a );
  16234. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  16235. c.bitXorAssign( b );
  16236. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  16237. a.bitXorAssign( c );
  16238. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  16239. b.bitXorAssign( a );
  16240. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  16241. c.bitXorAssign( b );
  16242. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  16243. return c;
  16244. } ).setLayout( {
  16245. name: 'mx_bjfinal',
  16246. type: 'uint',
  16247. inputs: [
  16248. { name: 'a', type: 'uint' },
  16249. { name: 'b', type: 'uint' },
  16250. { name: 'c', type: 'uint' }
  16251. ]
  16252. } );
  16253. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  16254. const bits = uint( bits_immutable ).toVar();
  16255. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  16256. } ).setLayout( {
  16257. name: 'mx_bits_to_01',
  16258. type: 'float',
  16259. inputs: [
  16260. { name: 'bits', type: 'uint' }
  16261. ]
  16262. } );
  16263. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  16264. const t = float( t_immutable ).toVar();
  16265. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  16266. } ).setLayout( {
  16267. name: 'mx_fade',
  16268. type: 'float',
  16269. inputs: [
  16270. { name: 't', type: 'float' }
  16271. ]
  16272. } );
  16273. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  16274. const x = int( x_immutable ).toVar();
  16275. const len = uint( uint( 1 ) ).toVar();
  16276. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  16277. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  16278. } ).setLayout( {
  16279. name: 'mx_hash_int_0',
  16280. type: 'uint',
  16281. inputs: [
  16282. { name: 'x', type: 'int' }
  16283. ]
  16284. } );
  16285. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  16286. const y = int( y_immutable ).toVar();
  16287. const x = int( x_immutable ).toVar();
  16288. const len = uint( uint( 2 ) ).toVar();
  16289. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16290. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16291. a.addAssign( uint( x ) );
  16292. b.addAssign( uint( y ) );
  16293. return mx_bjfinal( a, b, c );
  16294. } ).setLayout( {
  16295. name: 'mx_hash_int_1',
  16296. type: 'uint',
  16297. inputs: [
  16298. { name: 'x', type: 'int' },
  16299. { name: 'y', type: 'int' }
  16300. ]
  16301. } );
  16302. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  16303. const z = int( z_immutable ).toVar();
  16304. const y = int( y_immutable ).toVar();
  16305. const x = int( x_immutable ).toVar();
  16306. const len = uint( uint( 3 ) ).toVar();
  16307. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16308. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16309. a.addAssign( uint( x ) );
  16310. b.addAssign( uint( y ) );
  16311. c.addAssign( uint( z ) );
  16312. return mx_bjfinal( a, b, c );
  16313. } ).setLayout( {
  16314. name: 'mx_hash_int_2',
  16315. type: 'uint',
  16316. inputs: [
  16317. { name: 'x', type: 'int' },
  16318. { name: 'y', type: 'int' },
  16319. { name: 'z', type: 'int' }
  16320. ]
  16321. } );
  16322. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  16323. const xx = int( xx_immutable ).toVar();
  16324. const z = int( z_immutable ).toVar();
  16325. const y = int( y_immutable ).toVar();
  16326. const x = int( x_immutable ).toVar();
  16327. const len = uint( uint( 4 ) ).toVar();
  16328. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16329. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16330. a.addAssign( uint( x ) );
  16331. b.addAssign( uint( y ) );
  16332. c.addAssign( uint( z ) );
  16333. mx_bjmix( a, b, c );
  16334. a.addAssign( uint( xx ) );
  16335. return mx_bjfinal( a, b, c );
  16336. } ).setLayout( {
  16337. name: 'mx_hash_int_3',
  16338. type: 'uint',
  16339. inputs: [
  16340. { name: 'x', type: 'int' },
  16341. { name: 'y', type: 'int' },
  16342. { name: 'z', type: 'int' },
  16343. { name: 'xx', type: 'int' }
  16344. ]
  16345. } );
  16346. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  16347. const yy = int( yy_immutable ).toVar();
  16348. const xx = int( xx_immutable ).toVar();
  16349. const z = int( z_immutable ).toVar();
  16350. const y = int( y_immutable ).toVar();
  16351. const x = int( x_immutable ).toVar();
  16352. const len = uint( uint( 5 ) ).toVar();
  16353. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16354. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16355. a.addAssign( uint( x ) );
  16356. b.addAssign( uint( y ) );
  16357. c.addAssign( uint( z ) );
  16358. mx_bjmix( a, b, c );
  16359. a.addAssign( uint( xx ) );
  16360. b.addAssign( uint( yy ) );
  16361. return mx_bjfinal( a, b, c );
  16362. } ).setLayout( {
  16363. name: 'mx_hash_int_4',
  16364. type: 'uint',
  16365. inputs: [
  16366. { name: 'x', type: 'int' },
  16367. { name: 'y', type: 'int' },
  16368. { name: 'z', type: 'int' },
  16369. { name: 'xx', type: 'int' },
  16370. { name: 'yy', type: 'int' }
  16371. ]
  16372. } );
  16373. 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 ] );
  16374. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  16375. const y = int( y_immutable ).toVar();
  16376. const x = int( x_immutable ).toVar();
  16377. const h = uint( mx_hash_int( x, y ) ).toVar();
  16378. const result = uvec3().toVar();
  16379. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  16380. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  16381. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  16382. return result;
  16383. } ).setLayout( {
  16384. name: 'mx_hash_vec3_0',
  16385. type: 'uvec3',
  16386. inputs: [
  16387. { name: 'x', type: 'int' },
  16388. { name: 'y', type: 'int' }
  16389. ]
  16390. } );
  16391. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  16392. const z = int( z_immutable ).toVar();
  16393. const y = int( y_immutable ).toVar();
  16394. const x = int( x_immutable ).toVar();
  16395. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  16396. const result = uvec3().toVar();
  16397. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  16398. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  16399. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  16400. return result;
  16401. } ).setLayout( {
  16402. name: 'mx_hash_vec3_1',
  16403. type: 'uvec3',
  16404. inputs: [
  16405. { name: 'x', type: 'int' },
  16406. { name: 'y', type: 'int' },
  16407. { name: 'z', type: 'int' }
  16408. ]
  16409. } );
  16410. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  16411. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16412. const p = vec2( p_immutable ).toVar();
  16413. const X = int().toVar(), Y = int().toVar();
  16414. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  16415. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  16416. const u = float( mx_fade( fx ) ).toVar();
  16417. const v = float( mx_fade( fy ) ).toVar();
  16418. 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();
  16419. return mx_gradient_scale2d( result );
  16420. } ).setLayout( {
  16421. name: 'mx_perlin_noise_float_0',
  16422. type: 'float',
  16423. inputs: [
  16424. { name: 'p', type: 'vec2' }
  16425. ]
  16426. } );
  16427. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16428. const p = vec3( p_immutable ).toVar();
  16429. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16430. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  16431. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  16432. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  16433. const u = float( mx_fade( fx ) ).toVar();
  16434. const v = float( mx_fade( fy ) ).toVar();
  16435. const w = float( mx_fade( fz ) ).toVar();
  16436. 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();
  16437. return mx_gradient_scale3d( result );
  16438. } ).setLayout( {
  16439. name: 'mx_perlin_noise_float_1',
  16440. type: 'float',
  16441. inputs: [
  16442. { name: 'p', type: 'vec3' }
  16443. ]
  16444. } );
  16445. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  16446. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16447. const p = vec2( p_immutable ).toVar();
  16448. const X = int().toVar(), Y = int().toVar();
  16449. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  16450. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  16451. const u = float( mx_fade( fx ) ).toVar();
  16452. const v = float( mx_fade( fy ) ).toVar();
  16453. 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();
  16454. return mx_gradient_scale2d( result );
  16455. } ).setLayout( {
  16456. name: 'mx_perlin_noise_vec3_0',
  16457. type: 'vec3',
  16458. inputs: [
  16459. { name: 'p', type: 'vec2' }
  16460. ]
  16461. } );
  16462. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16463. const p = vec3( p_immutable ).toVar();
  16464. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16465. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  16466. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  16467. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  16468. const u = float( mx_fade( fx ) ).toVar();
  16469. const v = float( mx_fade( fy ) ).toVar();
  16470. const w = float( mx_fade( fz ) ).toVar();
  16471. 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();
  16472. return mx_gradient_scale3d( result );
  16473. } ).setLayout( {
  16474. name: 'mx_perlin_noise_vec3_1',
  16475. type: 'vec3',
  16476. inputs: [
  16477. { name: 'p', type: 'vec3' }
  16478. ]
  16479. } );
  16480. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  16481. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16482. const p = float( p_immutable ).toVar();
  16483. const ix = int( mx_floor( p ) ).toVar();
  16484. return mx_bits_to_01( mx_hash_int( ix ) );
  16485. } ).setLayout( {
  16486. name: 'mx_cell_noise_float_0',
  16487. type: 'float',
  16488. inputs: [
  16489. { name: 'p', type: 'float' }
  16490. ]
  16491. } );
  16492. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16493. const p = vec2( p_immutable ).toVar();
  16494. const ix = int( mx_floor( p.x ) ).toVar();
  16495. const iy = int( mx_floor( p.y ) ).toVar();
  16496. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  16497. } ).setLayout( {
  16498. name: 'mx_cell_noise_float_1',
  16499. type: 'float',
  16500. inputs: [
  16501. { name: 'p', type: 'vec2' }
  16502. ]
  16503. } );
  16504. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16505. const p = vec3( p_immutable ).toVar();
  16506. const ix = int( mx_floor( p.x ) ).toVar();
  16507. const iy = int( mx_floor( p.y ) ).toVar();
  16508. const iz = int( mx_floor( p.z ) ).toVar();
  16509. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  16510. } ).setLayout( {
  16511. name: 'mx_cell_noise_float_2',
  16512. type: 'float',
  16513. inputs: [
  16514. { name: 'p', type: 'vec3' }
  16515. ]
  16516. } );
  16517. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16518. const p = vec4( p_immutable ).toVar();
  16519. const ix = int( mx_floor( p.x ) ).toVar();
  16520. const iy = int( mx_floor( p.y ) ).toVar();
  16521. const iz = int( mx_floor( p.z ) ).toVar();
  16522. const iw = int( mx_floor( p.w ) ).toVar();
  16523. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  16524. } ).setLayout( {
  16525. name: 'mx_cell_noise_float_3',
  16526. type: 'float',
  16527. inputs: [
  16528. { name: 'p', type: 'vec4' }
  16529. ]
  16530. } );
  16531. 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 ] );
  16532. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16533. const p = float( p_immutable ).toVar();
  16534. const ix = int( mx_floor( p ) ).toVar();
  16535. 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 ) ) ) );
  16536. } ).setLayout( {
  16537. name: 'mx_cell_noise_vec3_0',
  16538. type: 'vec3',
  16539. inputs: [
  16540. { name: 'p', type: 'float' }
  16541. ]
  16542. } );
  16543. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16544. const p = vec2( p_immutable ).toVar();
  16545. const ix = int( mx_floor( p.x ) ).toVar();
  16546. const iy = int( mx_floor( p.y ) ).toVar();
  16547. 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 ) ) ) );
  16548. } ).setLayout( {
  16549. name: 'mx_cell_noise_vec3_1',
  16550. type: 'vec3',
  16551. inputs: [
  16552. { name: 'p', type: 'vec2' }
  16553. ]
  16554. } );
  16555. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16556. const p = vec3( p_immutable ).toVar();
  16557. const ix = int( mx_floor( p.x ) ).toVar();
  16558. const iy = int( mx_floor( p.y ) ).toVar();
  16559. const iz = int( mx_floor( p.z ) ).toVar();
  16560. 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 ) ) ) );
  16561. } ).setLayout( {
  16562. name: 'mx_cell_noise_vec3_2',
  16563. type: 'vec3',
  16564. inputs: [
  16565. { name: 'p', type: 'vec3' }
  16566. ]
  16567. } );
  16568. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16569. const p = vec4( p_immutable ).toVar();
  16570. const ix = int( mx_floor( p.x ) ).toVar();
  16571. const iy = int( mx_floor( p.y ) ).toVar();
  16572. const iz = int( mx_floor( p.z ) ).toVar();
  16573. const iw = int( mx_floor( p.w ) ).toVar();
  16574. 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 ) ) ) );
  16575. } ).setLayout( {
  16576. name: 'mx_cell_noise_vec3_3',
  16577. type: 'vec3',
  16578. inputs: [
  16579. { name: 'p', type: 'vec4' }
  16580. ]
  16581. } );
  16582. 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 ] );
  16583. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  16584. const diminish = float( diminish_immutable ).toVar();
  16585. const lacunarity = float( lacunarity_immutable ).toVar();
  16586. const octaves = int( octaves_immutable ).toVar();
  16587. const p = vec3( p_immutable ).toVar();
  16588. const result = float( 0.0 ).toVar();
  16589. const amplitude = float( 1.0 ).toVar();
  16590. Loop( octaves, () => {
  16591. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  16592. amplitude.mulAssign( diminish );
  16593. p.mulAssign( lacunarity );
  16594. } );
  16595. return result;
  16596. } ).setLayout( {
  16597. name: 'mx_fractal_noise_float',
  16598. type: 'float',
  16599. inputs: [
  16600. { name: 'p', type: 'vec3' },
  16601. { name: 'octaves', type: 'int' },
  16602. { name: 'lacunarity', type: 'float' },
  16603. { name: 'diminish', type: 'float' }
  16604. ]
  16605. } );
  16606. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  16607. const diminish = float( diminish_immutable ).toVar();
  16608. const lacunarity = float( lacunarity_immutable ).toVar();
  16609. const octaves = int( octaves_immutable ).toVar();
  16610. const p = vec3( p_immutable ).toVar();
  16611. const result = vec3( 0.0 ).toVar();
  16612. const amplitude = float( 1.0 ).toVar();
  16613. Loop( octaves, () => {
  16614. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  16615. amplitude.mulAssign( diminish );
  16616. p.mulAssign( lacunarity );
  16617. } );
  16618. return result;
  16619. } ).setLayout( {
  16620. name: 'mx_fractal_noise_vec3',
  16621. type: 'vec3',
  16622. inputs: [
  16623. { name: 'p', type: 'vec3' },
  16624. { name: 'octaves', type: 'int' },
  16625. { name: 'lacunarity', type: 'float' },
  16626. { name: 'diminish', type: 'float' }
  16627. ]
  16628. } );
  16629. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  16630. const diminish = float( diminish_immutable ).toVar();
  16631. const lacunarity = float( lacunarity_immutable ).toVar();
  16632. const octaves = int( octaves_immutable ).toVar();
  16633. const p = vec3( p_immutable ).toVar();
  16634. 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 ) );
  16635. } ).setLayout( {
  16636. name: 'mx_fractal_noise_vec2',
  16637. type: 'vec2',
  16638. inputs: [
  16639. { name: 'p', type: 'vec3' },
  16640. { name: 'octaves', type: 'int' },
  16641. { name: 'lacunarity', type: 'float' },
  16642. { name: 'diminish', type: 'float' }
  16643. ]
  16644. } );
  16645. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  16646. const diminish = float( diminish_immutable ).toVar();
  16647. const lacunarity = float( lacunarity_immutable ).toVar();
  16648. const octaves = int( octaves_immutable ).toVar();
  16649. const p = vec3( p_immutable ).toVar();
  16650. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  16651. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  16652. return vec4( c, f );
  16653. } ).setLayout( {
  16654. name: 'mx_fractal_noise_vec4',
  16655. type: 'vec4',
  16656. inputs: [
  16657. { name: 'p', type: 'vec3' },
  16658. { name: 'octaves', type: 'int' },
  16659. { name: 'lacunarity', type: 'float' },
  16660. { name: 'diminish', type: 'float' }
  16661. ]
  16662. } );
  16663. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  16664. const metric = int( metric_immutable ).toVar();
  16665. const jitter = float( jitter_immutable ).toVar();
  16666. const yoff = int( yoff_immutable ).toVar();
  16667. const xoff = int( xoff_immutable ).toVar();
  16668. const y = int( y_immutable ).toVar();
  16669. const x = int( x_immutable ).toVar();
  16670. const p = vec2( p_immutable ).toVar();
  16671. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  16672. const off = vec2( tmp.x, tmp.y ).toVar();
  16673. off.subAssign( 0.5 );
  16674. off.mulAssign( jitter );
  16675. off.addAssign( 0.5 );
  16676. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  16677. const diff = vec2( cellpos.sub( p ) ).toVar();
  16678. If( metric.equal( int( 2 ) ), () => {
  16679. return abs( diff.x ).add( abs( diff.y ) );
  16680. } );
  16681. If( metric.equal( int( 3 ) ), () => {
  16682. return max$1( abs( diff.x ), abs( diff.y ) );
  16683. } );
  16684. return dot( diff, diff );
  16685. } ).setLayout( {
  16686. name: 'mx_worley_distance_0',
  16687. type: 'float',
  16688. inputs: [
  16689. { name: 'p', type: 'vec2' },
  16690. { name: 'x', type: 'int' },
  16691. { name: 'y', type: 'int' },
  16692. { name: 'xoff', type: 'int' },
  16693. { name: 'yoff', type: 'int' },
  16694. { name: 'jitter', type: 'float' },
  16695. { name: 'metric', type: 'int' }
  16696. ]
  16697. } );
  16698. 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 ] ) => {
  16699. const metric = int( metric_immutable ).toVar();
  16700. const jitter = float( jitter_immutable ).toVar();
  16701. const zoff = int( zoff_immutable ).toVar();
  16702. const yoff = int( yoff_immutable ).toVar();
  16703. const xoff = int( xoff_immutable ).toVar();
  16704. const z = int( z_immutable ).toVar();
  16705. const y = int( y_immutable ).toVar();
  16706. const x = int( x_immutable ).toVar();
  16707. const p = vec3( p_immutable ).toVar();
  16708. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  16709. off.subAssign( 0.5 );
  16710. off.mulAssign( jitter );
  16711. off.addAssign( 0.5 );
  16712. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  16713. const diff = vec3( cellpos.sub( p ) ).toVar();
  16714. If( metric.equal( int( 2 ) ), () => {
  16715. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  16716. } );
  16717. If( metric.equal( int( 3 ) ), () => {
  16718. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  16719. } );
  16720. return dot( diff, diff );
  16721. } ).setLayout( {
  16722. name: 'mx_worley_distance_1',
  16723. type: 'float',
  16724. inputs: [
  16725. { name: 'p', type: 'vec3' },
  16726. { name: 'x', type: 'int' },
  16727. { name: 'y', type: 'int' },
  16728. { name: 'z', type: 'int' },
  16729. { name: 'xoff', type: 'int' },
  16730. { name: 'yoff', type: 'int' },
  16731. { name: 'zoff', type: 'int' },
  16732. { name: 'jitter', type: 'float' },
  16733. { name: 'metric', type: 'int' }
  16734. ]
  16735. } );
  16736. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  16737. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16738. const metric = int( metric_immutable ).toVar();
  16739. const jitter = float( jitter_immutable ).toVar();
  16740. const p = vec2( p_immutable ).toVar();
  16741. const X = int().toVar(), Y = int().toVar();
  16742. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  16743. const sqdist = float( 1e6 ).toVar();
  16744. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16745. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16746. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  16747. sqdist.assign( min$1( sqdist, dist ) );
  16748. } );
  16749. } );
  16750. If( metric.equal( int( 0 ) ), () => {
  16751. sqdist.assign( sqrt( sqdist ) );
  16752. } );
  16753. return sqdist;
  16754. } ).setLayout( {
  16755. name: 'mx_worley_noise_float_0',
  16756. type: 'float',
  16757. inputs: [
  16758. { name: 'p', type: 'vec2' },
  16759. { name: 'jitter', type: 'float' },
  16760. { name: 'metric', type: 'int' }
  16761. ]
  16762. } );
  16763. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16764. const metric = int( metric_immutable ).toVar();
  16765. const jitter = float( jitter_immutable ).toVar();
  16766. const p = vec2( p_immutable ).toVar();
  16767. const X = int().toVar(), Y = int().toVar();
  16768. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  16769. const sqdist = vec2( 1e6, 1e6 ).toVar();
  16770. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16771. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16772. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  16773. If( dist.lessThan( sqdist.x ), () => {
  16774. sqdist.y.assign( sqdist.x );
  16775. sqdist.x.assign( dist );
  16776. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  16777. sqdist.y.assign( dist );
  16778. } );
  16779. } );
  16780. } );
  16781. If( metric.equal( int( 0 ) ), () => {
  16782. sqdist.assign( sqrt( sqdist ) );
  16783. } );
  16784. return sqdist;
  16785. } ).setLayout( {
  16786. name: 'mx_worley_noise_vec2_0',
  16787. type: 'vec2',
  16788. inputs: [
  16789. { name: 'p', type: 'vec2' },
  16790. { name: 'jitter', type: 'float' },
  16791. { name: 'metric', type: 'int' }
  16792. ]
  16793. } );
  16794. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16795. const metric = int( metric_immutable ).toVar();
  16796. const jitter = float( jitter_immutable ).toVar();
  16797. const p = vec2( p_immutable ).toVar();
  16798. const X = int().toVar(), Y = int().toVar();
  16799. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  16800. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  16801. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16802. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16803. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  16804. If( dist.lessThan( sqdist.x ), () => {
  16805. sqdist.z.assign( sqdist.y );
  16806. sqdist.y.assign( sqdist.x );
  16807. sqdist.x.assign( dist );
  16808. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  16809. sqdist.z.assign( sqdist.y );
  16810. sqdist.y.assign( dist );
  16811. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  16812. sqdist.z.assign( dist );
  16813. } );
  16814. } );
  16815. } );
  16816. If( metric.equal( int( 0 ) ), () => {
  16817. sqdist.assign( sqrt( sqdist ) );
  16818. } );
  16819. return sqdist;
  16820. } ).setLayout( {
  16821. name: 'mx_worley_noise_vec3_0',
  16822. type: 'vec3',
  16823. inputs: [
  16824. { name: 'p', type: 'vec2' },
  16825. { name: 'jitter', type: 'float' },
  16826. { name: 'metric', type: 'int' }
  16827. ]
  16828. } );
  16829. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16830. const metric = int( metric_immutable ).toVar();
  16831. const jitter = float( jitter_immutable ).toVar();
  16832. const p = vec3( p_immutable ).toVar();
  16833. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16834. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  16835. const sqdist = float( 1e6 ).toVar();
  16836. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16837. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16838. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  16839. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  16840. sqdist.assign( min$1( sqdist, dist ) );
  16841. } );
  16842. } );
  16843. } );
  16844. If( metric.equal( int( 0 ) ), () => {
  16845. sqdist.assign( sqrt( sqdist ) );
  16846. } );
  16847. return sqdist;
  16848. } ).setLayout( {
  16849. name: 'mx_worley_noise_float_1',
  16850. type: 'float',
  16851. inputs: [
  16852. { name: 'p', type: 'vec3' },
  16853. { name: 'jitter', type: 'float' },
  16854. { name: 'metric', type: 'int' }
  16855. ]
  16856. } );
  16857. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  16858. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16859. const metric = int( metric_immutable ).toVar();
  16860. const jitter = float( jitter_immutable ).toVar();
  16861. const p = vec3( p_immutable ).toVar();
  16862. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16863. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  16864. const sqdist = vec2( 1e6, 1e6 ).toVar();
  16865. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16866. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16867. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  16868. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  16869. If( dist.lessThan( sqdist.x ), () => {
  16870. sqdist.y.assign( sqdist.x );
  16871. sqdist.x.assign( dist );
  16872. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  16873. sqdist.y.assign( dist );
  16874. } );
  16875. } );
  16876. } );
  16877. } );
  16878. If( metric.equal( int( 0 ) ), () => {
  16879. sqdist.assign( sqrt( sqdist ) );
  16880. } );
  16881. return sqdist;
  16882. } ).setLayout( {
  16883. name: 'mx_worley_noise_vec2_1',
  16884. type: 'vec2',
  16885. inputs: [
  16886. { name: 'p', type: 'vec3' },
  16887. { name: 'jitter', type: 'float' },
  16888. { name: 'metric', type: 'int' }
  16889. ]
  16890. } );
  16891. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  16892. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16893. const metric = int( metric_immutable ).toVar();
  16894. const jitter = float( jitter_immutable ).toVar();
  16895. const p = vec3( p_immutable ).toVar();
  16896. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16897. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  16898. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  16899. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16900. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16901. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  16902. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  16903. If( dist.lessThan( sqdist.x ), () => {
  16904. sqdist.z.assign( sqdist.y );
  16905. sqdist.y.assign( sqdist.x );
  16906. sqdist.x.assign( dist );
  16907. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  16908. sqdist.z.assign( sqdist.y );
  16909. sqdist.y.assign( dist );
  16910. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  16911. sqdist.z.assign( dist );
  16912. } );
  16913. } );
  16914. } );
  16915. } );
  16916. If( metric.equal( int( 0 ) ), () => {
  16917. sqdist.assign( sqrt( sqdist ) );
  16918. } );
  16919. return sqdist;
  16920. } ).setLayout( {
  16921. name: 'mx_worley_noise_vec3_1',
  16922. type: 'vec3',
  16923. inputs: [
  16924. { name: 'p', type: 'vec3' },
  16925. { name: 'jitter', type: 'float' },
  16926. { name: 'metric', type: 'int' }
  16927. ]
  16928. } );
  16929. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  16930. // Three.js Transpiler
  16931. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  16932. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  16933. const s = hsv.y;
  16934. const v = hsv.z;
  16935. const result = vec3().toVar();
  16936. If( s.lessThan( 0.0001 ), () => {
  16937. result.assign( vec3( v, v, v ) );
  16938. } ).Else( () => {
  16939. let h = hsv.x;
  16940. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  16941. const hi = int( trunc( h ) );
  16942. const f = h.sub( float( hi ) );
  16943. const p = v.mul( s.oneMinus() );
  16944. const q = v.mul( s.mul( f ).oneMinus() );
  16945. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  16946. If( hi.equal( int( 0 ) ), () => {
  16947. result.assign( vec3( v, t, p ) );
  16948. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  16949. result.assign( vec3( q, v, p ) );
  16950. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  16951. result.assign( vec3( p, v, t ) );
  16952. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  16953. result.assign( vec3( p, q, v ) );
  16954. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  16955. result.assign( vec3( t, p, v ) );
  16956. } ).Else( () => {
  16957. result.assign( vec3( v, p, q ) );
  16958. } );
  16959. } );
  16960. return result;
  16961. } ).setLayout( {
  16962. name: 'mx_hsvtorgb',
  16963. type: 'vec3',
  16964. inputs: [
  16965. { name: 'hsv', type: 'vec3' }
  16966. ]
  16967. } );
  16968. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  16969. const c = vec3( c_immutable ).toVar();
  16970. const r = float( c.x ).toVar();
  16971. const g = float( c.y ).toVar();
  16972. const b = float( c.z ).toVar();
  16973. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  16974. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  16975. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  16976. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  16977. v.assign( maxcomp );
  16978. If( maxcomp.greaterThan( 0.0 ), () => {
  16979. s.assign( delta.div( maxcomp ) );
  16980. } ).Else( () => {
  16981. s.assign( 0.0 );
  16982. } );
  16983. If( s.lessThanEqual( 0.0 ), () => {
  16984. h.assign( 0.0 );
  16985. } ).Else( () => {
  16986. If( r.greaterThanEqual( maxcomp ), () => {
  16987. h.assign( g.sub( b ).div( delta ) );
  16988. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  16989. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  16990. } ).Else( () => {
  16991. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  16992. } );
  16993. h.mulAssign( 1.0 / 6.0 );
  16994. If( h.lessThan( 0.0 ), () => {
  16995. h.addAssign( 1.0 );
  16996. } );
  16997. } );
  16998. return vec3( h, s, v );
  16999. } ).setLayout( {
  17000. name: 'mx_rgbtohsv',
  17001. type: 'vec3',
  17002. inputs: [
  17003. { name: 'c', type: 'vec3' }
  17004. ]
  17005. } );
  17006. // Three.js Transpiler
  17007. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  17008. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  17009. const color = vec3( color_immutable ).toVar();
  17010. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  17011. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  17012. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  17013. return mix( linSeg, powSeg, isAbove );
  17014. } ).setLayout( {
  17015. name: 'mx_srgb_texture_to_lin_rec709',
  17016. type: 'vec3',
  17017. inputs: [
  17018. { name: 'color', type: 'vec3' }
  17019. ]
  17020. } );
  17021. const mx_aastep = ( threshold, value ) => {
  17022. threshold = float( threshold );
  17023. value = float( value );
  17024. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  17025. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  17026. };
  17027. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  17028. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  17029. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  17030. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  17031. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  17032. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  17033. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  17034. const mx_safepower = ( in1, in2 = 1 ) => {
  17035. in1 = float( in1 );
  17036. return in1.abs().pow( in2 ).mul( in1.sign() );
  17037. };
  17038. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  17039. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17040. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17041. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17042. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  17043. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  17044. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  17045. return noise_vec4.mul( amplitude ).add( pivot );
  17046. };
  17047. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17048. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17049. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17050. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  17051. 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 );
  17052. 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 );
  17053. 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 );
  17054. 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 );
  17055. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  17056. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  17057. const nDir = normalize( normal ).toVar( 'nDir' );
  17058. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  17059. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  17060. const rbminmax = vec3().toVar( 'rbminmax' );
  17061. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  17062. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  17063. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  17064. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  17065. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  17066. return boxIntersection.sub( cubePos );
  17067. } );
  17068. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  17069. // normal is assumed to have unit length
  17070. const x = normal.x, y = normal.y, z = normal.z;
  17071. // band 0
  17072. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  17073. // band 1
  17074. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  17075. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  17076. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  17077. // band 2
  17078. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  17079. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  17080. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  17081. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  17082. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  17083. return result;
  17084. } );
  17085. // constants
  17086. var TSL = /*#__PURE__*/Object.freeze({
  17087. __proto__: null,
  17088. BRDF_GGX: BRDF_GGX,
  17089. BRDF_Lambert: BRDF_Lambert,
  17090. BasicShadowFilter: BasicShadowFilter,
  17091. Break: Break,
  17092. Continue: Continue,
  17093. DFGApprox: DFGApprox,
  17094. D_GGX: D_GGX,
  17095. Discard: Discard,
  17096. EPSILON: EPSILON,
  17097. F_Schlick: F_Schlick,
  17098. Fn: Fn,
  17099. INFINITY: INFINITY,
  17100. If: If,
  17101. Loop: Loop,
  17102. NodeAccess: NodeAccess,
  17103. NodeShaderStage: NodeShaderStage,
  17104. NodeType: NodeType,
  17105. NodeUpdateType: NodeUpdateType,
  17106. PCFShadowFilter: PCFShadowFilter,
  17107. PCFSoftShadowFilter: PCFSoftShadowFilter,
  17108. PI: PI,
  17109. PI2: PI2,
  17110. Return: Return,
  17111. Schlick_to_F0: Schlick_to_F0,
  17112. ScriptableNodeResources: ScriptableNodeResources,
  17113. ShaderNode: ShaderNode,
  17114. TBNViewMatrix: TBNViewMatrix,
  17115. VSMShadowFilter: VSMShadowFilter,
  17116. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  17117. abs: abs,
  17118. acesFilmicToneMapping: acesFilmicToneMapping,
  17119. acos: acos,
  17120. add: add,
  17121. addMethodChaining: addMethodChaining,
  17122. addNodeElement: addNodeElement,
  17123. agxToneMapping: agxToneMapping,
  17124. all: all,
  17125. alphaT: alphaT,
  17126. and: and,
  17127. anisotropy: anisotropy,
  17128. anisotropyB: anisotropyB,
  17129. anisotropyT: anisotropyT,
  17130. any: any,
  17131. append: append,
  17132. arrayBuffer: arrayBuffer,
  17133. asin: asin,
  17134. assign: assign,
  17135. atan: atan,
  17136. atan2: atan2,
  17137. atomicAdd: atomicAdd,
  17138. atomicAnd: atomicAnd,
  17139. atomicFunc: atomicFunc,
  17140. atomicMax: atomicMax,
  17141. atomicMin: atomicMin,
  17142. atomicOr: atomicOr,
  17143. atomicStore: atomicStore,
  17144. atomicSub: atomicSub,
  17145. atomicXor: atomicXor,
  17146. attenuationColor: attenuationColor,
  17147. attenuationDistance: attenuationDistance,
  17148. attribute: attribute,
  17149. attributeArray: attributeArray,
  17150. backgroundBlurriness: backgroundBlurriness,
  17151. backgroundIntensity: backgroundIntensity,
  17152. backgroundRotation: backgroundRotation,
  17153. batch: batch,
  17154. billboarding: billboarding,
  17155. bitAnd: bitAnd,
  17156. bitNot: bitNot,
  17157. bitOr: bitOr,
  17158. bitXor: bitXor,
  17159. bitangentGeometry: bitangentGeometry,
  17160. bitangentLocal: bitangentLocal,
  17161. bitangentView: bitangentView,
  17162. bitangentWorld: bitangentWorld,
  17163. bitcast: bitcast,
  17164. blendBurn: blendBurn,
  17165. blendColor: blendColor,
  17166. blendDodge: blendDodge,
  17167. blendOverlay: blendOverlay,
  17168. blendScreen: blendScreen,
  17169. blur: blur,
  17170. bool: bool,
  17171. buffer: buffer,
  17172. bufferAttribute: bufferAttribute,
  17173. bumpMap: bumpMap,
  17174. burn: burn,
  17175. bvec2: bvec2,
  17176. bvec3: bvec3,
  17177. bvec4: bvec4,
  17178. bypass: bypass,
  17179. cache: cache,
  17180. call: call,
  17181. cameraFar: cameraFar,
  17182. cameraNear: cameraNear,
  17183. cameraNormalMatrix: cameraNormalMatrix,
  17184. cameraPosition: cameraPosition,
  17185. cameraProjectionMatrix: cameraProjectionMatrix,
  17186. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  17187. cameraViewMatrix: cameraViewMatrix,
  17188. cameraWorldMatrix: cameraWorldMatrix,
  17189. cbrt: cbrt,
  17190. cdl: cdl,
  17191. ceil: ceil,
  17192. checker: checker,
  17193. cineonToneMapping: cineonToneMapping,
  17194. clamp: clamp,
  17195. clearcoat: clearcoat,
  17196. clearcoatRoughness: clearcoatRoughness,
  17197. code: code,
  17198. color: color,
  17199. colorSpaceToWorking: colorSpaceToWorking,
  17200. colorToDirection: colorToDirection,
  17201. compute: compute,
  17202. cond: cond,
  17203. context: context,
  17204. convert: convert,
  17205. convertColorSpace: convertColorSpace,
  17206. convertToTexture: convertToTexture,
  17207. cos: cos,
  17208. cross: cross,
  17209. cubeTexture: cubeTexture,
  17210. dFdx: dFdx,
  17211. dFdy: dFdy,
  17212. dashSize: dashSize,
  17213. defaultBuildStages: defaultBuildStages,
  17214. defaultShaderStages: defaultShaderStages,
  17215. defined: defined,
  17216. degrees: degrees,
  17217. deltaTime: deltaTime,
  17218. densityFog: densityFog,
  17219. depth: depth,
  17220. depthPass: depthPass,
  17221. difference: difference,
  17222. diffuseColor: diffuseColor,
  17223. directPointLight: directPointLight,
  17224. directionToColor: directionToColor,
  17225. dispersion: dispersion,
  17226. distance: distance,
  17227. div: div,
  17228. dodge: dodge,
  17229. dot: dot,
  17230. drawIndex: drawIndex,
  17231. dynamicBufferAttribute: dynamicBufferAttribute,
  17232. element: element,
  17233. emissive: emissive,
  17234. equal: equal,
  17235. equals: equals,
  17236. equirectUV: equirectUV,
  17237. exp: exp,
  17238. exp2: exp2,
  17239. expression: expression,
  17240. faceDirection: faceDirection,
  17241. faceForward: faceForward,
  17242. float: float,
  17243. floor: floor,
  17244. fog: fog,
  17245. fract: fract,
  17246. frameGroup: frameGroup,
  17247. frameId: frameId,
  17248. frontFacing: frontFacing,
  17249. fwidth: fwidth,
  17250. gain: gain,
  17251. gapSize: gapSize,
  17252. getConstNodeType: getConstNodeType,
  17253. getCurrentStack: getCurrentStack,
  17254. getDirection: getDirection,
  17255. getDistanceAttenuation: getDistanceAttenuation,
  17256. getGeometryRoughness: getGeometryRoughness,
  17257. getNormalFromDepth: getNormalFromDepth,
  17258. getParallaxCorrectNormal: getParallaxCorrectNormal,
  17259. getRoughness: getRoughness,
  17260. getScreenPosition: getScreenPosition,
  17261. getShIrradianceAt: getShIrradianceAt,
  17262. getTextureIndex: getTextureIndex,
  17263. getViewPosition: getViewPosition,
  17264. glsl: glsl,
  17265. glslFn: glslFn,
  17266. grayscale: grayscale,
  17267. greaterThan: greaterThan,
  17268. greaterThanEqual: greaterThanEqual,
  17269. hash: hash,
  17270. highPrecisionModelNormalViewMatrix: highPrecisionModelNormalViewMatrix,
  17271. highPrecisionModelViewMatrix: highPrecisionModelViewMatrix,
  17272. hue: hue,
  17273. instance: instance,
  17274. instanceIndex: instanceIndex,
  17275. instancedArray: instancedArray,
  17276. instancedBufferAttribute: instancedBufferAttribute,
  17277. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  17278. instancedMesh: instancedMesh,
  17279. int: int,
  17280. inverseSqrt: inverseSqrt,
  17281. invocationLocalIndex: invocationLocalIndex,
  17282. invocationSubgroupIndex: invocationSubgroupIndex,
  17283. ior: ior,
  17284. iridescence: iridescence,
  17285. iridescenceIOR: iridescenceIOR,
  17286. iridescenceThickness: iridescenceThickness,
  17287. ivec2: ivec2,
  17288. ivec3: ivec3,
  17289. ivec4: ivec4,
  17290. js: js,
  17291. label: label,
  17292. length: length,
  17293. lengthSq: lengthSq,
  17294. lessThan: lessThan,
  17295. lessThanEqual: lessThanEqual,
  17296. lightPosition: lightPosition,
  17297. lightProjectionUV: lightProjectionUV,
  17298. lightShadowMatrix: lightShadowMatrix,
  17299. lightTargetDirection: lightTargetDirection,
  17300. lightTargetPosition: lightTargetPosition,
  17301. lightViewPosition: lightViewPosition,
  17302. lightingContext: lightingContext,
  17303. lights: lights,
  17304. linearDepth: linearDepth,
  17305. linearToneMapping: linearToneMapping,
  17306. localId: localId,
  17307. log: log,
  17308. log2: log2,
  17309. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  17310. loop: loop,
  17311. luminance: luminance,
  17312. mat2: mat2,
  17313. mat3: mat3,
  17314. mat4: mat4,
  17315. matcapUV: matcapUV,
  17316. materialAOMap: materialAOMap,
  17317. materialAlphaTest: materialAlphaTest,
  17318. materialAnisotropy: materialAnisotropy,
  17319. materialAnisotropyVector: materialAnisotropyVector,
  17320. materialAttenuationColor: materialAttenuationColor,
  17321. materialAttenuationDistance: materialAttenuationDistance,
  17322. materialClearcoat: materialClearcoat,
  17323. materialClearcoatNormal: materialClearcoatNormal,
  17324. materialClearcoatRoughness: materialClearcoatRoughness,
  17325. materialColor: materialColor,
  17326. materialDispersion: materialDispersion,
  17327. materialEmissive: materialEmissive,
  17328. materialIOR: materialIOR,
  17329. materialIridescence: materialIridescence,
  17330. materialIridescenceIOR: materialIridescenceIOR,
  17331. materialIridescenceThickness: materialIridescenceThickness,
  17332. materialLightMap: materialLightMap,
  17333. materialLineDashOffset: materialLineDashOffset,
  17334. materialLineDashSize: materialLineDashSize,
  17335. materialLineGapSize: materialLineGapSize,
  17336. materialLineScale: materialLineScale,
  17337. materialLineWidth: materialLineWidth,
  17338. materialMetalness: materialMetalness,
  17339. materialNormal: materialNormal,
  17340. materialOpacity: materialOpacity,
  17341. materialPointWidth: materialPointWidth,
  17342. materialReference: materialReference,
  17343. materialReflectivity: materialReflectivity,
  17344. materialRefractionRatio: materialRefractionRatio,
  17345. materialRotation: materialRotation,
  17346. materialRoughness: materialRoughness,
  17347. materialSheen: materialSheen,
  17348. materialSheenRoughness: materialSheenRoughness,
  17349. materialShininess: materialShininess,
  17350. materialSpecular: materialSpecular,
  17351. materialSpecularColor: materialSpecularColor,
  17352. materialSpecularIntensity: materialSpecularIntensity,
  17353. materialSpecularStrength: materialSpecularStrength,
  17354. materialThickness: materialThickness,
  17355. materialTransmission: materialTransmission,
  17356. max: max$1,
  17357. maxMipLevel: maxMipLevel,
  17358. metalness: metalness,
  17359. min: min$1,
  17360. mix: mix,
  17361. mixElement: mixElement,
  17362. mod: mod,
  17363. modInt: modInt,
  17364. modelDirection: modelDirection,
  17365. modelNormalMatrix: modelNormalMatrix,
  17366. modelPosition: modelPosition,
  17367. modelScale: modelScale,
  17368. modelViewMatrix: modelViewMatrix,
  17369. modelViewPosition: modelViewPosition,
  17370. modelViewProjection: modelViewProjection,
  17371. modelWorldMatrix: modelWorldMatrix,
  17372. modelWorldMatrixInverse: modelWorldMatrixInverse,
  17373. morphReference: morphReference,
  17374. mrt: mrt,
  17375. mul: mul,
  17376. mx_aastep: mx_aastep,
  17377. mx_cell_noise_float: mx_cell_noise_float,
  17378. mx_contrast: mx_contrast,
  17379. mx_fractal_noise_float: mx_fractal_noise_float,
  17380. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  17381. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  17382. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  17383. mx_hsvtorgb: mx_hsvtorgb,
  17384. mx_noise_float: mx_noise_float,
  17385. mx_noise_vec3: mx_noise_vec3,
  17386. mx_noise_vec4: mx_noise_vec4,
  17387. mx_ramplr: mx_ramplr,
  17388. mx_ramptb: mx_ramptb,
  17389. mx_rgbtohsv: mx_rgbtohsv,
  17390. mx_safepower: mx_safepower,
  17391. mx_splitlr: mx_splitlr,
  17392. mx_splittb: mx_splittb,
  17393. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  17394. mx_transform_uv: mx_transform_uv,
  17395. mx_worley_noise_float: mx_worley_noise_float,
  17396. mx_worley_noise_vec2: mx_worley_noise_vec2,
  17397. mx_worley_noise_vec3: mx_worley_noise_vec3,
  17398. negate: negate,
  17399. neutralToneMapping: neutralToneMapping,
  17400. nodeArray: nodeArray,
  17401. nodeImmutable: nodeImmutable,
  17402. nodeObject: nodeObject,
  17403. nodeObjects: nodeObjects,
  17404. nodeProxy: nodeProxy,
  17405. normalFlat: normalFlat,
  17406. normalGeometry: normalGeometry,
  17407. normalLocal: normalLocal,
  17408. normalMap: normalMap,
  17409. normalView: normalView,
  17410. normalWorld: normalWorld,
  17411. normalize: normalize,
  17412. not: not,
  17413. notEqual: notEqual,
  17414. numWorkgroups: numWorkgroups,
  17415. objectDirection: objectDirection,
  17416. objectGroup: objectGroup,
  17417. objectPosition: objectPosition,
  17418. objectScale: objectScale,
  17419. objectViewPosition: objectViewPosition,
  17420. objectWorldMatrix: objectWorldMatrix,
  17421. oneMinus: oneMinus,
  17422. or: or,
  17423. orthographicDepthToViewZ: orthographicDepthToViewZ,
  17424. oscSawtooth: oscSawtooth,
  17425. oscSine: oscSine,
  17426. oscSquare: oscSquare,
  17427. oscTriangle: oscTriangle,
  17428. output: output,
  17429. outputStruct: outputStruct,
  17430. overlay: overlay,
  17431. overloadingFn: overloadingFn,
  17432. parabola: parabola,
  17433. parallaxDirection: parallaxDirection,
  17434. parallaxUV: parallaxUV,
  17435. parameter: parameter,
  17436. pass: pass,
  17437. passTexture: passTexture,
  17438. pcurve: pcurve,
  17439. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  17440. pmremTexture: pmremTexture,
  17441. pointUV: pointUV,
  17442. pointWidth: pointWidth,
  17443. positionGeometry: positionGeometry,
  17444. positionLocal: positionLocal,
  17445. positionPrevious: positionPrevious,
  17446. positionView: positionView,
  17447. positionViewDirection: positionViewDirection,
  17448. positionWorld: positionWorld,
  17449. positionWorldDirection: positionWorldDirection,
  17450. posterize: posterize,
  17451. pow: pow,
  17452. pow2: pow2,
  17453. pow3: pow3,
  17454. pow4: pow4,
  17455. property: property,
  17456. radians: radians,
  17457. rand: rand,
  17458. range: range,
  17459. rangeFog: rangeFog,
  17460. reciprocal: reciprocal,
  17461. reference: reference,
  17462. referenceBuffer: referenceBuffer,
  17463. reflect: reflect,
  17464. reflectVector: reflectVector,
  17465. reflectView: reflectView,
  17466. reflector: reflector,
  17467. refract: refract,
  17468. refractVector: refractVector,
  17469. refractView: refractView,
  17470. reinhardToneMapping: reinhardToneMapping,
  17471. remainder: remainder,
  17472. remap: remap,
  17473. remapClamp: remapClamp,
  17474. renderGroup: renderGroup,
  17475. renderOutput: renderOutput,
  17476. rendererReference: rendererReference,
  17477. rotate: rotate,
  17478. rotateUV: rotateUV,
  17479. roughness: roughness,
  17480. round: round,
  17481. rtt: rtt,
  17482. sRGBTransferEOTF: sRGBTransferEOTF,
  17483. sRGBTransferOETF: sRGBTransferOETF,
  17484. sampler: sampler,
  17485. saturate: saturate,
  17486. saturation: saturation,
  17487. screen: screen,
  17488. screenCoordinate: screenCoordinate,
  17489. screenSize: screenSize,
  17490. screenUV: screenUV,
  17491. scriptable: scriptable,
  17492. scriptableValue: scriptableValue,
  17493. select: select,
  17494. setCurrentStack: setCurrentStack,
  17495. shaderStages: shaderStages,
  17496. shadow: shadow,
  17497. sharedUniformGroup: sharedUniformGroup,
  17498. sheen: sheen,
  17499. sheenRoughness: sheenRoughness,
  17500. shiftLeft: shiftLeft,
  17501. shiftRight: shiftRight,
  17502. shininess: shininess,
  17503. sign: sign,
  17504. sin: sin,
  17505. sinc: sinc,
  17506. skinning: skinning,
  17507. skinningReference: skinningReference,
  17508. smoothstep: smoothstep,
  17509. smoothstepElement: smoothstepElement,
  17510. specularColor: specularColor,
  17511. specularF90: specularF90,
  17512. spherizeUV: spherizeUV,
  17513. split: split,
  17514. spritesheetUV: spritesheetUV,
  17515. sqrt: sqrt,
  17516. stack: stack,
  17517. step: step,
  17518. storage: storage,
  17519. storageBarrier: storageBarrier,
  17520. storageObject: storageObject,
  17521. storageTexture: storageTexture,
  17522. string: string,
  17523. sub: sub,
  17524. subgroupIndex: subgroupIndex,
  17525. subgroupSize: subgroupSize,
  17526. tan: tan,
  17527. tangentGeometry: tangentGeometry,
  17528. tangentLocal: tangentLocal,
  17529. tangentView: tangentView,
  17530. tangentWorld: tangentWorld,
  17531. temp: temp,
  17532. texture: texture,
  17533. texture3D: texture3D,
  17534. textureBarrier: textureBarrier,
  17535. textureBicubic: textureBicubic,
  17536. textureCubeUV: textureCubeUV,
  17537. textureLoad: textureLoad,
  17538. textureSize: textureSize,
  17539. textureStore: textureStore,
  17540. thickness: thickness,
  17541. time: time,
  17542. timerDelta: timerDelta,
  17543. timerGlobal: timerGlobal,
  17544. timerLocal: timerLocal,
  17545. toOutputColorSpace: toOutputColorSpace,
  17546. toWorkingColorSpace: toWorkingColorSpace,
  17547. toneMapping: toneMapping,
  17548. toneMappingExposure: toneMappingExposure,
  17549. toonOutlinePass: toonOutlinePass,
  17550. transformDirection: transformDirection,
  17551. transformNormal: transformNormal,
  17552. transformNormalToView: transformNormalToView,
  17553. transformedBentNormalView: transformedBentNormalView,
  17554. transformedBitangentView: transformedBitangentView,
  17555. transformedBitangentWorld: transformedBitangentWorld,
  17556. transformedClearcoatNormalView: transformedClearcoatNormalView,
  17557. transformedNormalView: transformedNormalView,
  17558. transformedNormalWorld: transformedNormalWorld,
  17559. transformedTangentView: transformedTangentView,
  17560. transformedTangentWorld: transformedTangentWorld,
  17561. transmission: transmission,
  17562. transpose: transpose,
  17563. tri: tri,
  17564. tri3: tri3,
  17565. triNoise3D: triNoise3D,
  17566. triplanarTexture: triplanarTexture,
  17567. triplanarTextures: triplanarTextures,
  17568. trunc: trunc,
  17569. tslFn: tslFn,
  17570. uint: uint,
  17571. uniform: uniform,
  17572. uniformArray: uniformArray,
  17573. uniformGroup: uniformGroup,
  17574. uniforms: uniforms,
  17575. userData: userData,
  17576. uv: uv,
  17577. uvec2: uvec2,
  17578. uvec3: uvec3,
  17579. uvec4: uvec4,
  17580. varying: varying,
  17581. varyingProperty: varyingProperty,
  17582. vec2: vec2,
  17583. vec3: vec3,
  17584. vec4: vec4,
  17585. vectorComponents: vectorComponents,
  17586. velocity: velocity,
  17587. vertexColor: vertexColor,
  17588. vertexIndex: vertexIndex,
  17589. vibrance: vibrance,
  17590. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  17591. viewZToOrthographicDepth: viewZToOrthographicDepth,
  17592. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  17593. viewport: viewport,
  17594. viewportBottomLeft: viewportBottomLeft,
  17595. viewportCoordinate: viewportCoordinate,
  17596. viewportDepthTexture: viewportDepthTexture,
  17597. viewportLinearDepth: viewportLinearDepth,
  17598. viewportMipTexture: viewportMipTexture,
  17599. viewportResolution: viewportResolution,
  17600. viewportSafeUV: viewportSafeUV,
  17601. viewportSharedTexture: viewportSharedTexture,
  17602. viewportSize: viewportSize,
  17603. viewportTexture: viewportTexture,
  17604. viewportTopLeft: viewportTopLeft,
  17605. viewportUV: viewportUV,
  17606. wgsl: wgsl,
  17607. wgslFn: wgslFn,
  17608. workgroupArray: workgroupArray,
  17609. workgroupBarrier: workgroupBarrier,
  17610. workgroupId: workgroupId,
  17611. workingToColorSpace: workingToColorSpace,
  17612. xor: xor
  17613. });
  17614. const _clearColor$1 = /*@__PURE__*/ new Color4();
  17615. class Background extends DataMap {
  17616. constructor( renderer, nodes ) {
  17617. super();
  17618. this.renderer = renderer;
  17619. this.nodes = nodes;
  17620. }
  17621. update( scene, renderList, renderContext ) {
  17622. const renderer = this.renderer;
  17623. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  17624. let forceClear = false;
  17625. if ( background === null ) {
  17626. // no background settings, use clear color configuration from the renderer
  17627. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  17628. _clearColor$1.a = renderer._clearColor.a;
  17629. } else if ( background.isColor === true ) {
  17630. // background is an opaque color
  17631. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  17632. _clearColor$1.a = 1;
  17633. forceClear = true;
  17634. } else if ( background.isNode === true ) {
  17635. const sceneData = this.get( scene );
  17636. const backgroundNode = background;
  17637. _clearColor$1.copy( renderer._clearColor );
  17638. let backgroundMesh = sceneData.backgroundMesh;
  17639. if ( backgroundMesh === undefined ) {
  17640. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  17641. // @TODO: Add Texture2D support using node context
  17642. getUV: () => backgroundRotation.mul( normalWorld ),
  17643. getTextureLevel: () => backgroundBlurriness
  17644. } );
  17645. let viewProj = modelViewProjection();
  17646. viewProj = viewProj.setZ( viewProj.w );
  17647. const nodeMaterial = new NodeMaterial();
  17648. nodeMaterial.name = 'Background.material';
  17649. nodeMaterial.side = BackSide;
  17650. nodeMaterial.depthTest = false;
  17651. nodeMaterial.depthWrite = false;
  17652. nodeMaterial.fog = false;
  17653. nodeMaterial.lights = false;
  17654. nodeMaterial.vertexNode = viewProj;
  17655. nodeMaterial.colorNode = backgroundMeshNode;
  17656. sceneData.backgroundMeshNode = backgroundMeshNode;
  17657. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  17658. backgroundMesh.frustumCulled = false;
  17659. backgroundMesh.name = 'Background.mesh';
  17660. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  17661. this.matrixWorld.copyPosition( camera.matrixWorld );
  17662. };
  17663. }
  17664. const backgroundCacheKey = backgroundNode.getCacheKey();
  17665. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  17666. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  17667. sceneData.backgroundMeshNode.needsUpdate = true;
  17668. backgroundMesh.material.needsUpdate = true;
  17669. sceneData.backgroundCacheKey = backgroundCacheKey;
  17670. }
  17671. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  17672. } else {
  17673. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  17674. }
  17675. //
  17676. if ( renderer.autoClear === true || forceClear === true ) {
  17677. const clearColorValue = renderContext.clearColorValue;
  17678. clearColorValue.r = _clearColor$1.r;
  17679. clearColorValue.g = _clearColor$1.g;
  17680. clearColorValue.b = _clearColor$1.b;
  17681. clearColorValue.a = _clearColor$1.a;
  17682. // premultiply alpha
  17683. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  17684. clearColorValue.r *= clearColorValue.a;
  17685. clearColorValue.g *= clearColorValue.a;
  17686. clearColorValue.b *= clearColorValue.a;
  17687. }
  17688. //
  17689. renderContext.depthClearValue = renderer._clearDepth;
  17690. renderContext.stencilClearValue = renderer._clearStencil;
  17691. renderContext.clearColor = renderer.autoClearColor === true;
  17692. renderContext.clearDepth = renderer.autoClearDepth === true;
  17693. renderContext.clearStencil = renderer.autoClearStencil === true;
  17694. } else {
  17695. renderContext.clearColor = false;
  17696. renderContext.clearDepth = false;
  17697. renderContext.clearStencil = false;
  17698. }
  17699. }
  17700. }
  17701. let _id$6 = 0;
  17702. class BindGroup {
  17703. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  17704. this.name = name;
  17705. this.bindings = bindings;
  17706. this.index = index;
  17707. this.bindingsReference = bindingsReference;
  17708. this.id = _id$6 ++;
  17709. }
  17710. }
  17711. class NodeBuilderState {
  17712. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  17713. this.vertexShader = vertexShader;
  17714. this.fragmentShader = fragmentShader;
  17715. this.computeShader = computeShader;
  17716. this.transforms = transforms;
  17717. this.nodeAttributes = nodeAttributes;
  17718. this.bindings = bindings;
  17719. this.updateNodes = updateNodes;
  17720. this.updateBeforeNodes = updateBeforeNodes;
  17721. this.updateAfterNodes = updateAfterNodes;
  17722. this.monitor = monitor;
  17723. this.usedTimes = 0;
  17724. }
  17725. createBindings() {
  17726. const bindings = [];
  17727. for ( const instanceGroup of this.bindings ) {
  17728. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  17729. if ( shared !== true ) {
  17730. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  17731. bindings.push( bindingsGroup );
  17732. for ( const instanceBinding of instanceGroup.bindings ) {
  17733. bindingsGroup.bindings.push( instanceBinding.clone() );
  17734. }
  17735. } else {
  17736. bindings.push( instanceGroup );
  17737. }
  17738. }
  17739. return bindings;
  17740. }
  17741. }
  17742. /**
  17743. * {@link NodeBuilder} is going to create instances of this class during the build process
  17744. * of nodes. They represent the final shader attributes that are going to be generated
  17745. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  17746. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  17747. */
  17748. class NodeAttribute {
  17749. /**
  17750. * Constructs a new node attribute.
  17751. *
  17752. * @param {String} name - The name of the attribute.
  17753. * @param {String} type - The type of the attribute.
  17754. * @param {Node?} node - An optional reference to the node.
  17755. */
  17756. constructor( name, type, node = null ) {
  17757. /**
  17758. * This flag can be used for type testing.
  17759. *
  17760. * @type {Boolean}
  17761. * @readonly
  17762. * @default true
  17763. */
  17764. this.isNodeAttribute = true;
  17765. /**
  17766. * The name of the attribute.
  17767. *
  17768. * @type {String}
  17769. */
  17770. this.name = name;
  17771. /**
  17772. * The type of the attribute.
  17773. *
  17774. * @type {String}
  17775. */
  17776. this.type = type;
  17777. /**
  17778. * An optional reference to the node.
  17779. *
  17780. * @type {Node?}
  17781. * @default null
  17782. */
  17783. this.node = node;
  17784. }
  17785. }
  17786. /**
  17787. * {@link NodeBuilder} is going to create instances of this class during the build process
  17788. * of nodes. They represent the final shader uniforms that are going to be generated
  17789. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  17790. * for this purpose.
  17791. */
  17792. class NodeUniform {
  17793. /**
  17794. * Constructs a new node uniform.
  17795. *
  17796. * @param {String} name - The name of the uniform.
  17797. * @param {String} type - The type of the uniform.
  17798. * @param {UniformNode} node - An reference to the node.
  17799. */
  17800. constructor( name, type, node ) {
  17801. /**
  17802. * This flag can be used for type testing.
  17803. *
  17804. * @type {Boolean}
  17805. * @readonly
  17806. * @default true
  17807. */
  17808. this.isNodeUniform = true;
  17809. /**
  17810. * The name of the uniform.
  17811. *
  17812. * @type {String}
  17813. */
  17814. this.name = name;
  17815. /**
  17816. * The type of the uniform.
  17817. *
  17818. * @type {String}
  17819. */
  17820. this.type = type;
  17821. /**
  17822. * An reference to the node.
  17823. *
  17824. * @type {UniformNode}
  17825. */
  17826. this.node = node.getSelf();
  17827. }
  17828. /**
  17829. * The value of the uniform node.
  17830. *
  17831. * @type {Any}
  17832. */
  17833. get value() {
  17834. return this.node.value;
  17835. }
  17836. set value( val ) {
  17837. this.node.value = val;
  17838. }
  17839. /**
  17840. * The id of the uniform node.
  17841. *
  17842. * @type {Number}
  17843. */
  17844. get id() {
  17845. return this.node.id;
  17846. }
  17847. /**
  17848. * The uniform node's group.
  17849. *
  17850. * @type {UniformGroupNode}
  17851. */
  17852. get groupNode() {
  17853. return this.node.groupNode;
  17854. }
  17855. }
  17856. /**
  17857. * {@link NodeBuilder} is going to create instances of this class during the build process
  17858. * of nodes. They represent the final shader variables that are going to be generated
  17859. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  17860. * this purpose.
  17861. */
  17862. class NodeVar {
  17863. /**
  17864. * Constructs a new node variable.
  17865. *
  17866. * @param {String} name - The name of the variable.
  17867. * @param {String} type - The type of the variable.
  17868. */
  17869. constructor( name, type ) {
  17870. /**
  17871. * This flag can be used for type testing.
  17872. *
  17873. * @type {Boolean}
  17874. * @readonly
  17875. * @default true
  17876. */
  17877. this.isNodeVar = true;
  17878. /**
  17879. * The name of the variable.
  17880. *
  17881. * @type {String}
  17882. */
  17883. this.name = name;
  17884. /**
  17885. * The type of the variable.
  17886. *
  17887. * @type {String}
  17888. */
  17889. this.type = type;
  17890. }
  17891. }
  17892. /**
  17893. * {@link NodeBuilder} is going to create instances of this class during the build process
  17894. * of nodes. They represent the final shader varyings that are going to be generated
  17895. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  17896. * this purpose.
  17897. *
  17898. * @augments NodeVar
  17899. */
  17900. class NodeVarying extends NodeVar {
  17901. /**
  17902. * Constructs a new node varying.
  17903. *
  17904. * @param {String} name - The name of the varying.
  17905. * @param {String} type - The type of the varying.
  17906. */
  17907. constructor( name, type ) {
  17908. super( name, type );
  17909. /**
  17910. * Whether this varying requires interpolation or not. This property can be used
  17911. * to check if the varying can be optimized for a variable.
  17912. *
  17913. * @type {Boolean}
  17914. * @default false
  17915. */
  17916. this.needsInterpolation = false;
  17917. /**
  17918. * This flag can be used for type testing.
  17919. *
  17920. * @type {Boolean}
  17921. * @readonly
  17922. * @default true
  17923. */
  17924. this.isNodeVarying = true;
  17925. }
  17926. }
  17927. /**
  17928. * {@link NodeBuilder} is going to create instances of this class during the build process
  17929. * of nodes. They represent user-defined, native shader code portions that are going to be
  17930. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  17931. * for this purpose.
  17932. */
  17933. class NodeCode {
  17934. /**
  17935. * Constructs a new code node.
  17936. *
  17937. * @param {String} name - The name of the code.
  17938. * @param {String} type - The node type.
  17939. * @param {String} [code=''] - The native shader code.
  17940. */
  17941. constructor( name, type, code = '' ) {
  17942. /**
  17943. * The name of the code.
  17944. *
  17945. * @type {String}
  17946. */
  17947. this.name = name;
  17948. /**
  17949. * The node type.
  17950. *
  17951. * @type {String}
  17952. */
  17953. this.type = type;
  17954. /**
  17955. * The native shader code.
  17956. *
  17957. * @type {String}
  17958. * @default ''
  17959. */
  17960. this.code = code;
  17961. Object.defineProperty( this, 'isNodeCode', { value: true } );
  17962. }
  17963. }
  17964. let _id$5 = 0;
  17965. /**
  17966. * This utility class is used in {@link NodeBuilder} as an internal
  17967. * cache data structure for node data.
  17968. */
  17969. class NodeCache {
  17970. /**
  17971. * Constructs a new node cache.
  17972. *
  17973. * @param {NodeCache?} parent - A reference to a parent cache.
  17974. */
  17975. constructor( parent = null ) {
  17976. /**
  17977. * The id of the cache.
  17978. *
  17979. * @type {Number}
  17980. * @readonly
  17981. */
  17982. this.id = _id$5 ++;
  17983. /**
  17984. * A weak map for managing node data.
  17985. *
  17986. * @type {WeakMap}
  17987. */
  17988. this.nodesData = new WeakMap();
  17989. /**
  17990. * Reference to a parent node cache.
  17991. *
  17992. * @type {NodeCache?}
  17993. * @default null
  17994. */
  17995. this.parent = parent;
  17996. }
  17997. /**
  17998. * Returns the data for the given node.
  17999. *
  18000. * @param {Node} node - The node.
  18001. * @return {Object?} The data for the node.
  18002. */
  18003. getData( node ) {
  18004. let data = this.nodesData.get( node );
  18005. if ( data === undefined && this.parent !== null ) {
  18006. data = this.parent.getData( node );
  18007. }
  18008. return data;
  18009. }
  18010. /**
  18011. * Sets the data for a given node.
  18012. *
  18013. * @param {Node} node - The node.
  18014. * @param {Object} data - The data that should be cached.
  18015. */
  18016. setData( node, data ) {
  18017. this.nodesData.set( node, data );
  18018. }
  18019. }
  18020. /**
  18021. * {@link NodeBuilder} is going to create instances of this class during the build process
  18022. * of nodes. They represent the final shader struct data that are going to be generated
  18023. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  18024. * for this purpose.
  18025. */
  18026. class StructTypeNode extends Node {
  18027. static get type() {
  18028. return 'StructTypeNode';
  18029. }
  18030. /**
  18031. * Constructs a new struct type node.
  18032. *
  18033. * @param {String} name - The name of the struct.
  18034. * @param {Array<String>} types - An array of types.
  18035. */
  18036. constructor( name, types ) {
  18037. super();
  18038. /**
  18039. * The name of the struct.
  18040. *
  18041. * @type {String}
  18042. */
  18043. this.name = name;
  18044. /**
  18045. * An array of types.
  18046. *
  18047. * @type {Array<String>}
  18048. */
  18049. this.types = types;
  18050. /**
  18051. * This flag can be used for type testing.
  18052. *
  18053. * @type {Boolean}
  18054. * @readonly
  18055. * @default true
  18056. */
  18057. this.isStructTypeNode = true;
  18058. }
  18059. /**
  18060. * Returns the member types.
  18061. *
  18062. * @return {Array<String>} The types.
  18063. */
  18064. getMemberTypes() {
  18065. return this.types;
  18066. }
  18067. }
  18068. class Uniform {
  18069. constructor( name, value ) {
  18070. this.name = name;
  18071. this.value = value;
  18072. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  18073. this.itemSize = 0;
  18074. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  18075. }
  18076. setValue( value ) {
  18077. this.value = value;
  18078. }
  18079. getValue() {
  18080. return this.value;
  18081. }
  18082. }
  18083. class NumberUniform extends Uniform {
  18084. constructor( name, value = 0 ) {
  18085. super( name, value );
  18086. this.isNumberUniform = true;
  18087. this.boundary = 4;
  18088. this.itemSize = 1;
  18089. }
  18090. }
  18091. class Vector2Uniform extends Uniform {
  18092. constructor( name, value = new Vector2() ) {
  18093. super( name, value );
  18094. this.isVector2Uniform = true;
  18095. this.boundary = 8;
  18096. this.itemSize = 2;
  18097. }
  18098. }
  18099. class Vector3Uniform extends Uniform {
  18100. constructor( name, value = new Vector3() ) {
  18101. super( name, value );
  18102. this.isVector3Uniform = true;
  18103. this.boundary = 16;
  18104. this.itemSize = 3;
  18105. }
  18106. }
  18107. class Vector4Uniform extends Uniform {
  18108. constructor( name, value = new Vector4() ) {
  18109. super( name, value );
  18110. this.isVector4Uniform = true;
  18111. this.boundary = 16;
  18112. this.itemSize = 4;
  18113. }
  18114. }
  18115. class ColorUniform extends Uniform {
  18116. constructor( name, value = new Color() ) {
  18117. super( name, value );
  18118. this.isColorUniform = true;
  18119. this.boundary = 16;
  18120. this.itemSize = 3;
  18121. }
  18122. }
  18123. class Matrix3Uniform extends Uniform {
  18124. constructor( name, value = new Matrix3() ) {
  18125. super( name, value );
  18126. this.isMatrix3Uniform = true;
  18127. this.boundary = 48;
  18128. this.itemSize = 12;
  18129. }
  18130. }
  18131. class Matrix4Uniform extends Uniform {
  18132. constructor( name, value = new Matrix4() ) {
  18133. super( name, value );
  18134. this.isMatrix4Uniform = true;
  18135. this.boundary = 64;
  18136. this.itemSize = 16;
  18137. }
  18138. }
  18139. class NumberNodeUniform extends NumberUniform {
  18140. constructor( nodeUniform ) {
  18141. super( nodeUniform.name, nodeUniform.value );
  18142. this.nodeUniform = nodeUniform;
  18143. }
  18144. getValue() {
  18145. return this.nodeUniform.value;
  18146. }
  18147. getType() {
  18148. return this.nodeUniform.type;
  18149. }
  18150. }
  18151. class Vector2NodeUniform extends Vector2Uniform {
  18152. constructor( nodeUniform ) {
  18153. super( nodeUniform.name, nodeUniform.value );
  18154. this.nodeUniform = nodeUniform;
  18155. }
  18156. getValue() {
  18157. return this.nodeUniform.value;
  18158. }
  18159. getType() {
  18160. return this.nodeUniform.type;
  18161. }
  18162. }
  18163. class Vector3NodeUniform extends Vector3Uniform {
  18164. constructor( nodeUniform ) {
  18165. super( nodeUniform.name, nodeUniform.value );
  18166. this.nodeUniform = nodeUniform;
  18167. }
  18168. getValue() {
  18169. return this.nodeUniform.value;
  18170. }
  18171. getType() {
  18172. return this.nodeUniform.type;
  18173. }
  18174. }
  18175. class Vector4NodeUniform extends Vector4Uniform {
  18176. constructor( nodeUniform ) {
  18177. super( nodeUniform.name, nodeUniform.value );
  18178. this.nodeUniform = nodeUniform;
  18179. }
  18180. getValue() {
  18181. return this.nodeUniform.value;
  18182. }
  18183. getType() {
  18184. return this.nodeUniform.type;
  18185. }
  18186. }
  18187. class ColorNodeUniform extends ColorUniform {
  18188. constructor( nodeUniform ) {
  18189. super( nodeUniform.name, nodeUniform.value );
  18190. this.nodeUniform = nodeUniform;
  18191. }
  18192. getValue() {
  18193. return this.nodeUniform.value;
  18194. }
  18195. getType() {
  18196. return this.nodeUniform.type;
  18197. }
  18198. }
  18199. class Matrix3NodeUniform extends Matrix3Uniform {
  18200. constructor( nodeUniform ) {
  18201. super( nodeUniform.name, nodeUniform.value );
  18202. this.nodeUniform = nodeUniform;
  18203. }
  18204. getValue() {
  18205. return this.nodeUniform.value;
  18206. }
  18207. getType() {
  18208. return this.nodeUniform.type;
  18209. }
  18210. }
  18211. class Matrix4NodeUniform extends Matrix4Uniform {
  18212. constructor( nodeUniform ) {
  18213. super( nodeUniform.name, nodeUniform.value );
  18214. this.nodeUniform = nodeUniform;
  18215. }
  18216. getValue() {
  18217. return this.nodeUniform.value;
  18218. }
  18219. getType() {
  18220. return this.nodeUniform.type;
  18221. }
  18222. }
  18223. const LOD_MIN = 4;
  18224. // The standard deviations (radians) associated with the extra mips. These are
  18225. // chosen to approximate a Trowbridge-Reitz distribution function times the
  18226. // geometric shadowing function. These sigma values squared must match the
  18227. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  18228. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  18229. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  18230. // samples and exit early, but not recompile the shader.
  18231. const MAX_SAMPLES = 20;
  18232. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  18233. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  18234. const _clearColor = /*@__PURE__*/ new Color();
  18235. let _oldTarget = null;
  18236. let _oldActiveCubeFace = 0;
  18237. let _oldActiveMipmapLevel = 0;
  18238. // Golden Ratio
  18239. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  18240. const INV_PHI = 1 / PHI;
  18241. // Vertices of a dodecahedron (except the opposites, which represent the
  18242. // same axis), used as axis directions evenly spread on a sphere.
  18243. const _axisDirections = [
  18244. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  18245. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  18246. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  18247. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  18248. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  18249. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  18250. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  18251. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  18252. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  18253. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  18254. ];
  18255. //
  18256. // WebGPU Face indices
  18257. const _faceLib = [
  18258. 3, 1, 5,
  18259. 0, 4, 2
  18260. ];
  18261. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  18262. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  18263. /**
  18264. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  18265. * (PMREM) from a cubeMap environment texture. This allows different levels of
  18266. * blur to be quickly accessed based on material roughness. It is packed into a
  18267. * special CubeUV format that allows us to perform custom interpolation so that
  18268. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  18269. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  18270. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  18271. * higher roughness levels. In this way we maintain resolution to smoothly
  18272. * interpolate diffuse lighting while limiting sampling computation.
  18273. *
  18274. * Paper: Fast, Accurate Image-Based Lighting
  18275. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  18276. */
  18277. class PMREMGenerator {
  18278. constructor( renderer ) {
  18279. this._renderer = renderer;
  18280. this._pingPongRenderTarget = null;
  18281. this._lodMax = 0;
  18282. this._cubeSize = 0;
  18283. this._lodPlanes = [];
  18284. this._sizeLods = [];
  18285. this._sigmas = [];
  18286. this._lodMeshes = [];
  18287. this._blurMaterial = null;
  18288. this._cubemapMaterial = null;
  18289. this._equirectMaterial = null;
  18290. this._backgroundBox = null;
  18291. }
  18292. get _hasInitialized() {
  18293. return this._renderer.hasInitialized();
  18294. }
  18295. /**
  18296. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18297. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18298. * in radians to be applied to the scene before PMREM generation. Optional near
  18299. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  18300. * is placed at the origin).
  18301. */
  18302. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  18303. this._setSize( 256 );
  18304. if ( this._hasInitialized === false ) {
  18305. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  18306. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18307. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  18308. return cubeUVRenderTarget;
  18309. }
  18310. _oldTarget = this._renderer.getRenderTarget();
  18311. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18312. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18313. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18314. cubeUVRenderTarget.depthBuffer = true;
  18315. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  18316. if ( sigma > 0 ) {
  18317. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  18318. }
  18319. this._applyPMREM( cubeUVRenderTarget );
  18320. this._cleanup( cubeUVRenderTarget );
  18321. return cubeUVRenderTarget;
  18322. }
  18323. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  18324. if ( this._hasInitialized === false ) await this._renderer.init();
  18325. return this.fromScene( scene, sigma, near, far, renderTarget );
  18326. }
  18327. /**
  18328. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18329. * or HDR. The ideal input image size is 1k (1024 x 512),
  18330. * as this matches best with the 256 x 256 cubemap output.
  18331. */
  18332. fromEquirectangular( equirectangular, renderTarget = null ) {
  18333. if ( this._hasInitialized === false ) {
  18334. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  18335. this._setSizeFromTexture( equirectangular );
  18336. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18337. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  18338. return cubeUVRenderTarget;
  18339. }
  18340. return this._fromTexture( equirectangular, renderTarget );
  18341. }
  18342. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  18343. if ( this._hasInitialized === false ) await this._renderer.init();
  18344. return this._fromTexture( equirectangular, renderTarget );
  18345. }
  18346. /**
  18347. * Generates a PMREM from an cubemap texture, which can be either LDR
  18348. * or HDR. The ideal input cube size is 256 x 256,
  18349. * as this matches best with the 256 x 256 cubemap output.
  18350. */
  18351. fromCubemap( cubemap, renderTarget = null ) {
  18352. if ( this._hasInitialized === false ) {
  18353. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  18354. this._setSizeFromTexture( cubemap );
  18355. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18356. this.fromCubemapAsync( cubemap, renderTarget );
  18357. return cubeUVRenderTarget;
  18358. }
  18359. return this._fromTexture( cubemap, renderTarget );
  18360. }
  18361. async fromCubemapAsync( cubemap, renderTarget = null ) {
  18362. if ( this._hasInitialized === false ) await this._renderer.init();
  18363. return this._fromTexture( cubemap, renderTarget );
  18364. }
  18365. /**
  18366. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  18367. * your texture's network fetch for increased concurrency.
  18368. */
  18369. async compileCubemapShader() {
  18370. if ( this._cubemapMaterial === null ) {
  18371. this._cubemapMaterial = _getCubemapMaterial();
  18372. await this._compileMaterial( this._cubemapMaterial );
  18373. }
  18374. }
  18375. /**
  18376. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  18377. * your texture's network fetch for increased concurrency.
  18378. */
  18379. async compileEquirectangularShader() {
  18380. if ( this._equirectMaterial === null ) {
  18381. this._equirectMaterial = _getEquirectMaterial();
  18382. await this._compileMaterial( this._equirectMaterial );
  18383. }
  18384. }
  18385. /**
  18386. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  18387. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  18388. * one of them will cause any others to also become unusable.
  18389. */
  18390. dispose() {
  18391. this._dispose();
  18392. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  18393. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  18394. if ( this._backgroundBox !== null ) {
  18395. this._backgroundBox.geometry.dispose();
  18396. this._backgroundBox.material.dispose();
  18397. }
  18398. }
  18399. // private interface
  18400. _setSizeFromTexture( texture ) {
  18401. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  18402. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  18403. } else { // Equirectangular
  18404. this._setSize( texture.image.width / 4 );
  18405. }
  18406. }
  18407. _setSize( cubeSize ) {
  18408. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  18409. this._cubeSize = Math.pow( 2, this._lodMax );
  18410. }
  18411. _dispose() {
  18412. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  18413. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  18414. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  18415. this._lodPlanes[ i ].dispose();
  18416. }
  18417. }
  18418. _cleanup( outputTarget ) {
  18419. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  18420. outputTarget.scissorTest = false;
  18421. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  18422. }
  18423. _fromTexture( texture, renderTarget ) {
  18424. this._setSizeFromTexture( texture );
  18425. _oldTarget = this._renderer.getRenderTarget();
  18426. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18427. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18428. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18429. this._textureToCubeUV( texture, cubeUVRenderTarget );
  18430. this._applyPMREM( cubeUVRenderTarget );
  18431. this._cleanup( cubeUVRenderTarget );
  18432. return cubeUVRenderTarget;
  18433. }
  18434. _allocateTargets() {
  18435. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  18436. const height = 4 * this._cubeSize;
  18437. const params = {
  18438. magFilter: LinearFilter,
  18439. minFilter: LinearFilter,
  18440. generateMipmaps: false,
  18441. type: HalfFloatType,
  18442. format: RGBAFormat,
  18443. colorSpace: LinearSRGBColorSpace,
  18444. //depthBuffer: false
  18445. };
  18446. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  18447. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  18448. if ( this._pingPongRenderTarget !== null ) {
  18449. this._dispose();
  18450. }
  18451. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  18452. const { _lodMax } = this;
  18453. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  18454. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  18455. }
  18456. return cubeUVRenderTarget;
  18457. }
  18458. async _compileMaterial( material ) {
  18459. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  18460. await this._renderer.compile( tmpMesh, _flatCamera );
  18461. }
  18462. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  18463. const cubeCamera = _cubeCamera;
  18464. cubeCamera.near = near;
  18465. cubeCamera.far = far;
  18466. // px, py, pz, nx, ny, nz
  18467. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  18468. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  18469. const renderer = this._renderer;
  18470. const originalAutoClear = renderer.autoClear;
  18471. renderer.getClearColor( _clearColor );
  18472. renderer.autoClear = false;
  18473. let backgroundBox = this._backgroundBox;
  18474. if ( backgroundBox === null ) {
  18475. const backgroundMaterial = new MeshBasicMaterial( {
  18476. name: 'PMREM.Background',
  18477. side: BackSide,
  18478. depthWrite: false,
  18479. depthTest: false
  18480. } );
  18481. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  18482. }
  18483. let useSolidColor = false;
  18484. const background = scene.background;
  18485. if ( background ) {
  18486. if ( background.isColor ) {
  18487. backgroundBox.material.color.copy( background );
  18488. scene.background = null;
  18489. useSolidColor = true;
  18490. }
  18491. } else {
  18492. backgroundBox.material.color.copy( _clearColor );
  18493. useSolidColor = true;
  18494. }
  18495. renderer.setRenderTarget( cubeUVRenderTarget );
  18496. renderer.clear();
  18497. if ( useSolidColor ) {
  18498. renderer.render( backgroundBox, cubeCamera );
  18499. }
  18500. for ( let i = 0; i < 6; i ++ ) {
  18501. const col = i % 3;
  18502. if ( col === 0 ) {
  18503. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18504. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  18505. } else if ( col === 1 ) {
  18506. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18507. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  18508. } else {
  18509. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18510. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  18511. }
  18512. const size = this._cubeSize;
  18513. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18514. renderer.render( scene, cubeCamera );
  18515. }
  18516. renderer.autoClear = originalAutoClear;
  18517. scene.background = background;
  18518. }
  18519. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18520. const renderer = this._renderer;
  18521. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18522. if ( isCubeTexture ) {
  18523. if ( this._cubemapMaterial === null ) {
  18524. this._cubemapMaterial = _getCubemapMaterial( texture );
  18525. }
  18526. } else {
  18527. if ( this._equirectMaterial === null ) {
  18528. this._equirectMaterial = _getEquirectMaterial( texture );
  18529. }
  18530. }
  18531. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18532. material.fragmentNode.value = texture;
  18533. const mesh = this._lodMeshes[ 0 ];
  18534. mesh.material = material;
  18535. const size = this._cubeSize;
  18536. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18537. renderer.setRenderTarget( cubeUVRenderTarget );
  18538. renderer.render( mesh, _flatCamera );
  18539. }
  18540. _applyPMREM( cubeUVRenderTarget ) {
  18541. const renderer = this._renderer;
  18542. const autoClear = renderer.autoClear;
  18543. renderer.autoClear = false;
  18544. const n = this._lodPlanes.length;
  18545. for ( let i = 1; i < n; i ++ ) {
  18546. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  18547. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  18548. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  18549. }
  18550. renderer.autoClear = autoClear;
  18551. }
  18552. /**
  18553. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18554. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18555. * the blur latitudinally (around the poles), and then longitudinally (towards
  18556. * the poles) to approximate the orthogonally-separable blur. It is least
  18557. * accurate at the poles, but still does a decent job.
  18558. */
  18559. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18560. const pingPongRenderTarget = this._pingPongRenderTarget;
  18561. this._halfBlur(
  18562. cubeUVRenderTarget,
  18563. pingPongRenderTarget,
  18564. lodIn,
  18565. lodOut,
  18566. sigma,
  18567. 'latitudinal',
  18568. poleAxis );
  18569. this._halfBlur(
  18570. pingPongRenderTarget,
  18571. cubeUVRenderTarget,
  18572. lodOut,
  18573. lodOut,
  18574. sigma,
  18575. 'longitudinal',
  18576. poleAxis );
  18577. }
  18578. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18579. const renderer = this._renderer;
  18580. const blurMaterial = this._blurMaterial;
  18581. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18582. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  18583. }
  18584. // Number of standard deviations at which to cut off the discrete approximation.
  18585. const STANDARD_DEVIATIONS = 3;
  18586. const blurMesh = this._lodMeshes[ lodOut ];
  18587. blurMesh.material = blurMaterial;
  18588. const blurUniforms = blurMaterial.uniforms;
  18589. const pixels = this._sizeLods[ lodIn ] - 1;
  18590. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18591. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18592. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18593. if ( samples > MAX_SAMPLES ) {
  18594. console.warn( `sigmaRadians, ${
  18595. sigmaRadians}, is too large and will clip, as it requested ${
  18596. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18597. }
  18598. const weights = [];
  18599. let sum = 0;
  18600. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18601. const x = i / sigmaPixels;
  18602. const weight = Math.exp( - x * x / 2 );
  18603. weights.push( weight );
  18604. if ( i === 0 ) {
  18605. sum += weight;
  18606. } else if ( i < samples ) {
  18607. sum += 2 * weight;
  18608. }
  18609. }
  18610. for ( let i = 0; i < weights.length; i ++ ) {
  18611. weights[ i ] = weights[ i ] / sum;
  18612. }
  18613. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18614. blurUniforms.envMap.value = targetIn.texture;
  18615. blurUniforms.samples.value = samples;
  18616. blurUniforms.weights.array = weights;
  18617. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18618. if ( poleAxis ) {
  18619. blurUniforms.poleAxis.value = poleAxis;
  18620. }
  18621. const { _lodMax } = this;
  18622. blurUniforms.dTheta.value = radiansPerPixel;
  18623. blurUniforms.mipInt.value = _lodMax - lodIn;
  18624. const outputSize = this._sizeLods[ lodOut ];
  18625. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18626. const y = 4 * ( this._cubeSize - outputSize );
  18627. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18628. renderer.setRenderTarget( targetOut );
  18629. renderer.render( blurMesh, _flatCamera );
  18630. }
  18631. }
  18632. function _createPlanes( lodMax ) {
  18633. const lodPlanes = [];
  18634. const sizeLods = [];
  18635. const sigmas = [];
  18636. const lodMeshes = [];
  18637. let lod = lodMax;
  18638. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18639. for ( let i = 0; i < totalLods; i ++ ) {
  18640. const sizeLod = Math.pow( 2, lod );
  18641. sizeLods.push( sizeLod );
  18642. let sigma = 1.0 / sizeLod;
  18643. if ( i > lodMax - LOD_MIN ) {
  18644. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18645. } else if ( i === 0 ) {
  18646. sigma = 0;
  18647. }
  18648. sigmas.push( sigma );
  18649. const texelSize = 1.0 / ( sizeLod - 2 );
  18650. const min = - texelSize;
  18651. const max = 1 + texelSize;
  18652. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18653. const cubeFaces = 6;
  18654. const vertices = 6;
  18655. const positionSize = 3;
  18656. const uvSize = 2;
  18657. const faceIndexSize = 1;
  18658. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18659. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18660. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18661. for ( let face = 0; face < cubeFaces; face ++ ) {
  18662. const x = ( face % 3 ) * 2 / 3 - 1;
  18663. const y = face > 2 ? 0 : - 1;
  18664. const coordinates = [
  18665. x, y, 0,
  18666. x + 2 / 3, y, 0,
  18667. x + 2 / 3, y + 1, 0,
  18668. x, y, 0,
  18669. x + 2 / 3, y + 1, 0,
  18670. x, y + 1, 0
  18671. ];
  18672. const faceIdx = _faceLib[ face ];
  18673. position.set( coordinates, positionSize * vertices * faceIdx );
  18674. uv.set( uv1, uvSize * vertices * faceIdx );
  18675. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18676. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18677. }
  18678. const planes = new BufferGeometry();
  18679. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18680. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18681. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18682. lodPlanes.push( planes );
  18683. lodMeshes.push( new Mesh( planes, null ) );
  18684. if ( lod > LOD_MIN ) {
  18685. lod --;
  18686. }
  18687. }
  18688. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  18689. }
  18690. function _createRenderTarget( width, height, params ) {
  18691. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18692. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18693. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18694. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18695. cubeUVRenderTarget.scissorTest = true;
  18696. return cubeUVRenderTarget;
  18697. }
  18698. function _setViewport( target, x, y, width, height ) {
  18699. target.viewport.set( x, y, width, height );
  18700. target.scissor.set( x, y, width, height );
  18701. }
  18702. function _getMaterial( type ) {
  18703. const material = new NodeMaterial();
  18704. material.depthTest = false;
  18705. material.depthWrite = false;
  18706. material.blending = NoBlending;
  18707. material.name = `PMREM_${ type }`;
  18708. return material;
  18709. }
  18710. function _getBlurShader( lodMax, width, height ) {
  18711. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18712. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18713. const dTheta = uniform( 0 );
  18714. const n = float( MAX_SAMPLES );
  18715. const latitudinal = uniform( 0 ); // false, bool
  18716. const samples = uniform( 1 ); // int
  18717. const envMap = texture( null );
  18718. const mipInt = uniform( 0 ); // int
  18719. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18720. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18721. const CUBEUV_MAX_MIP = float( lodMax );
  18722. const materialUniforms = {
  18723. n,
  18724. latitudinal,
  18725. weights,
  18726. poleAxis,
  18727. outputDirection,
  18728. dTheta,
  18729. samples,
  18730. envMap,
  18731. mipInt,
  18732. CUBEUV_TEXEL_WIDTH,
  18733. CUBEUV_TEXEL_HEIGHT,
  18734. CUBEUV_MAX_MIP
  18735. };
  18736. const material = _getMaterial( 'blur' );
  18737. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  18738. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18739. return material;
  18740. }
  18741. function _getCubemapMaterial( envTexture ) {
  18742. const material = _getMaterial( 'cubemap' );
  18743. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  18744. return material;
  18745. }
  18746. function _getEquirectMaterial( envTexture ) {
  18747. const material = _getMaterial( 'equirect' );
  18748. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  18749. return material;
  18750. }
  18751. const rendererCache = new WeakMap();
  18752. const typeFromArray = new Map( [
  18753. [ Int8Array, 'int' ],
  18754. [ Int16Array, 'int' ],
  18755. [ Int32Array, 'int' ],
  18756. [ Uint8Array, 'uint' ],
  18757. [ Uint16Array, 'uint' ],
  18758. [ Uint32Array, 'uint' ],
  18759. [ Float32Array, 'float' ]
  18760. ] );
  18761. const toFloat = ( value ) => {
  18762. if ( /e/g.test( value ) ) {
  18763. return String( value ).replace( /\+/g, '' );
  18764. } else {
  18765. value = Number( value );
  18766. return value + ( value % 1 ? '' : '.0' );
  18767. }
  18768. };
  18769. /**
  18770. * Base class for builders which generate a shader program based
  18771. * on a 3D object and its node material definition.
  18772. */
  18773. class NodeBuilder {
  18774. /**
  18775. * Constructs a new node builder.
  18776. *
  18777. * @param {Object3D} object - The 3D object.
  18778. * @param {Renderer} renderer - The current renderer.
  18779. * @param {NodeParser} parser - A reference to a node parser.
  18780. */
  18781. constructor( object, renderer, parser ) {
  18782. /**
  18783. * The 3D object.
  18784. *
  18785. * @type {Object3D}
  18786. */
  18787. this.object = object;
  18788. /**
  18789. * The material of the 3D object.
  18790. *
  18791. * @type {Material?}
  18792. */
  18793. this.material = ( object && object.material ) || null;
  18794. /**
  18795. * The geometry of the 3D object.
  18796. *
  18797. * @type {BufferGeometry?}
  18798. */
  18799. this.geometry = ( object && object.geometry ) || null;
  18800. /**
  18801. * The current renderer.
  18802. *
  18803. * @type {Renderer}
  18804. */
  18805. this.renderer = renderer;
  18806. /**
  18807. * A reference to a node parser.
  18808. *
  18809. * @type {NodeParser}
  18810. */
  18811. this.parser = parser;
  18812. /**
  18813. * The scene the 3D object belongs to.
  18814. *
  18815. * @type {Scene?}
  18816. * @default null
  18817. */
  18818. this.scene = null;
  18819. /**
  18820. * The camera the 3D object is rendered with.
  18821. *
  18822. * @type {Camera?}
  18823. * @default null
  18824. */
  18825. this.camera = null;
  18826. /**
  18827. * A list of all nodes the builder is processing
  18828. * for this 3D object.
  18829. *
  18830. * @type {Array<Node>}
  18831. */
  18832. this.nodes = [];
  18833. /**
  18834. * A list of all sequential nodes.
  18835. *
  18836. * @type {Array<Node>}
  18837. */
  18838. this.sequentialNodes = [];
  18839. /**
  18840. * A list of all nodes which {@link Node#update} method should be executed.
  18841. *
  18842. * @type {Array<Node>}
  18843. */
  18844. this.updateNodes = [];
  18845. /**
  18846. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  18847. *
  18848. * @type {Array<Node>}
  18849. */
  18850. this.updateBeforeNodes = [];
  18851. /**
  18852. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  18853. *
  18854. * @type {Array<Node>}
  18855. */
  18856. this.updateAfterNodes = [];
  18857. /**
  18858. * A dictionary that assigns each node to a unique hash.
  18859. *
  18860. * @type {Object<Number,Node>}
  18861. */
  18862. this.hashNodes = {};
  18863. /**
  18864. * A reference to a node material observer.
  18865. *
  18866. * @type {NodeMaterialObserver?}
  18867. * @default null
  18868. */
  18869. this.monitor = null;
  18870. /**
  18871. * A reference to the current lights node.
  18872. *
  18873. * @type {LightsNode?}
  18874. * @default null
  18875. */
  18876. this.lightsNode = null;
  18877. /**
  18878. * A reference to the current environment node.
  18879. *
  18880. * @type {Node?}
  18881. * @default null
  18882. */
  18883. this.environmentNode = null;
  18884. /**
  18885. * A reference to the current fog node.
  18886. *
  18887. * @type {FogNode?}
  18888. * @default null
  18889. */
  18890. this.fogNode = null;
  18891. /**
  18892. * The current clipping context.
  18893. *
  18894. * @type {ClippingContext?}
  18895. */
  18896. this.clippingContext = null;
  18897. /**
  18898. * The generated vertex shader.
  18899. *
  18900. * @type {String?}
  18901. */
  18902. this.vertexShader = null;
  18903. /**
  18904. * The generated fragment shader.
  18905. *
  18906. * @type {String?}
  18907. */
  18908. this.fragmentShader = null;
  18909. /**
  18910. * The generated compute shader.
  18911. *
  18912. * @type {String?}
  18913. */
  18914. this.computeShader = null;
  18915. /**
  18916. * Nodes used in the primary flow of code generation.
  18917. *
  18918. * @type {Object<String,Array<Node>>}
  18919. */
  18920. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  18921. /**
  18922. * Nodes code from `.flowNodes`.
  18923. *
  18924. * @type {Object<String,String>}
  18925. */
  18926. this.flowCode = { vertex: '', fragment: '', compute: '' };
  18927. /**
  18928. * This dictionary holds the node uniforms of the builder.
  18929. * The uniforms are maintained in an array for each shader stage.
  18930. *
  18931. * @type {Object}
  18932. */
  18933. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  18934. /**
  18935. * This dictionary holds the output structs of the builder.
  18936. * The structs are maintained in an array for each shader stage.
  18937. *
  18938. * @type {Object}
  18939. */
  18940. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  18941. /**
  18942. * This dictionary holds the bindings for each shader stage.
  18943. *
  18944. * @type {Object}
  18945. */
  18946. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  18947. /**
  18948. * This dictionary maintains the binding indices per bind group.
  18949. *
  18950. * @type {Object}
  18951. */
  18952. this.bindingsIndexes = {};
  18953. /**
  18954. * Reference to the array of bind groups.
  18955. *
  18956. * @type {Array<BindGroup>?}
  18957. */
  18958. this.bindGroups = null;
  18959. /**
  18960. * This array holds the node attributes of this builder
  18961. * created via {@link AttributeNode}.
  18962. *
  18963. * @type {Array<NodeAttribute>}
  18964. */
  18965. this.attributes = [];
  18966. /**
  18967. * This array holds the node attributes of this builder
  18968. * created via {@link BufferAttributeNode}.
  18969. *
  18970. * @type {Array<NodeAttribute>}
  18971. */
  18972. this.bufferAttributes = [];
  18973. /**
  18974. * This array holds the node varyings of this builder.
  18975. *
  18976. * @type {Array<NodeVarying>}
  18977. */
  18978. this.varyings = [];
  18979. /**
  18980. * This dictionary holds the (native) node codes of this builder.
  18981. * The codes are maintained in an array for each shader stage.
  18982. *
  18983. * @type {Object<String,Array<NodeCode>>}
  18984. */
  18985. this.codes = {};
  18986. /**
  18987. * This dictionary holds the node variables of this builder.
  18988. * The variables are maintained in an array for each shader stage.
  18989. *
  18990. * @type {Object<String,Array<NodeVar>>}
  18991. */
  18992. this.vars = {};
  18993. /**
  18994. * Current code flow.
  18995. * All code generated in this stack will be stored in `.flow`.
  18996. *
  18997. * @type {{code: String}}
  18998. */
  18999. this.flow = { code: '' };
  19000. /**
  19001. * A chain of nodes.
  19002. * Used to check recursive calls in node-graph.
  19003. *
  19004. * @type {Array<Node>}
  19005. */
  19006. this.chaining = [];
  19007. /**
  19008. * The current stack.
  19009. * This reflects the current process in the code block hierarchy,
  19010. * it is useful to know if the current process is inside a conditional for example.
  19011. *
  19012. * @type {StackNode}
  19013. */
  19014. this.stack = stack();
  19015. /**
  19016. * List of stack nodes.
  19017. * The current stack hierarchy is stored in an array.
  19018. *
  19019. * @type {Array<StackNode>}
  19020. */
  19021. this.stacks = [];
  19022. /**
  19023. * A tab value. Used for shader string generation.
  19024. *
  19025. * @type {String}
  19026. * @default '\t'
  19027. */
  19028. this.tab = '\t';
  19029. /**
  19030. * Reference to the current function node.
  19031. *
  19032. * @type {FunctionNode?}
  19033. * @default null
  19034. */
  19035. this.currentFunctionNode = null;
  19036. /**
  19037. * The builder's context.
  19038. *
  19039. * @type {Object}
  19040. */
  19041. this.context = {
  19042. material: this.material
  19043. };
  19044. /**
  19045. * The builder's cache.
  19046. *
  19047. * @type {NodeCache}
  19048. */
  19049. this.cache = new NodeCache();
  19050. /**
  19051. * Since the {@link NodeBuilder#cache} might be temporarily
  19052. * overwritten by other caches, this member retains the reference
  19053. * to the builder's own cache.
  19054. *
  19055. * @type {NodeCache}
  19056. * @default this.cache
  19057. */
  19058. this.globalCache = this.cache;
  19059. this.flowsData = new WeakMap();
  19060. /**
  19061. * The current shader stage.
  19062. *
  19063. * @type {('vertex'|'fragment'|'compute'|'any')?}
  19064. */
  19065. this.shaderStage = null;
  19066. /**
  19067. * The current build stage.
  19068. *
  19069. * @type {('setup'|'analyze'|'generate')?}
  19070. */
  19071. this.buildStage = null;
  19072. /**
  19073. * Whether comparison in shader code are generated with methods or not.
  19074. *
  19075. * @type {Boolean}
  19076. * @default false
  19077. */
  19078. this.useComparisonMethod = false;
  19079. }
  19080. /**
  19081. * Returns the bind groups of the current renderer.
  19082. *
  19083. * @return {ChainMap} The cache.
  19084. */
  19085. getBindGroupsCache() {
  19086. let bindGroupsCache = rendererCache.get( this.renderer );
  19087. if ( bindGroupsCache === undefined ) {
  19088. bindGroupsCache = new ChainMap();
  19089. rendererCache.set( this.renderer, bindGroupsCache );
  19090. }
  19091. return bindGroupsCache;
  19092. }
  19093. /**
  19094. * Factory method for creating an instance of {@link RenderTarget} with the given
  19095. * dimensions and options.
  19096. *
  19097. * @param {Number} width - The width of the render target.
  19098. * @param {Number} height - The height of the render target.
  19099. * @param {Object} options - The options of the render target.
  19100. * @return {RenderTarget} The render target.
  19101. */
  19102. createRenderTarget( width, height, options ) {
  19103. return new RenderTarget( width, height, options );
  19104. }
  19105. /**
  19106. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  19107. * dimensions and options.
  19108. *
  19109. * @param {Number} size - The size of the cube render target.
  19110. * @param {Object} options - The options of the cube render target.
  19111. * @return {CubeRenderTarget} The cube render target.
  19112. */
  19113. createCubeRenderTarget( size, options ) {
  19114. return new CubeRenderTarget( size, options );
  19115. }
  19116. /**
  19117. * Factory method for creating an instance of {@link PMREMGenerator}.
  19118. *
  19119. * @return {PMREMGenerator} The PMREM generator.
  19120. */
  19121. createPMREMGenerator() {
  19122. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  19123. return new PMREMGenerator( this.renderer );
  19124. }
  19125. /**
  19126. * Whether the given node is included in the internal array of nodes or not.
  19127. *
  19128. * @param {Node} node - The node to test.
  19129. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  19130. */
  19131. includes( node ) {
  19132. return this.nodes.includes( node );
  19133. }
  19134. /**
  19135. * Returns a bind group for the given group name and binding.
  19136. *
  19137. * @private
  19138. * @param {String} groupName - The group name.
  19139. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  19140. * @return {BindGroup} The bind group
  19141. */
  19142. _getBindGroup( groupName, bindings ) {
  19143. const bindGroupsCache = this.getBindGroupsCache();
  19144. //
  19145. const bindingsArray = [];
  19146. let sharedGroup = true;
  19147. for ( const binding of bindings ) {
  19148. bindingsArray.push( binding );
  19149. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  19150. }
  19151. //
  19152. let bindGroup;
  19153. if ( sharedGroup ) {
  19154. bindGroup = bindGroupsCache.get( bindingsArray );
  19155. if ( bindGroup === undefined ) {
  19156. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  19157. bindGroupsCache.set( bindingsArray, bindGroup );
  19158. }
  19159. } else {
  19160. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  19161. }
  19162. return bindGroup;
  19163. }
  19164. /**
  19165. * Returns an array of node uniform groups for the given group name and shader stage.
  19166. *
  19167. * @param {String} groupName - The group name.
  19168. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  19169. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  19170. */
  19171. getBindGroupArray( groupName, shaderStage ) {
  19172. const bindings = this.bindings[ shaderStage ];
  19173. let bindGroup = bindings[ groupName ];
  19174. if ( bindGroup === undefined ) {
  19175. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  19176. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  19177. }
  19178. bindings[ groupName ] = bindGroup = [];
  19179. }
  19180. return bindGroup;
  19181. }
  19182. /**
  19183. * Returns a list bindings of all shader stages separated by groups.
  19184. *
  19185. * @return {Array<BindGroup>} The list of bindings.
  19186. */
  19187. getBindings() {
  19188. let bindingsGroups = this.bindGroups;
  19189. if ( bindingsGroups === null ) {
  19190. const groups = {};
  19191. const bindings = this.bindings;
  19192. for ( const shaderStage of shaderStages ) {
  19193. for ( const groupName in bindings[ shaderStage ] ) {
  19194. const uniforms = bindings[ shaderStage ][ groupName ];
  19195. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  19196. groupUniforms.push( ...uniforms );
  19197. }
  19198. }
  19199. bindingsGroups = [];
  19200. for ( const groupName in groups ) {
  19201. const group = groups[ groupName ];
  19202. const bindingsGroup = this._getBindGroup( groupName, group );
  19203. bindingsGroups.push( bindingsGroup );
  19204. }
  19205. this.bindGroups = bindingsGroups;
  19206. }
  19207. return bindingsGroups;
  19208. }
  19209. /**
  19210. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  19211. */
  19212. sortBindingGroups() {
  19213. const bindingsGroups = this.getBindings();
  19214. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  19215. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  19216. const bindingGroup = bindingsGroups[ i ];
  19217. this.bindingsIndexes[ bindingGroup.name ].group = i;
  19218. bindingGroup.index = i;
  19219. }
  19220. }
  19221. /**
  19222. * The builder maintains each node in a hash-based dictionary.
  19223. * This method sets the given node (value) with the given hash (key) into this dictionary.
  19224. *
  19225. * @param {Node} node - The node to add.
  19226. * @param {Number} hash - The hash of the node.
  19227. */
  19228. setHashNode( node, hash ) {
  19229. this.hashNodes[ hash ] = node;
  19230. }
  19231. /**
  19232. * Adds a node to this builder.
  19233. *
  19234. * @param {Node} node - The node to add.
  19235. */
  19236. addNode( node ) {
  19237. if ( this.nodes.includes( node ) === false ) {
  19238. this.nodes.push( node );
  19239. this.setHashNode( node, node.getHash( this ) );
  19240. }
  19241. }
  19242. /**
  19243. * It is used to add Nodes that will be used as FRAME and RENDER events,
  19244. * and need to follow a certain sequence in the calls to work correctly.
  19245. *
  19246. * @param {Node} node - The node to add.
  19247. */
  19248. addSequentialNode( node ) {
  19249. if ( this.sequentialNodes.includes( node ) === false ) {
  19250. this.sequentialNodes.push( node );
  19251. }
  19252. }
  19253. /**
  19254. * Checks the update types of nodes
  19255. */
  19256. buildUpdateNodes() {
  19257. for ( const node of this.nodes ) {
  19258. const updateType = node.getUpdateType();
  19259. if ( updateType !== NodeUpdateType.NONE ) {
  19260. this.updateNodes.push( node.getSelf() );
  19261. }
  19262. }
  19263. for ( const node of this.sequentialNodes ) {
  19264. const updateBeforeType = node.getUpdateBeforeType();
  19265. const updateAfterType = node.getUpdateAfterType();
  19266. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  19267. this.updateBeforeNodes.push( node.getSelf() );
  19268. }
  19269. if ( updateAfterType !== NodeUpdateType.NONE ) {
  19270. this.updateAfterNodes.push( node.getSelf() );
  19271. }
  19272. }
  19273. }
  19274. /**
  19275. * A reference the current node which is the
  19276. * last node in the chain of nodes.
  19277. *
  19278. * @type {Node}
  19279. */
  19280. get currentNode() {
  19281. return this.chaining[ this.chaining.length - 1 ];
  19282. }
  19283. /**
  19284. * Whether the given texture is filtered or not.
  19285. *
  19286. * @param {Texture} texture - The texture to check.
  19287. * @return {Boolean} Whether the given texture is filtered or not.
  19288. */
  19289. isFilteredTexture( texture ) {
  19290. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  19291. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  19292. }
  19293. /**
  19294. * Adds the given node to the internal node chain.
  19295. * This is used to check recursive calls in node-graph.
  19296. *
  19297. * @param {Node} node - The node to add.
  19298. */
  19299. addChain( node ) {
  19300. /*
  19301. if ( this.chaining.indexOf( node ) !== - 1 ) {
  19302. console.warn( 'Recursive node: ', node );
  19303. }
  19304. */
  19305. this.chaining.push( node );
  19306. }
  19307. /**
  19308. * Removes the given node from the internal node chain.
  19309. *
  19310. * @param {Node} node - The node to remove.
  19311. */
  19312. removeChain( node ) {
  19313. const lastChain = this.chaining.pop();
  19314. if ( lastChain !== node ) {
  19315. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  19316. }
  19317. }
  19318. /**
  19319. * Returns the native shader method name for a given generic name. E.g.
  19320. * the method name `textureDimensions` matches the WGSL name but must be
  19321. * resolved to `textureSize` in GLSL.
  19322. *
  19323. * @abstract
  19324. * @param {String} name - The method name to resolve.
  19325. * @return {String} The resolved method name.
  19326. */
  19327. getMethod( method ) {
  19328. return method;
  19329. }
  19330. /**
  19331. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  19332. *
  19333. * @param {Number} hash - The hash of the node.
  19334. * @return {Node} The found node.
  19335. */
  19336. getNodeFromHash( hash ) {
  19337. return this.hashNodes[ hash ];
  19338. }
  19339. /**
  19340. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  19341. *
  19342. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  19343. * @param {Node} node - The node to add.
  19344. * @return {Node} The node.
  19345. */
  19346. addFlow( shaderStage, node ) {
  19347. this.flowNodes[ shaderStage ].push( node );
  19348. return node;
  19349. }
  19350. /**
  19351. * Sets builder's context.
  19352. *
  19353. * @param {Object} context - The context to set.
  19354. */
  19355. setContext( context ) {
  19356. this.context = context;
  19357. }
  19358. /**
  19359. * Returns the builder's current context.
  19360. *
  19361. * @return {Object} The builder's current context.
  19362. */
  19363. getContext() {
  19364. return this.context;
  19365. }
  19366. /**
  19367. * Gets a context used in shader construction that can be shared across different materials.
  19368. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  19369. *
  19370. * @return {Object} The builder's current context without material.
  19371. */
  19372. getSharedContext() {
  19373. ({ ...this.context });
  19374. return this.context;
  19375. }
  19376. /**
  19377. * Sets builder's cache.
  19378. *
  19379. * @param {NodeCache} cache - The cache to set.
  19380. */
  19381. setCache( cache ) {
  19382. this.cache = cache;
  19383. }
  19384. /**
  19385. * Returns the builder's current cache.
  19386. *
  19387. * @return {NodeCache} The builder's current cache.
  19388. */
  19389. getCache() {
  19390. return this.cache;
  19391. }
  19392. /**
  19393. * Returns a cache for the given node.
  19394. *
  19395. * @param {Node} Node - The node.
  19396. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  19397. * @return {NodeCache} The cache.
  19398. */
  19399. getCacheFromNode( node, parent = true ) {
  19400. const data = this.getDataFromNode( node );
  19401. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  19402. return data.cache;
  19403. }
  19404. /**
  19405. * Whether the requested feature is available or not.
  19406. *
  19407. * @abstract
  19408. * @param {String} name - The requested feature.
  19409. * @return {Boolean} Whether the requested feature is supported or not.
  19410. */
  19411. isAvailable( /*name*/ ) {
  19412. return false;
  19413. }
  19414. /**
  19415. * Returns the vertexIndex input variable as a native shader string.
  19416. *
  19417. * @abstract
  19418. * @return {String} The instanceIndex shader string.
  19419. */
  19420. getVertexIndex() {
  19421. console.warn( 'Abstract function.' );
  19422. }
  19423. /**
  19424. * Returns the instanceIndex input variable as a native shader string.
  19425. *
  19426. * @abstract
  19427. * @return {String} The instanceIndex shader string.
  19428. */
  19429. getInstanceIndex() {
  19430. console.warn( 'Abstract function.' );
  19431. }
  19432. /**
  19433. * Returns the drawIndex input variable as a native shader string.
  19434. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  19435. *
  19436. * @abstract
  19437. * @return {String} The drawIndex shader string.
  19438. */
  19439. getDrawIndex() {
  19440. console.warn( 'Abstract function.' );
  19441. }
  19442. /**
  19443. * Returns the frontFacing input variable as a native shader string.
  19444. *
  19445. * @abstract
  19446. * @return {String} The frontFacing shader string.
  19447. */
  19448. getFrontFacing() {
  19449. console.warn( 'Abstract function.' );
  19450. }
  19451. /**
  19452. * Returns the fragCoord input variable as a native shader string.
  19453. *
  19454. * @abstract
  19455. * @return {String} The fragCoord shader string.
  19456. */
  19457. getFragCoord() {
  19458. console.warn( 'Abstract function.' );
  19459. }
  19460. /**
  19461. * Whether to flip texture data along its vertical axis or not. WebGL needs
  19462. * this method evaluate to `true`, WebGPU to `false`.
  19463. *
  19464. * @abstract
  19465. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  19466. */
  19467. isFlipY() {
  19468. return false;
  19469. }
  19470. /**
  19471. * Calling this method increases the usage count for the given node by one.
  19472. *
  19473. * @param {Node} Node - The node to increase the usage count for.
  19474. * @return {Number} The updated usage count.
  19475. */
  19476. increaseUsage( node ) {
  19477. const nodeData = this.getDataFromNode( node );
  19478. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  19479. return nodeData.usageCount;
  19480. }
  19481. /**
  19482. * Generates a texture sample shader string for the given texture data.
  19483. *
  19484. * @abstract
  19485. * @param {Texture} texture - The texture.
  19486. * @param {String} textureProperty - The texture property name.
  19487. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  19488. * @return {String} The generated shader string.
  19489. */
  19490. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  19491. console.warn( 'Abstract function.' );
  19492. }
  19493. /**
  19494. * Generates a texture LOD shader string for the given texture data.
  19495. *
  19496. * @abstract
  19497. * @param {Texture} texture - The texture.
  19498. * @param {String} textureProperty - The texture property name.
  19499. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  19500. * @param {String} levelSnippet - Snippet defining the mip level.
  19501. * @return {String} The generated shader string.
  19502. */
  19503. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  19504. console.warn( 'Abstract function.' );
  19505. }
  19506. /**
  19507. * Generates the shader string for the given type and value.
  19508. *
  19509. * @param {String} type - The type.
  19510. * @param {Any?} [value=null] - The value.
  19511. * @return {String} The generated value as a shader string.
  19512. */
  19513. generateConst( type, value = null ) {
  19514. if ( value === null ) {
  19515. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  19516. else if ( type === 'bool' ) value = false;
  19517. else if ( type === 'color' ) value = new Color();
  19518. else if ( type === 'vec2' ) value = new Vector2();
  19519. else if ( type === 'vec3' ) value = new Vector3();
  19520. else if ( type === 'vec4' ) value = new Vector4();
  19521. }
  19522. if ( type === 'float' ) return toFloat( value );
  19523. if ( type === 'int' ) return `${ Math.round( value ) }`;
  19524. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  19525. if ( type === 'bool' ) return value ? 'true' : 'false';
  19526. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  19527. const typeLength = this.getTypeLength( type );
  19528. const componentType = this.getComponentType( type );
  19529. const generateConst = value => this.generateConst( componentType, value );
  19530. if ( typeLength === 2 ) {
  19531. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  19532. } else if ( typeLength === 3 ) {
  19533. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  19534. } else if ( typeLength === 4 ) {
  19535. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  19536. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  19537. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  19538. } else if ( typeLength > 4 ) {
  19539. return `${ this.getType( type ) }()`;
  19540. }
  19541. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  19542. }
  19543. /**
  19544. * It might be necessary to convert certain data types to different ones
  19545. * so this method can be used to hide the conversion.
  19546. *
  19547. * @param {String} type - The type.
  19548. * @return {String} The updated type.
  19549. */
  19550. getType( type ) {
  19551. if ( type === 'color' ) return 'vec3';
  19552. return type;
  19553. }
  19554. /**
  19555. * Whether the given attribute name is defined in the geometry or not.
  19556. *
  19557. * @param {String} name - The attribute name.
  19558. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  19559. */
  19560. hasGeometryAttribute( name ) {
  19561. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  19562. }
  19563. /**
  19564. * Returns a node attribute for the given name and type.
  19565. *
  19566. * @param {String} name - The attribute's name.
  19567. * @param {String} type - The attribute's type.
  19568. * @return {NodeAttribute} The node attribute.
  19569. */
  19570. getAttribute( name, type ) {
  19571. const attributes = this.attributes;
  19572. // find attribute
  19573. for ( const attribute of attributes ) {
  19574. if ( attribute.name === name ) {
  19575. return attribute;
  19576. }
  19577. }
  19578. // create a new if no exist
  19579. const attribute = new NodeAttribute( name, type );
  19580. attributes.push( attribute );
  19581. return attribute;
  19582. }
  19583. /**
  19584. * Returns for the given node and shader stage the property name for the shader.
  19585. *
  19586. * @param {Node} node - The node.
  19587. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  19588. * @return {String} The property name.
  19589. */
  19590. getPropertyName( node/*, shaderStage*/ ) {
  19591. return node.name;
  19592. }
  19593. /**
  19594. * Whether the given type is a vector type or not.
  19595. *
  19596. * @param {String} type - The type to check.
  19597. * @return {Boolean} Whether the given type is a vector type or not.
  19598. */
  19599. isVector( type ) {
  19600. return /vec\d/.test( type );
  19601. }
  19602. /**
  19603. * Whether the given type is a matrix type or not.
  19604. *
  19605. * @param {String} type - The type to check.
  19606. * @return {Boolean} Whether the given type is a matrix type or not.
  19607. */
  19608. isMatrix( type ) {
  19609. return /mat\d/.test( type );
  19610. }
  19611. /**
  19612. * Whether the given type is a reference type or not.
  19613. *
  19614. * @param {String} type - The type to check.
  19615. * @return {Boolean} Whether the given type is a reference type or not.
  19616. */
  19617. isReference( type ) {
  19618. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  19619. }
  19620. /**
  19621. * Whether the given texture needs a conversion to working color space.
  19622. *
  19623. * @abstract
  19624. * @param {Texture} texture - The texture to check.
  19625. * @return {Boolean} Whether a color space conversion is required or not.
  19626. */
  19627. needsToWorkingColorSpace( /*texture*/ ) {
  19628. return false;
  19629. }
  19630. /**
  19631. * Returns the component type of a given texture.
  19632. *
  19633. * @param {Texture} texture - The texture.
  19634. * @return {String} The component type.
  19635. */
  19636. getComponentTypeFromTexture( texture ) {
  19637. const type = texture.type;
  19638. if ( texture.isDataTexture ) {
  19639. if ( type === IntType ) return 'int';
  19640. if ( type === UnsignedIntType ) return 'uint';
  19641. }
  19642. return 'float';
  19643. }
  19644. /**
  19645. * Returns the element type for a given type.
  19646. *
  19647. * @param {String} type - The type.
  19648. * @return {String} The element type.
  19649. */
  19650. getElementType( type ) {
  19651. if ( type === 'mat2' ) return 'vec2';
  19652. if ( type === 'mat3' ) return 'vec3';
  19653. if ( type === 'mat4' ) return 'vec4';
  19654. return this.getComponentType( type );
  19655. }
  19656. /**
  19657. * Returns the component type for a given type.
  19658. *
  19659. * @param {String} type - The type.
  19660. * @return {String} The component type.
  19661. */
  19662. getComponentType( type ) {
  19663. type = this.getVectorType( type );
  19664. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  19665. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  19666. if ( componentType === null ) return null;
  19667. if ( componentType[ 1 ] === 'b' ) return 'bool';
  19668. if ( componentType[ 1 ] === 'i' ) return 'int';
  19669. if ( componentType[ 1 ] === 'u' ) return 'uint';
  19670. return 'float';
  19671. }
  19672. /**
  19673. * Returns the vector type for a given type.
  19674. *
  19675. * @param {String} type - The type.
  19676. * @return {String} The vector type.
  19677. */
  19678. getVectorType( type ) {
  19679. if ( type === 'color' ) return 'vec3';
  19680. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  19681. return type;
  19682. }
  19683. /**
  19684. * Returns the data type for the given the length and component type.
  19685. *
  19686. * @param {Number} length - The length.
  19687. * @param {String} [componentType='float'] - The component type.
  19688. * @return {String} The type.
  19689. */
  19690. getTypeFromLength( length, componentType = 'float' ) {
  19691. if ( length === 1 ) return componentType;
  19692. const baseType = getTypeFromLength( length );
  19693. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  19694. return prefix + baseType;
  19695. }
  19696. /**
  19697. * Returns the type for a given typed array.
  19698. *
  19699. * @param {TypedArray} type - The typed array.
  19700. * @return {String} The type.
  19701. */
  19702. getTypeFromArray( array ) {
  19703. return typeFromArray.get( array.constructor );
  19704. }
  19705. /**
  19706. * Returns the type for a given buffer attribute.
  19707. *
  19708. * @param {BufferAttribute} attribute - The buffer attribute.
  19709. * @return {String} The type.
  19710. */
  19711. getTypeFromAttribute( attribute ) {
  19712. let dataAttribute = attribute;
  19713. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  19714. const array = dataAttribute.array;
  19715. const itemSize = attribute.itemSize;
  19716. const normalized = attribute.normalized;
  19717. let arrayType;
  19718. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  19719. arrayType = this.getTypeFromArray( array );
  19720. }
  19721. return this.getTypeFromLength( itemSize, arrayType );
  19722. }
  19723. /**
  19724. * Returns the length for the given data type.
  19725. *
  19726. * @param {String} type - The data type.
  19727. * @return {Number} The length.
  19728. */
  19729. getTypeLength( type ) {
  19730. const vecType = this.getVectorType( type );
  19731. const vecNum = /vec([2-4])/.exec( vecType );
  19732. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  19733. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  19734. if ( /mat2/.test( type ) === true ) return 4;
  19735. if ( /mat3/.test( type ) === true ) return 9;
  19736. if ( /mat4/.test( type ) === true ) return 16;
  19737. return 0;
  19738. }
  19739. /**
  19740. * Returns the vector type for a given matrix type.
  19741. *
  19742. * @param {String} type - The matrix type.
  19743. * @return {String} The vector type.
  19744. */
  19745. getVectorFromMatrix( type ) {
  19746. return type.replace( 'mat', 'vec' );
  19747. }
  19748. /**
  19749. * For a given type this method changes the component type to the
  19750. * given value. E.g. `vec4` should be changed to the new component type
  19751. * `uint` which results in `uvec4`.
  19752. *
  19753. * @param {String} type - The type.
  19754. * @param {String} newComponentType - The new component type.
  19755. * @return {String} The new type.
  19756. */
  19757. changeComponentType( type, newComponentType ) {
  19758. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  19759. }
  19760. /**
  19761. * Returns the integer type pendant for the given type.
  19762. *
  19763. * @param {String} type - The type.
  19764. * @return {String} The integer type.
  19765. */
  19766. getIntegerType( type ) {
  19767. const componentType = this.getComponentType( type );
  19768. if ( componentType === 'int' || componentType === 'uint' ) return type;
  19769. return this.changeComponentType( type, 'int' );
  19770. }
  19771. /**
  19772. * Adds a stack node to the internal stack.
  19773. *
  19774. * @return {StackNode} The added stack node.
  19775. */
  19776. addStack() {
  19777. this.stack = stack( this.stack );
  19778. this.stacks.push( getCurrentStack() || this.stack );
  19779. setCurrentStack( this.stack );
  19780. return this.stack;
  19781. }
  19782. /**
  19783. * Removes the last stack node from the internal stack.
  19784. *
  19785. * @return {StackNode} The removed stack node.
  19786. */
  19787. removeStack() {
  19788. const lastStack = this.stack;
  19789. this.stack = lastStack.parent;
  19790. setCurrentStack( this.stacks.pop() );
  19791. return lastStack;
  19792. }
  19793. /**
  19794. * The builder maintains (cached) data for each node during the building process. This method
  19795. * can be used to get these data for a specific shader stage and cache.
  19796. *
  19797. * @param {Node} node - The node to get the data for.
  19798. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19799. * @param {NodeCache?} cache - An optional cache.
  19800. * @return {Object} The node data.
  19801. */
  19802. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  19803. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  19804. let nodeData = cache.getData( node );
  19805. if ( nodeData === undefined ) {
  19806. nodeData = {};
  19807. cache.setData( node, nodeData );
  19808. }
  19809. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  19810. return nodeData[ shaderStage ];
  19811. }
  19812. /**
  19813. * Returns the properties for the given node and shader stage.
  19814. *
  19815. * @param {Node} node - The node to get the properties for.
  19816. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  19817. * @return {Object} The node properties.
  19818. */
  19819. getNodeProperties( node, shaderStage = 'any' ) {
  19820. const nodeData = this.getDataFromNode( node, shaderStage );
  19821. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  19822. }
  19823. /**
  19824. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  19825. *
  19826. * @param {BufferAttributeNode} node - The buffer attribute node.
  19827. * @param {String} type - The node type.
  19828. * @return {NodeAttribute} The node attribute.
  19829. */
  19830. getBufferAttributeFromNode( node, type ) {
  19831. const nodeData = this.getDataFromNode( node );
  19832. let bufferAttribute = nodeData.bufferAttribute;
  19833. if ( bufferAttribute === undefined ) {
  19834. const index = this.uniforms.index ++;
  19835. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  19836. this.bufferAttributes.push( bufferAttribute );
  19837. nodeData.bufferAttribute = bufferAttribute;
  19838. }
  19839. return bufferAttribute;
  19840. }
  19841. /**
  19842. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  19843. *
  19844. * @param {OutputStructNode} node - The output struct node.
  19845. * @param {Array<String>} types - The output struct types.
  19846. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19847. * @return {StructTypeNode} The struct type attribute.
  19848. */
  19849. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  19850. const nodeData = this.getDataFromNode( node, shaderStage );
  19851. let structType = nodeData.structType;
  19852. if ( structType === undefined ) {
  19853. const index = this.structs.index ++;
  19854. structType = new StructTypeNode( 'StructType' + index, types );
  19855. this.structs[ shaderStage ].push( structType );
  19856. nodeData.structType = structType;
  19857. }
  19858. return structType;
  19859. }
  19860. /**
  19861. * Returns an instance of {@link NodeUniform} for the given uniform node.
  19862. *
  19863. * @param {UniformNode} node - The uniform node.
  19864. * @param {String} type - The uniform type.
  19865. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19866. * @param {String?} name - The name of the uniform.
  19867. * @return {NodeUniform} The node uniform.
  19868. */
  19869. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  19870. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  19871. let nodeUniform = nodeData.uniform;
  19872. if ( nodeUniform === undefined ) {
  19873. const index = this.uniforms.index ++;
  19874. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  19875. this.uniforms[ shaderStage ].push( nodeUniform );
  19876. nodeData.uniform = nodeUniform;
  19877. }
  19878. return nodeUniform;
  19879. }
  19880. /**
  19881. * Returns an instance of {@link NodeVar} for the given variable node.
  19882. *
  19883. * @param {VarNode} node - The variable node.
  19884. * @param {String?} name - The variable's name.
  19885. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  19886. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19887. * @return {NodeVar} The node variable.
  19888. */
  19889. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  19890. const nodeData = this.getDataFromNode( node, shaderStage );
  19891. let nodeVar = nodeData.variable;
  19892. if ( nodeVar === undefined ) {
  19893. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  19894. if ( name === null ) name = 'nodeVar' + vars.length;
  19895. nodeVar = new NodeVar( name, type );
  19896. vars.push( nodeVar );
  19897. nodeData.variable = nodeVar;
  19898. }
  19899. return nodeVar;
  19900. }
  19901. /**
  19902. * Returns an instance of {@link NodeVarying} for the given varying node.
  19903. *
  19904. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  19905. * @param {String?} name - The varying's name.
  19906. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  19907. * @return {NodeVar} The node varying.
  19908. */
  19909. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  19910. const nodeData = this.getDataFromNode( node, 'any' );
  19911. let nodeVarying = nodeData.varying;
  19912. if ( nodeVarying === undefined ) {
  19913. const varyings = this.varyings;
  19914. const index = varyings.length;
  19915. if ( name === null ) name = 'nodeVarying' + index;
  19916. nodeVarying = new NodeVarying( name, type );
  19917. varyings.push( nodeVarying );
  19918. nodeData.varying = nodeVarying;
  19919. }
  19920. return nodeVarying;
  19921. }
  19922. /**
  19923. * Returns an instance of {@link NodeCode} for the given code node.
  19924. *
  19925. * @param {CodeNode} node - The code node.
  19926. * @param {String} type - The node type.
  19927. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19928. * @return {NodeCode} The node code.
  19929. */
  19930. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  19931. const nodeData = this.getDataFromNode( node );
  19932. let nodeCode = nodeData.code;
  19933. if ( nodeCode === undefined ) {
  19934. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  19935. const index = codes.length;
  19936. nodeCode = new NodeCode( 'nodeCode' + index, type );
  19937. codes.push( nodeCode );
  19938. nodeData.code = nodeCode;
  19939. }
  19940. return nodeCode;
  19941. }
  19942. /**
  19943. * Adds a code flow based on the code-block hierarchy.
  19944. * This is used so that code-blocks like If,Else create their variables locally if the Node
  19945. * is only used inside one of these conditionals in the current shader stage.
  19946. *
  19947. * @param {Node} node - The node to add.
  19948. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  19949. */
  19950. addFlowCodeHierarchy( node, nodeBlock ) {
  19951. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  19952. let needsFlowCode = true;
  19953. let nodeBlockHierarchy = nodeBlock;
  19954. while ( nodeBlockHierarchy ) {
  19955. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  19956. needsFlowCode = false;
  19957. break;
  19958. }
  19959. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  19960. }
  19961. if ( needsFlowCode ) {
  19962. for ( const flowCode of flowCodes ) {
  19963. this.addLineFlowCode( flowCode );
  19964. }
  19965. }
  19966. }
  19967. /**
  19968. * Add a inline-code to the current flow code-block.
  19969. *
  19970. * @param {Node} node - The node to add.
  19971. * @param {String} code - The code to add.
  19972. * @param {Node} nodeBlock - Current ConditionalNode
  19973. */
  19974. addLineFlowCodeBlock( node, code, nodeBlock ) {
  19975. const nodeData = this.getDataFromNode( node );
  19976. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  19977. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  19978. flowCodes.push( code );
  19979. codeBlock.set( nodeBlock, true );
  19980. }
  19981. /**
  19982. * Add a inline-code to the current flow.
  19983. *
  19984. * @param {String} code - The code to add.
  19985. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  19986. * @return {NodeBuilder} A reference to this node builder.
  19987. */
  19988. addLineFlowCode( code, node = null ) {
  19989. if ( code === '' ) return this;
  19990. if ( node !== null && this.context.nodeBlock ) {
  19991. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  19992. }
  19993. code = this.tab + code;
  19994. if ( ! /;\s*$/.test( code ) ) {
  19995. code = code + ';\n';
  19996. }
  19997. this.flow.code += code;
  19998. return this;
  19999. }
  20000. /**
  20001. * Adds a code to the current code flow.
  20002. *
  20003. * @param {String} code - Shader code.
  20004. * @return {NodeBuilder} A reference to this node builder.
  20005. */
  20006. addFlowCode( code ) {
  20007. this.flow.code += code;
  20008. return this;
  20009. }
  20010. /**
  20011. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  20012. * Typically used in codes with If,Else.
  20013. *
  20014. * @return {NodeBuilder} A reference to this node builder.
  20015. */
  20016. addFlowTab() {
  20017. this.tab += '\t';
  20018. return this;
  20019. }
  20020. /**
  20021. * Removes a tab.
  20022. *
  20023. * @return {NodeBuilder} A reference to this node builder.
  20024. */
  20025. removeFlowTab() {
  20026. this.tab = this.tab.slice( 0, - 1 );
  20027. return this;
  20028. }
  20029. /**
  20030. * Gets the current flow data based on a Node.
  20031. *
  20032. * @param {Node} node - Node that the flow was started.
  20033. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20034. * @return {Object} The flow data.
  20035. */
  20036. getFlowData( node/*, shaderStage*/ ) {
  20037. return this.flowsData.get( node );
  20038. }
  20039. /**
  20040. * Executes the node flow based on a root node to generate the final shader code.
  20041. *
  20042. * @param {Node} node - The node to execute.
  20043. * @return {Object} The code flow.
  20044. */
  20045. flowNode( node ) {
  20046. const output = node.getNodeType( this );
  20047. const flowData = this.flowChildNode( node, output );
  20048. this.flowsData.set( node, flowData );
  20049. return flowData;
  20050. }
  20051. /**
  20052. * Returns the native shader operator name for a given generic name.
  20053. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  20054. *
  20055. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  20056. * @return {FunctionNode} The build function node.
  20057. */
  20058. buildFunctionNode( shaderNode ) {
  20059. const fn = new FunctionNode();
  20060. const previous = this.currentFunctionNode;
  20061. this.currentFunctionNode = fn;
  20062. fn.code = this.buildFunctionCode( shaderNode );
  20063. this.currentFunctionNode = previous;
  20064. return fn;
  20065. }
  20066. /**
  20067. * Generates a code flow based on a TSL function: Fn().
  20068. *
  20069. * @param {ShaderNodeInternal} node - A function code will be generated based on the input.
  20070. * @return {Object}
  20071. */
  20072. flowShaderNode( shaderNode ) {
  20073. const layout = shaderNode.layout;
  20074. const inputs = {
  20075. [ Symbol.iterator ]() {
  20076. let index = 0;
  20077. const values = Object.values( this );
  20078. return {
  20079. next: () => ( {
  20080. value: values[ index ],
  20081. done: index ++ >= values.length
  20082. } )
  20083. };
  20084. }
  20085. };
  20086. for ( const input of layout.inputs ) {
  20087. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  20088. }
  20089. //
  20090. shaderNode.layout = null;
  20091. const callNode = shaderNode.call( inputs );
  20092. const flowData = this.flowStagesNode( callNode, layout.type );
  20093. shaderNode.layout = layout;
  20094. return flowData;
  20095. }
  20096. /**
  20097. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  20098. *
  20099. * @param {Node} node - The node to execute.
  20100. * @param {String?} output - Expected output type. For example 'vec3'.
  20101. * @return {Object}
  20102. */
  20103. flowStagesNode( node, output = null ) {
  20104. const previousFlow = this.flow;
  20105. const previousVars = this.vars;
  20106. const previousCache = this.cache;
  20107. const previousBuildStage = this.buildStage;
  20108. const previousStack = this.stack;
  20109. const flow = {
  20110. code: ''
  20111. };
  20112. this.flow = flow;
  20113. this.vars = {};
  20114. this.cache = new NodeCache();
  20115. this.stack = stack();
  20116. for ( const buildStage of defaultBuildStages ) {
  20117. this.setBuildStage( buildStage );
  20118. flow.result = node.build( this, output );
  20119. }
  20120. flow.vars = this.getVars( this.shaderStage );
  20121. this.flow = previousFlow;
  20122. this.vars = previousVars;
  20123. this.cache = previousCache;
  20124. this.stack = previousStack;
  20125. this.setBuildStage( previousBuildStage );
  20126. return flow;
  20127. }
  20128. /**
  20129. * Returns the native shader operator name for a given generic name.
  20130. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  20131. *
  20132. * @abstract
  20133. * @param {String} op - The operator name to resolve.
  20134. * @return {String} The resolved operator name.
  20135. */
  20136. getFunctionOperator( /* op */ ) {
  20137. return null;
  20138. }
  20139. /**
  20140. * Generates a code flow based on a child Node.
  20141. *
  20142. * @param {Node} node - The node to execute.
  20143. * @param {String?} output - Expected output type. For example 'vec3'.
  20144. * @return {Object} The code flow.
  20145. */
  20146. flowChildNode( node, output = null ) {
  20147. const previousFlow = this.flow;
  20148. const flow = {
  20149. code: ''
  20150. };
  20151. this.flow = flow;
  20152. flow.result = node.build( this, output );
  20153. this.flow = previousFlow;
  20154. return flow;
  20155. }
  20156. /**
  20157. * Executes a flow of code in a different stage.
  20158. *
  20159. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  20160. * return the value in fragment-stage even if it is being executed in an input fragment.
  20161. *
  20162. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20163. * @param {Node} node - The node to execute.
  20164. * @param {String?} output - Expected output type. For example 'vec3'.
  20165. * @param {String?} propertyName - The property name to assign the result.
  20166. * @return {Object}
  20167. */
  20168. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  20169. const previousShaderStage = this.shaderStage;
  20170. this.setShaderStage( shaderStage );
  20171. const flowData = this.flowChildNode( node, output );
  20172. if ( propertyName !== null ) {
  20173. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  20174. }
  20175. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  20176. this.setShaderStage( previousShaderStage );
  20177. return flowData;
  20178. }
  20179. /**
  20180. * Returns an array holding all node attributes of this node builder.
  20181. *
  20182. * @return {Array<NodeAttribute>} The node attributes of this builder.
  20183. */
  20184. getAttributesArray() {
  20185. return this.attributes.concat( this.bufferAttributes );
  20186. }
  20187. /**
  20188. * Returns the attribute definitions as a shader string for the given shader stage.
  20189. *
  20190. * @abstract
  20191. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20192. * @return {String} The attribute code section.
  20193. */
  20194. getAttributes( /*shaderStage*/ ) {
  20195. console.warn( 'Abstract function.' );
  20196. }
  20197. /**
  20198. * Returns the varying definitions as a shader string for the given shader stage.
  20199. *
  20200. * @abstract
  20201. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20202. * @return {String} The varying code section.
  20203. */
  20204. getVaryings( /*shaderStage*/ ) {
  20205. console.warn( 'Abstract function.' );
  20206. }
  20207. /**
  20208. * Returns a single variable definition as a shader string for the given variable type and name.
  20209. *
  20210. * @param {String} type - The variable's type.
  20211. * @param {String} name - The variable's name.
  20212. * @return {String} The shader string.
  20213. */
  20214. getVar( type, name ) {
  20215. return `${ this.getType( type ) } ${ name }`;
  20216. }
  20217. /**
  20218. * Returns the variable definitions as a shader string for the given shader stage.
  20219. *
  20220. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20221. * @return {String} The variable code section.
  20222. */
  20223. getVars( shaderStage ) {
  20224. let snippet = '';
  20225. const vars = this.vars[ shaderStage ];
  20226. if ( vars !== undefined ) {
  20227. for ( const variable of vars ) {
  20228. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  20229. }
  20230. }
  20231. return snippet;
  20232. }
  20233. /**
  20234. * Returns the uniform definitions as a shader string for the given shader stage.
  20235. *
  20236. * @abstract
  20237. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20238. * @return {String} The uniform code section.
  20239. */
  20240. getUniforms( /*shaderStage*/ ) {
  20241. console.warn( 'Abstract function.' );
  20242. }
  20243. /**
  20244. * Returns the native code definitions as a shader string for the given shader stage.
  20245. *
  20246. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20247. * @return {String} The native code section.
  20248. */
  20249. getCodes( shaderStage ) {
  20250. const codes = this.codes[ shaderStage ];
  20251. let code = '';
  20252. if ( codes !== undefined ) {
  20253. for ( const nodeCode of codes ) {
  20254. code += nodeCode.code + '\n';
  20255. }
  20256. }
  20257. return code;
  20258. }
  20259. /**
  20260. * Returns the hash of this node builder.
  20261. *
  20262. * @return {String} The hash.
  20263. */
  20264. getHash() {
  20265. return this.vertexShader + this.fragmentShader + this.computeShader;
  20266. }
  20267. /**
  20268. * Sets the current shader stage.
  20269. *
  20270. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  20271. */
  20272. setShaderStage( shaderStage ) {
  20273. this.shaderStage = shaderStage;
  20274. }
  20275. /**
  20276. * Returns the current shader stage.
  20277. *
  20278. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  20279. */
  20280. getShaderStage() {
  20281. return this.shaderStage;
  20282. }
  20283. /**
  20284. * Sets the current build stage.
  20285. *
  20286. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  20287. */
  20288. setBuildStage( buildStage ) {
  20289. this.buildStage = buildStage;
  20290. }
  20291. /**
  20292. * Returns the current build stage.
  20293. *
  20294. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  20295. */
  20296. getBuildStage() {
  20297. return this.buildStage;
  20298. }
  20299. /**
  20300. * Controls the code build of the shader stages.
  20301. *
  20302. * @abstract
  20303. */
  20304. buildCode() {
  20305. console.warn( 'Abstract function.' );
  20306. }
  20307. /**
  20308. * Central build method which controls the build for the given object.
  20309. *
  20310. * @return {NodeBuilder} A reference to this node builder.
  20311. */
  20312. build() {
  20313. const { object, material, renderer } = this;
  20314. if ( material !== null ) {
  20315. let nodeMaterial = renderer.library.fromMaterial( material );
  20316. if ( nodeMaterial === null ) {
  20317. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  20318. nodeMaterial = new NodeMaterial();
  20319. }
  20320. nodeMaterial.build( this );
  20321. } else {
  20322. this.addFlow( 'compute', object );
  20323. }
  20324. // setup() -> stage 1: create possible new nodes and returns an output reference node
  20325. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  20326. // generate() -> stage 3: generate shader
  20327. for ( const buildStage of defaultBuildStages ) {
  20328. this.setBuildStage( buildStage );
  20329. if ( this.context.vertex && this.context.vertex.isNode ) {
  20330. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  20331. }
  20332. for ( const shaderStage of shaderStages ) {
  20333. this.setShaderStage( shaderStage );
  20334. const flowNodes = this.flowNodes[ shaderStage ];
  20335. for ( const node of flowNodes ) {
  20336. if ( buildStage === 'generate' ) {
  20337. this.flowNode( node );
  20338. } else {
  20339. node.build( this );
  20340. }
  20341. }
  20342. }
  20343. }
  20344. this.setBuildStage( null );
  20345. this.setShaderStage( null );
  20346. // stage 4: build code for a specific output
  20347. this.buildCode();
  20348. this.buildUpdateNodes();
  20349. return this;
  20350. }
  20351. /**
  20352. * Returns a uniform representation which is later used for UBO generation and rendering.
  20353. *
  20354. * @param {NodeUniform} uniformNode - The uniform node.
  20355. * @param {String} type - The requested type.
  20356. * @return {Uniform} The uniform.
  20357. */
  20358. getNodeUniform( uniformNode, type ) {
  20359. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  20360. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  20361. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  20362. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  20363. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  20364. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  20365. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  20366. throw new Error( `Uniform "${type}" not declared.` );
  20367. }
  20368. /**
  20369. * Formats the given shader snippet from a given type into another one. E.g.
  20370. * this method might be used to convert a simple float string `"1.0"` into a
  20371. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  20372. *
  20373. * @param {String} snippet - The shader snippet.
  20374. * @param {String} fromType - The source type.
  20375. * @param {String} toType - The target type.
  20376. * @return {String} The updated shader string.
  20377. */
  20378. format( snippet, fromType, toType ) {
  20379. fromType = this.getVectorType( fromType );
  20380. toType = this.getVectorType( toType );
  20381. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  20382. return snippet;
  20383. }
  20384. const fromTypeLength = this.getTypeLength( fromType );
  20385. const toTypeLength = this.getTypeLength( toType );
  20386. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  20387. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  20388. }
  20389. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  20390. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  20391. }
  20392. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  20393. // @TODO: ignore for now
  20394. return snippet;
  20395. }
  20396. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  20397. // @TODO: ignore for now
  20398. return snippet;
  20399. }
  20400. if ( fromTypeLength === toTypeLength ) {
  20401. return `${ this.getType( toType ) }( ${ snippet } )`;
  20402. }
  20403. if ( fromTypeLength > toTypeLength ) {
  20404. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  20405. }
  20406. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  20407. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  20408. }
  20409. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  20410. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  20411. }
  20412. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  20413. // convert a number value to vector type, e.g:
  20414. // vec3( 1u ) -> vec3( float( 1u ) )
  20415. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  20416. }
  20417. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  20418. }
  20419. /**
  20420. * Returns a signature with the engine's current revision.
  20421. *
  20422. * @return {String} The signature.
  20423. */
  20424. getSignature() {
  20425. return `// Three.js r${ REVISION } - Node System\n`;
  20426. }
  20427. // deprecated
  20428. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  20429. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  20430. }
  20431. }
  20432. /**
  20433. * Management class for updating nodes. The module tracks metrics like
  20434. * the elapsed time, delta time, the render and frame ID to correctly
  20435. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  20436. * and {@link Node#updateAfter} depending on the node's configuration.
  20437. */
  20438. class NodeFrame {
  20439. /**
  20440. * Constructs a new node fame.
  20441. */
  20442. constructor() {
  20443. /**
  20444. * The elapsed time in seconds.
  20445. *
  20446. * @type {Number}
  20447. * @default 0
  20448. */
  20449. this.time = 0;
  20450. /**
  20451. * The delta time in seconds.
  20452. *
  20453. * @type {Number}
  20454. * @default 0
  20455. */
  20456. this.deltaTime = 0;
  20457. /**
  20458. * The frame ID.
  20459. *
  20460. * @type {Number}
  20461. * @default 0
  20462. */
  20463. this.frameId = 0;
  20464. /**
  20465. * The render ID.
  20466. *
  20467. * @type {Number}
  20468. * @default 0
  20469. */
  20470. this.renderId = 0;
  20471. /**
  20472. * Used to control the {@link Node#update} call.
  20473. *
  20474. * @type {WeakMap}
  20475. */
  20476. this.updateMap = new WeakMap();
  20477. /**
  20478. * Used to control the {@link Node#updateBefore} call.
  20479. *
  20480. * @type {WeakMap}
  20481. */
  20482. this.updateBeforeMap = new WeakMap();
  20483. /**
  20484. * Used to control the {@link Node#updateAfter} call.
  20485. *
  20486. * @type {WeakMap}
  20487. */
  20488. this.updateAfterMap = new WeakMap();
  20489. /**
  20490. * A reference to the current renderer.
  20491. *
  20492. * @type {Renderer?}
  20493. * @default null
  20494. */
  20495. this.renderer = null;
  20496. /**
  20497. * A reference to the current material.
  20498. *
  20499. * @type {Material?}
  20500. * @default null
  20501. */
  20502. this.material = null;
  20503. /**
  20504. * A reference to the current camera.
  20505. *
  20506. * @type {Camera?}
  20507. * @default null
  20508. */
  20509. this.camera = null;
  20510. /**
  20511. * A reference to the current 3D object.
  20512. *
  20513. * @type {Object3D?}
  20514. * @default null
  20515. */
  20516. this.object = null;
  20517. /**
  20518. * A reference to the current scene.
  20519. *
  20520. * @type {Scene?}
  20521. * @default null
  20522. */
  20523. this.scene = null;
  20524. }
  20525. /**
  20526. * Returns a dictionary for a given node and update map which
  20527. * is used to correctly call node update methods per frame or render.
  20528. *
  20529. * @private
  20530. * @param {WeakMap} referenceMap - The reference weak map.
  20531. * @param {Node} nodeRef - The reference to the current node.
  20532. * @return {Object<String,WeakMap>} The dictionary.
  20533. */
  20534. _getMaps( referenceMap, nodeRef ) {
  20535. let maps = referenceMap.get( nodeRef );
  20536. if ( maps === undefined ) {
  20537. maps = {
  20538. renderMap: new WeakMap(),
  20539. frameMap: new WeakMap()
  20540. };
  20541. referenceMap.set( nodeRef, maps );
  20542. }
  20543. return maps;
  20544. }
  20545. /**
  20546. * This method executes the {@link Node#updateBefore} for the given node.
  20547. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  20548. * is only executed once per frame, render or object depending on the update
  20549. * type.
  20550. *
  20551. * @param {Node} node - The node that should be updated.
  20552. */
  20553. updateBeforeNode( node ) {
  20554. const updateType = node.getUpdateBeforeType();
  20555. const reference = node.updateReference( this );
  20556. if ( updateType === NodeUpdateType.FRAME ) {
  20557. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  20558. if ( frameMap.get( reference ) !== this.frameId ) {
  20559. if ( node.updateBefore( this ) !== false ) {
  20560. frameMap.set( reference, this.frameId );
  20561. }
  20562. }
  20563. } else if ( updateType === NodeUpdateType.RENDER ) {
  20564. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  20565. if ( renderMap.get( reference ) !== this.renderId ) {
  20566. if ( node.updateBefore( this ) !== false ) {
  20567. renderMap.set( reference, this.renderId );
  20568. }
  20569. }
  20570. } else if ( updateType === NodeUpdateType.OBJECT ) {
  20571. node.updateBefore( this );
  20572. }
  20573. }
  20574. /**
  20575. * This method executes the {@link Node#updateAfter} for the given node.
  20576. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  20577. * is only executed once per frame, render or object depending on the update
  20578. * type.
  20579. *
  20580. * @param {Node} node - The node that should be updated.
  20581. */
  20582. updateAfterNode( node ) {
  20583. const updateType = node.getUpdateAfterType();
  20584. const reference = node.updateReference( this );
  20585. if ( updateType === NodeUpdateType.FRAME ) {
  20586. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  20587. if ( frameMap.get( reference ) !== this.frameId ) {
  20588. if ( node.updateAfter( this ) !== false ) {
  20589. frameMap.set( reference, this.frameId );
  20590. }
  20591. }
  20592. } else if ( updateType === NodeUpdateType.RENDER ) {
  20593. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  20594. if ( renderMap.get( reference ) !== this.renderId ) {
  20595. if ( node.updateAfter( this ) !== false ) {
  20596. renderMap.set( reference, this.renderId );
  20597. }
  20598. }
  20599. } else if ( updateType === NodeUpdateType.OBJECT ) {
  20600. node.updateAfter( this );
  20601. }
  20602. }
  20603. /**
  20604. * This method executes the {@link Node#update} for the given node.
  20605. * It makes sure {@link Node#updateType} is honored meaning the update
  20606. * is only executed once per frame, render or object depending on the update
  20607. * type.
  20608. *
  20609. * @param {Node} node - The node that should be updated.
  20610. */
  20611. updateNode( node ) {
  20612. const updateType = node.getUpdateType();
  20613. const reference = node.updateReference( this );
  20614. if ( updateType === NodeUpdateType.FRAME ) {
  20615. const { frameMap } = this._getMaps( this.updateMap, reference );
  20616. if ( frameMap.get( reference ) !== this.frameId ) {
  20617. if ( node.update( this ) !== false ) {
  20618. frameMap.set( reference, this.frameId );
  20619. }
  20620. }
  20621. } else if ( updateType === NodeUpdateType.RENDER ) {
  20622. const { renderMap } = this._getMaps( this.updateMap, reference );
  20623. if ( renderMap.get( reference ) !== this.renderId ) {
  20624. if ( node.update( this ) !== false ) {
  20625. renderMap.set( reference, this.renderId );
  20626. }
  20627. }
  20628. } else if ( updateType === NodeUpdateType.OBJECT ) {
  20629. node.update( this );
  20630. }
  20631. }
  20632. /**
  20633. * Updates the internal state of the node frame. This method is
  20634. * called by the renderer in its internal animation loop.
  20635. */
  20636. update() {
  20637. this.frameId ++;
  20638. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  20639. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  20640. this.lastTime = performance.now();
  20641. this.time += this.deltaTime;
  20642. }
  20643. }
  20644. /**
  20645. * Describes the input of a {@link NodeFunction}.
  20646. */
  20647. class NodeFunctionInput {
  20648. /**
  20649. * Constructs a new node function input.
  20650. *
  20651. * @param {String} type - The input type.
  20652. * @param {String} name - The input name.
  20653. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  20654. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  20655. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  20656. */
  20657. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  20658. /**
  20659. * The input type.
  20660. *
  20661. * @type {String}
  20662. */
  20663. this.type = type;
  20664. /**
  20665. * The input name.
  20666. *
  20667. * @type {String}
  20668. */
  20669. this.name = name;
  20670. /**
  20671. * If the input is an Array, count will be the length.
  20672. *
  20673. * @type {Number?}
  20674. * @default null
  20675. */
  20676. this.count = count;
  20677. /**
  20678. *The parameter qualifier (only relevant for GLSL).
  20679. *
  20680. * @type {('in'|'out'|'inout')}
  20681. * @default ''
  20682. */
  20683. this.qualifier = qualifier;
  20684. /**
  20685. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  20686. *
  20687. * @type {Boolean}
  20688. * @default false
  20689. */
  20690. this.isConst = isConst;
  20691. }
  20692. }
  20693. NodeFunctionInput.isNodeFunctionInput = true;
  20694. class DirectionalLightNode extends AnalyticLightNode {
  20695. static get type() {
  20696. return 'DirectionalLightNode';
  20697. }
  20698. constructor( light = null ) {
  20699. super( light );
  20700. }
  20701. setup( builder ) {
  20702. super.setup( builder );
  20703. const lightingModel = builder.context.lightingModel;
  20704. const lightColor = this.colorNode;
  20705. const lightDirection = lightTargetDirection( this.light );
  20706. const reflectedLight = builder.context.reflectedLight;
  20707. lightingModel.direct( {
  20708. lightDirection,
  20709. lightColor,
  20710. reflectedLight
  20711. }, builder.stack, builder );
  20712. }
  20713. }
  20714. const _matrix41 = /*@__PURE__*/ new Matrix4();
  20715. const _matrix42 = /*@__PURE__*/ new Matrix4();
  20716. let ltcLib = null;
  20717. class RectAreaLightNode extends AnalyticLightNode {
  20718. static get type() {
  20719. return 'RectAreaLightNode';
  20720. }
  20721. constructor( light = null ) {
  20722. super( light );
  20723. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  20724. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  20725. this.updateType = NodeUpdateType.RENDER;
  20726. }
  20727. update( frame ) {
  20728. super.update( frame );
  20729. const { light } = this;
  20730. const viewMatrix = frame.camera.matrixWorldInverse;
  20731. _matrix42.identity();
  20732. _matrix41.copy( light.matrixWorld );
  20733. _matrix41.premultiply( viewMatrix );
  20734. _matrix42.extractRotation( _matrix41 );
  20735. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  20736. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  20737. this.halfWidth.value.applyMatrix4( _matrix42 );
  20738. this.halfHeight.value.applyMatrix4( _matrix42 );
  20739. }
  20740. setup( builder ) {
  20741. super.setup( builder );
  20742. let ltc_1, ltc_2;
  20743. if ( builder.isAvailable( 'float32Filterable' ) ) {
  20744. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  20745. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  20746. } else {
  20747. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  20748. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  20749. }
  20750. const { colorNode, light } = this;
  20751. const lightingModel = builder.context.lightingModel;
  20752. const lightPosition = lightViewPosition( light );
  20753. const reflectedLight = builder.context.reflectedLight;
  20754. lightingModel.directRectArea( {
  20755. lightColor: colorNode,
  20756. lightPosition,
  20757. halfWidth: this.halfWidth,
  20758. halfHeight: this.halfHeight,
  20759. reflectedLight,
  20760. ltc_1,
  20761. ltc_2
  20762. }, builder.stack, builder );
  20763. }
  20764. static setLTC( ltc ) {
  20765. ltcLib = ltc;
  20766. }
  20767. }
  20768. class SpotLightNode extends AnalyticLightNode {
  20769. static get type() {
  20770. return 'SpotLightNode';
  20771. }
  20772. constructor( light = null ) {
  20773. super( light );
  20774. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  20775. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  20776. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  20777. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  20778. }
  20779. update( frame ) {
  20780. super.update( frame );
  20781. const { light } = this;
  20782. this.coneCosNode.value = Math.cos( light.angle );
  20783. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  20784. this.cutoffDistanceNode.value = light.distance;
  20785. this.decayExponentNode.value = light.decay;
  20786. }
  20787. getSpotAttenuation( angleCosine ) {
  20788. const { coneCosNode, penumbraCosNode } = this;
  20789. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  20790. }
  20791. setup( builder ) {
  20792. super.setup( builder );
  20793. const lightingModel = builder.context.lightingModel;
  20794. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  20795. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  20796. const lightDirection = lVector.normalize();
  20797. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  20798. const spotAttenuation = this.getSpotAttenuation( angleCos );
  20799. const lightDistance = lVector.length();
  20800. const lightAttenuation = getDistanceAttenuation( {
  20801. lightDistance,
  20802. cutoffDistance: cutoffDistanceNode,
  20803. decayExponent: decayExponentNode
  20804. } );
  20805. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  20806. if ( light.map ) {
  20807. const spotLightCoord = lightProjectionUV( light );
  20808. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  20809. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  20810. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  20811. }
  20812. const reflectedLight = builder.context.reflectedLight;
  20813. lightingModel.direct( {
  20814. lightDirection,
  20815. lightColor,
  20816. reflectedLight
  20817. }, builder.stack, builder );
  20818. }
  20819. }
  20820. class IESSpotLightNode extends SpotLightNode {
  20821. static get type() {
  20822. return 'IESSpotLightNode';
  20823. }
  20824. getSpotAttenuation( angleCosine ) {
  20825. const iesMap = this.light.iesMap;
  20826. let spotAttenuation = null;
  20827. if ( iesMap && iesMap.isTexture === true ) {
  20828. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  20829. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  20830. } else {
  20831. spotAttenuation = super.getSpotAttenuation( angleCosine );
  20832. }
  20833. return spotAttenuation;
  20834. }
  20835. }
  20836. class AmbientLightNode extends AnalyticLightNode {
  20837. static get type() {
  20838. return 'AmbientLightNode';
  20839. }
  20840. constructor( light = null ) {
  20841. super( light );
  20842. }
  20843. setup( { context } ) {
  20844. context.irradiance.addAssign( this.colorNode );
  20845. }
  20846. }
  20847. class HemisphereLightNode extends AnalyticLightNode {
  20848. static get type() {
  20849. return 'HemisphereLightNode';
  20850. }
  20851. constructor( light = null ) {
  20852. super( light );
  20853. this.lightPositionNode = lightPosition( light );
  20854. this.lightDirectionNode = this.lightPositionNode.normalize();
  20855. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  20856. }
  20857. update( frame ) {
  20858. const { light } = this;
  20859. super.update( frame );
  20860. this.lightPositionNode.object3d = light;
  20861. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  20862. }
  20863. setup( builder ) {
  20864. const { colorNode, groundColorNode, lightDirectionNode } = this;
  20865. const dotNL = normalView.dot( lightDirectionNode );
  20866. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  20867. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  20868. builder.context.irradiance.addAssign( irradiance );
  20869. }
  20870. }
  20871. class LightProbeNode extends AnalyticLightNode {
  20872. static get type() {
  20873. return 'LightProbeNode';
  20874. }
  20875. constructor( light = null ) {
  20876. super( light );
  20877. const array = [];
  20878. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  20879. this.lightProbe = uniformArray( array );
  20880. }
  20881. update( frame ) {
  20882. const { light } = this;
  20883. super.update( frame );
  20884. //
  20885. for ( let i = 0; i < 9; i ++ ) {
  20886. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  20887. }
  20888. }
  20889. setup( builder ) {
  20890. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  20891. builder.context.irradiance.addAssign( irradiance );
  20892. }
  20893. }
  20894. /**
  20895. * Base class for node parsers. A derived parser must be implemented
  20896. * for each supported native shader language.
  20897. */
  20898. class NodeParser {
  20899. /**
  20900. * The method parses the given native code an returns a node function.
  20901. *
  20902. * @abstract
  20903. * @param {String} source - The native shader code.
  20904. * @return {NodeFunction} A node function.
  20905. */
  20906. parseFunction( /*source*/ ) {
  20907. console.warn( 'Abstract function.' );
  20908. }
  20909. }
  20910. /**
  20911. * Base class for node functions. A derived module must be implemented
  20912. * for each supported native shader language. Similar to other `Node*` modules,
  20913. * this class is only relevant during the building process and not used
  20914. * in user-level code.
  20915. */
  20916. class NodeFunction {
  20917. /**
  20918. * Constructs a new node function.
  20919. *
  20920. * @param {String} type - The node type. This type is the return type of the node function.
  20921. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  20922. * @param {String} [name=''] - The function's name.
  20923. * @param {String} [precision=''] - The precision qualifier.
  20924. */
  20925. constructor( type, inputs, name = '', precision = '' ) {
  20926. /**
  20927. * The node type. This type is the return type of the node function.
  20928. *
  20929. * @type {String}
  20930. */
  20931. this.type = type;
  20932. /**
  20933. * The function's inputs.
  20934. *
  20935. * @type {Array<NodeFunctionInput>}
  20936. */
  20937. this.inputs = inputs;
  20938. /**
  20939. * The name of the uniform.
  20940. *
  20941. * @type {String}
  20942. * @default ''
  20943. */
  20944. this.name = name;
  20945. /**
  20946. * The precision qualifier.
  20947. *
  20948. * @type {String}
  20949. * @default ''
  20950. */
  20951. this.precision = precision;
  20952. }
  20953. /**
  20954. * This method returns the native code of the node function.
  20955. *
  20956. * @abstract
  20957. * @param {String} name - The function's name.
  20958. * @return {String} A shader code.
  20959. */
  20960. getCode( /*name = this.name*/ ) {
  20961. console.warn( 'Abstract function.' );
  20962. }
  20963. }
  20964. NodeFunction.isNodeFunction = true;
  20965. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  20966. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  20967. const pragmaMain = '#pragma main';
  20968. const parse$1 = ( source ) => {
  20969. source = source.trim();
  20970. const pragmaMainIndex = source.indexOf( pragmaMain );
  20971. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  20972. const declaration = mainCode.match( declarationRegexp$1 );
  20973. if ( declaration !== null && declaration.length === 5 ) {
  20974. // tokenizer
  20975. const inputsCode = declaration[ 4 ];
  20976. const propsMatches = [];
  20977. let nameMatch = null;
  20978. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  20979. propsMatches.push( nameMatch );
  20980. }
  20981. // parser
  20982. const inputs = [];
  20983. let i = 0;
  20984. while ( i < propsMatches.length ) {
  20985. const isConst = propsMatches[ i ][ 0 ] === 'const';
  20986. if ( isConst === true ) {
  20987. i ++;
  20988. }
  20989. let qualifier = propsMatches[ i ][ 0 ];
  20990. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  20991. i ++;
  20992. } else {
  20993. qualifier = '';
  20994. }
  20995. const type = propsMatches[ i ++ ][ 0 ];
  20996. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  20997. if ( Number.isNaN( count ) === false ) i ++;
  20998. else count = null;
  20999. const name = propsMatches[ i ++ ][ 0 ];
  21000. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  21001. }
  21002. //
  21003. const blockCode = mainCode.substring( declaration[ 0 ].length );
  21004. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  21005. const type = declaration[ 2 ];
  21006. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  21007. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  21008. return {
  21009. type,
  21010. inputs,
  21011. name,
  21012. precision,
  21013. inputsCode,
  21014. blockCode,
  21015. headerCode
  21016. };
  21017. } else {
  21018. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  21019. }
  21020. };
  21021. /**
  21022. * This class represents a GLSL node function.
  21023. *
  21024. * @augments NodeFunction
  21025. */
  21026. class GLSLNodeFunction extends NodeFunction {
  21027. /**
  21028. * Constructs a new GLSL node function.
  21029. *
  21030. * @param {String} source - The GLSL source.
  21031. */
  21032. constructor( source ) {
  21033. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  21034. super( type, inputs, name, precision );
  21035. this.inputsCode = inputsCode;
  21036. this.blockCode = blockCode;
  21037. this.headerCode = headerCode;
  21038. }
  21039. /**
  21040. * This method returns the GLSL code of the node function.
  21041. *
  21042. * @param {String} [name=this.name] - The function's name.
  21043. * @return {String} The shader code.
  21044. */
  21045. getCode( name = this.name ) {
  21046. let code;
  21047. const blockCode = this.blockCode;
  21048. if ( blockCode !== '' ) {
  21049. const { type, inputsCode, headerCode, precision } = this;
  21050. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  21051. if ( precision !== '' ) {
  21052. declarationCode = `${ precision } ${ declarationCode }`;
  21053. }
  21054. code = headerCode + declarationCode + blockCode;
  21055. } else {
  21056. // interface function
  21057. code = '';
  21058. }
  21059. return code;
  21060. }
  21061. }
  21062. /**
  21063. * A GLSL node parser.
  21064. *
  21065. * @augments NodeParser
  21066. */
  21067. class GLSLNodeParser extends NodeParser {
  21068. /**
  21069. * The method parses the given GLSL code an returns a node function.
  21070. *
  21071. * @param {String} source - The GLSL code.
  21072. * @return {GLSLNodeFunction} A node function.
  21073. */
  21074. parseFunction( source ) {
  21075. return new GLSLNodeFunction( source );
  21076. }
  21077. }
  21078. const outputNodeMap = new WeakMap();
  21079. class Nodes extends DataMap {
  21080. constructor( renderer, backend ) {
  21081. super();
  21082. this.renderer = renderer;
  21083. this.backend = backend;
  21084. this.nodeFrame = new NodeFrame();
  21085. this.nodeBuilderCache = new Map();
  21086. this.callHashCache = new ChainMap();
  21087. this.groupsData = new ChainMap();
  21088. }
  21089. updateGroup( nodeUniformsGroup ) {
  21090. const groupNode = nodeUniformsGroup.groupNode;
  21091. const name = groupNode.name;
  21092. // objectGroup is every updated
  21093. if ( name === objectGroup.name ) return true;
  21094. // renderGroup is updated once per render/compute call
  21095. if ( name === renderGroup.name ) {
  21096. const uniformsGroupData = this.get( nodeUniformsGroup );
  21097. const renderId = this.nodeFrame.renderId;
  21098. if ( uniformsGroupData.renderId !== renderId ) {
  21099. uniformsGroupData.renderId = renderId;
  21100. return true;
  21101. }
  21102. return false;
  21103. }
  21104. // frameGroup is updated once per frame
  21105. if ( name === frameGroup.name ) {
  21106. const uniformsGroupData = this.get( nodeUniformsGroup );
  21107. const frameId = this.nodeFrame.frameId;
  21108. if ( uniformsGroupData.frameId !== frameId ) {
  21109. uniformsGroupData.frameId = frameId;
  21110. return true;
  21111. }
  21112. return false;
  21113. }
  21114. // other groups are updated just when groupNode.needsUpdate is true
  21115. const groupChain = [ groupNode, nodeUniformsGroup ];
  21116. let groupData = this.groupsData.get( groupChain );
  21117. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  21118. if ( groupData.version !== groupNode.version ) {
  21119. groupData.version = groupNode.version;
  21120. return true;
  21121. }
  21122. return false;
  21123. }
  21124. getForRenderCacheKey( renderObject ) {
  21125. return renderObject.initialCacheKey;
  21126. }
  21127. getForRender( renderObject ) {
  21128. const renderObjectData = this.get( renderObject );
  21129. let nodeBuilderState = renderObjectData.nodeBuilderState;
  21130. if ( nodeBuilderState === undefined ) {
  21131. const { nodeBuilderCache } = this;
  21132. const cacheKey = this.getForRenderCacheKey( renderObject );
  21133. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  21134. if ( nodeBuilderState === undefined ) {
  21135. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  21136. nodeBuilder.scene = renderObject.scene;
  21137. nodeBuilder.material = renderObject.material;
  21138. nodeBuilder.camera = renderObject.camera;
  21139. nodeBuilder.context.material = renderObject.material;
  21140. nodeBuilder.lightsNode = renderObject.lightsNode;
  21141. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  21142. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  21143. nodeBuilder.clippingContext = renderObject.clippingContext;
  21144. nodeBuilder.build();
  21145. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  21146. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  21147. }
  21148. nodeBuilderState.usedTimes ++;
  21149. renderObjectData.nodeBuilderState = nodeBuilderState;
  21150. }
  21151. return nodeBuilderState;
  21152. }
  21153. delete( object ) {
  21154. if ( object.isRenderObject ) {
  21155. const nodeBuilderState = this.get( object ).nodeBuilderState;
  21156. nodeBuilderState.usedTimes --;
  21157. if ( nodeBuilderState.usedTimes === 0 ) {
  21158. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  21159. }
  21160. }
  21161. return super.delete( object );
  21162. }
  21163. getForCompute( computeNode ) {
  21164. const computeData = this.get( computeNode );
  21165. let nodeBuilderState = computeData.nodeBuilderState;
  21166. if ( nodeBuilderState === undefined ) {
  21167. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  21168. nodeBuilder.build();
  21169. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  21170. computeData.nodeBuilderState = nodeBuilderState;
  21171. }
  21172. return nodeBuilderState;
  21173. }
  21174. _createNodeBuilderState( nodeBuilder ) {
  21175. return new NodeBuilderState(
  21176. nodeBuilder.vertexShader,
  21177. nodeBuilder.fragmentShader,
  21178. nodeBuilder.computeShader,
  21179. nodeBuilder.getAttributesArray(),
  21180. nodeBuilder.getBindings(),
  21181. nodeBuilder.updateNodes,
  21182. nodeBuilder.updateBeforeNodes,
  21183. nodeBuilder.updateAfterNodes,
  21184. nodeBuilder.monitor,
  21185. nodeBuilder.transforms
  21186. );
  21187. }
  21188. getEnvironmentNode( scene ) {
  21189. return scene.environmentNode || this.get( scene ).environmentNode || null;
  21190. }
  21191. getBackgroundNode( scene ) {
  21192. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  21193. }
  21194. getFogNode( scene ) {
  21195. return scene.fogNode || this.get( scene ).fogNode || null;
  21196. }
  21197. getCacheKey( scene, lightsNode ) {
  21198. const chain = [ scene, lightsNode ];
  21199. const callId = this.renderer.info.calls;
  21200. let cacheKeyData = this.callHashCache.get( chain );
  21201. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  21202. const environmentNode = this.getEnvironmentNode( scene );
  21203. const fogNode = this.getFogNode( scene );
  21204. const values = [];
  21205. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  21206. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  21207. if ( fogNode ) values.push( fogNode.getCacheKey() );
  21208. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  21209. cacheKeyData = {
  21210. callId,
  21211. cacheKey: hashArray( values )
  21212. };
  21213. this.callHashCache.set( chain, cacheKeyData );
  21214. }
  21215. return cacheKeyData.cacheKey;
  21216. }
  21217. updateScene( scene ) {
  21218. this.updateEnvironment( scene );
  21219. this.updateFog( scene );
  21220. this.updateBackground( scene );
  21221. }
  21222. get isToneMappingState() {
  21223. return this.renderer.getRenderTarget() ? false : true;
  21224. }
  21225. updateBackground( scene ) {
  21226. const sceneData = this.get( scene );
  21227. const background = scene.background;
  21228. if ( background ) {
  21229. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  21230. if ( sceneData.background !== background || forceUpdate ) {
  21231. let backgroundNode = null;
  21232. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  21233. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  21234. backgroundNode = pmremTexture( background );
  21235. } else {
  21236. let envMap;
  21237. if ( background.isCubeTexture === true ) {
  21238. envMap = cubeTexture( background );
  21239. } else {
  21240. envMap = texture( background );
  21241. }
  21242. backgroundNode = cubeMapNode( envMap );
  21243. }
  21244. } else if ( background.isTexture === true ) {
  21245. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  21246. } else if ( background.isColor !== true ) {
  21247. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  21248. }
  21249. sceneData.backgroundNode = backgroundNode;
  21250. sceneData.background = background;
  21251. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  21252. }
  21253. } else if ( sceneData.backgroundNode ) {
  21254. delete sceneData.backgroundNode;
  21255. delete sceneData.background;
  21256. }
  21257. }
  21258. updateFog( scene ) {
  21259. const sceneData = this.get( scene );
  21260. const fog = scene.fog;
  21261. if ( fog ) {
  21262. if ( sceneData.fog !== fog ) {
  21263. let fogNode = null;
  21264. if ( fog.isFogExp2 ) {
  21265. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  21266. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  21267. fogNode = densityFog( color, density );
  21268. } else if ( fog.isFog ) {
  21269. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  21270. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  21271. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  21272. fogNode = rangeFog( color, near, far );
  21273. } else {
  21274. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  21275. }
  21276. sceneData.fogNode = fogNode;
  21277. sceneData.fog = fog;
  21278. }
  21279. } else {
  21280. delete sceneData.fogNode;
  21281. delete sceneData.fog;
  21282. }
  21283. }
  21284. updateEnvironment( scene ) {
  21285. const sceneData = this.get( scene );
  21286. const environment = scene.environment;
  21287. if ( environment ) {
  21288. if ( sceneData.environment !== environment ) {
  21289. let environmentNode = null;
  21290. if ( environment.isCubeTexture === true ) {
  21291. environmentNode = cubeTexture( environment );
  21292. } else if ( environment.isTexture === true ) {
  21293. environmentNode = texture( environment );
  21294. } else {
  21295. console.error( 'Nodes: Unsupported environment configuration.', environment );
  21296. }
  21297. sceneData.environmentNode = environmentNode;
  21298. sceneData.environment = environment;
  21299. }
  21300. } else if ( sceneData.environmentNode ) {
  21301. delete sceneData.environmentNode;
  21302. delete sceneData.environment;
  21303. }
  21304. }
  21305. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  21306. const nodeFrame = this.nodeFrame;
  21307. nodeFrame.renderer = renderer;
  21308. nodeFrame.scene = scene;
  21309. nodeFrame.object = object;
  21310. nodeFrame.camera = camera;
  21311. nodeFrame.material = material;
  21312. return nodeFrame;
  21313. }
  21314. getNodeFrameForRender( renderObject ) {
  21315. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  21316. }
  21317. getOutputCacheKey() {
  21318. const renderer = this.renderer;
  21319. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  21320. }
  21321. hasOutputChange( outputTarget ) {
  21322. const cacheKey = outputNodeMap.get( outputTarget );
  21323. return cacheKey !== this.getOutputCacheKey();
  21324. }
  21325. getOutputNode( outputTexture ) {
  21326. const renderer = this.renderer;
  21327. const cacheKey = this.getOutputCacheKey();
  21328. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  21329. outputNodeMap.set( outputTexture, cacheKey );
  21330. return output;
  21331. }
  21332. updateBefore( renderObject ) {
  21333. const nodeBuilder = renderObject.getNodeBuilderState();
  21334. for ( const node of nodeBuilder.updateBeforeNodes ) {
  21335. // update frame state for each node
  21336. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  21337. }
  21338. }
  21339. updateAfter( renderObject ) {
  21340. const nodeBuilder = renderObject.getNodeBuilderState();
  21341. for ( const node of nodeBuilder.updateAfterNodes ) {
  21342. // update frame state for each node
  21343. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  21344. }
  21345. }
  21346. updateForCompute( computeNode ) {
  21347. const nodeFrame = this.getNodeFrame();
  21348. const nodeBuilder = this.getForCompute( computeNode );
  21349. for ( const node of nodeBuilder.updateNodes ) {
  21350. nodeFrame.updateNode( node );
  21351. }
  21352. }
  21353. updateForRender( renderObject ) {
  21354. const nodeFrame = this.getNodeFrameForRender( renderObject );
  21355. const nodeBuilder = renderObject.getNodeBuilderState();
  21356. for ( const node of nodeBuilder.updateNodes ) {
  21357. nodeFrame.updateNode( node );
  21358. }
  21359. }
  21360. needsRefresh( renderObject ) {
  21361. const nodeFrame = this.getNodeFrameForRender( renderObject );
  21362. const monitor = renderObject.getMonitor();
  21363. return monitor.needsRefresh( renderObject, nodeFrame );
  21364. }
  21365. dispose() {
  21366. super.dispose();
  21367. this.nodeFrame = new NodeFrame();
  21368. this.nodeBuilderCache = new Map();
  21369. }
  21370. }
  21371. const _plane = /*@__PURE__*/ new Plane();
  21372. class ClippingContext {
  21373. constructor( parentContext = null ) {
  21374. this.version = 0;
  21375. this.clipIntersection = null;
  21376. this.cacheKey = '';
  21377. if ( parentContext === null ) {
  21378. this.intersectionPlanes = [];
  21379. this.unionPlanes = [];
  21380. this.viewNormalMatrix = new Matrix3();
  21381. this.clippingGroupContexts = new WeakMap();
  21382. this.shadowPass = false;
  21383. } else {
  21384. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  21385. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  21386. this.shadowPass = parentContext.shadowPass;
  21387. this.viewMatrix = parentContext.viewMatrix;
  21388. }
  21389. this.parentVersion = null;
  21390. }
  21391. projectPlanes( source, destination, offset ) {
  21392. const l = source.length;
  21393. for ( let i = 0; i < l; i ++ ) {
  21394. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  21395. const v = destination[ offset + i ];
  21396. const normal = _plane.normal;
  21397. v.x = - normal.x;
  21398. v.y = - normal.y;
  21399. v.z = - normal.z;
  21400. v.w = _plane.constant;
  21401. }
  21402. }
  21403. updateGlobal( scene, camera ) {
  21404. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  21405. this.viewMatrix = camera.matrixWorldInverse;
  21406. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  21407. }
  21408. update( parentContext, clippingGroup ) {
  21409. let update = false;
  21410. if ( parentContext.version !== this.parentVersion ) {
  21411. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  21412. this.unionPlanes = Array.from( parentContext.unionPlanes );
  21413. this.parentVersion = parentContext.version;
  21414. }
  21415. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  21416. this.clipIntersection = clippingGroup.clipIntersection;
  21417. if ( this.clipIntersection ) {
  21418. this.unionPlanes.length = parentContext.unionPlanes.length;
  21419. } else {
  21420. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  21421. }
  21422. }
  21423. const srcClippingPlanes = clippingGroup.clippingPlanes;
  21424. const l = srcClippingPlanes.length;
  21425. let dstClippingPlanes;
  21426. let offset;
  21427. if ( this.clipIntersection ) {
  21428. dstClippingPlanes = this.intersectionPlanes;
  21429. offset = parentContext.intersectionPlanes.length;
  21430. } else {
  21431. dstClippingPlanes = this.unionPlanes;
  21432. offset = parentContext.unionPlanes.length;
  21433. }
  21434. if ( dstClippingPlanes.length !== offset + l ) {
  21435. dstClippingPlanes.length = offset + l;
  21436. for ( let i = 0; i < l; i ++ ) {
  21437. dstClippingPlanes[ offset + i ] = new Vector4();
  21438. }
  21439. update = true;
  21440. }
  21441. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  21442. if ( update ) {
  21443. this.version ++;
  21444. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  21445. }
  21446. }
  21447. getGroupContext( clippingGroup ) {
  21448. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  21449. let context = this.clippingGroupContexts.get( clippingGroup );
  21450. if ( context === undefined ) {
  21451. context = new ClippingContext( this );
  21452. this.clippingGroupContexts.set( clippingGroup, context );
  21453. }
  21454. context.update( this, clippingGroup );
  21455. return context;
  21456. }
  21457. get unionClippingCount() {
  21458. return this.unionPlanes.length;
  21459. }
  21460. }
  21461. class RenderBundle {
  21462. constructor( scene, camera ) {
  21463. this.scene = scene;
  21464. this.camera = camera;
  21465. }
  21466. clone() {
  21467. return Object.assign( new this.constructor(), this );
  21468. }
  21469. }
  21470. class RenderBundles {
  21471. constructor() {
  21472. this.lists = new ChainMap();
  21473. }
  21474. get( scene, camera ) {
  21475. const lists = this.lists;
  21476. const keys = [ scene, camera ];
  21477. let list = lists.get( keys );
  21478. if ( list === undefined ) {
  21479. list = new RenderBundle( scene, camera );
  21480. lists.set( keys, list );
  21481. }
  21482. return list;
  21483. }
  21484. dispose() {
  21485. this.lists = new ChainMap();
  21486. }
  21487. }
  21488. class NodeLibrary {
  21489. constructor() {
  21490. this.lightNodes = new WeakMap();
  21491. this.materialNodes = new Map();
  21492. this.toneMappingNodes = new Map();
  21493. }
  21494. fromMaterial( material ) {
  21495. if ( material.isNodeMaterial ) return material;
  21496. let nodeMaterial = null;
  21497. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  21498. if ( nodeMaterialClass !== null ) {
  21499. nodeMaterial = new nodeMaterialClass();
  21500. for ( const key in material ) {
  21501. nodeMaterial[ key ] = material[ key ];
  21502. }
  21503. }
  21504. return nodeMaterial;
  21505. }
  21506. addToneMapping( toneMappingNode, toneMapping ) {
  21507. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  21508. }
  21509. getToneMappingFunction( toneMapping ) {
  21510. return this.toneMappingNodes.get( toneMapping ) || null;
  21511. }
  21512. getMaterialNodeClass( materialType ) {
  21513. return this.materialNodes.get( materialType ) || null;
  21514. }
  21515. addMaterial( materialNodeClass, materialClassType ) {
  21516. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  21517. }
  21518. getLightNodeClass( light ) {
  21519. return this.lightNodes.get( light ) || null;
  21520. }
  21521. addLight( lightNodeClass, lightClass ) {
  21522. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  21523. }
  21524. addType( nodeClass, type, library ) {
  21525. if ( library.has( type ) ) {
  21526. console.warn( `Redefinition of node ${ type }` );
  21527. return;
  21528. }
  21529. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  21530. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  21531. library.set( type, nodeClass );
  21532. }
  21533. addClass( nodeClass, baseClass, library ) {
  21534. if ( library.has( baseClass ) ) {
  21535. console.warn( `Redefinition of node ${ baseClass.name }` );
  21536. return;
  21537. }
  21538. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  21539. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  21540. library.set( baseClass, nodeClass );
  21541. }
  21542. }
  21543. const _defaultLights = /*@__PURE__*/ new LightsNode();
  21544. class Lighting extends ChainMap {
  21545. constructor() {
  21546. super();
  21547. }
  21548. createNode( lights = [] ) {
  21549. return new LightsNode().setLights( lights );
  21550. }
  21551. getNode( scene, camera ) {
  21552. // ignore post-processing
  21553. if ( scene.isQuadMesh ) return _defaultLights;
  21554. // tiled lighting
  21555. const keys = [ scene, camera ];
  21556. let node = this.get( keys );
  21557. if ( node === undefined ) {
  21558. node = this.createNode();
  21559. this.set( keys, node );
  21560. }
  21561. return node;
  21562. }
  21563. }
  21564. const _scene = /*@__PURE__*/ new Scene();
  21565. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  21566. const _screen = /*@__PURE__*/ new Vector4();
  21567. const _frustum = /*@__PURE__*/ new Frustum();
  21568. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  21569. const _vector4 = /*@__PURE__*/ new Vector4();
  21570. class Renderer {
  21571. constructor( backend, parameters = {} ) {
  21572. this.isRenderer = true;
  21573. //
  21574. const {
  21575. logarithmicDepthBuffer = false,
  21576. alpha = true,
  21577. depth = true,
  21578. stencil = false,
  21579. antialias = false,
  21580. samples = 0,
  21581. getFallback = null
  21582. } = parameters;
  21583. // public
  21584. this.domElement = backend.getDomElement();
  21585. this.backend = backend;
  21586. this.samples = samples || ( antialias === true ) ? 4 : 0;
  21587. this.autoClear = true;
  21588. this.autoClearColor = true;
  21589. this.autoClearDepth = true;
  21590. this.autoClearStencil = true;
  21591. this.alpha = alpha;
  21592. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  21593. this.outputColorSpace = SRGBColorSpace;
  21594. this.toneMapping = NoToneMapping;
  21595. this.toneMappingExposure = 1.0;
  21596. this.sortObjects = true;
  21597. this.depth = depth;
  21598. this.stencil = stencil;
  21599. this.info = new Info();
  21600. this.nodes = {
  21601. modelViewMatrix: null,
  21602. modelNormalViewMatrix: null
  21603. };
  21604. this.library = new NodeLibrary();
  21605. this.lighting = new Lighting();
  21606. // internals
  21607. this._getFallback = getFallback;
  21608. this._pixelRatio = 1;
  21609. this._width = this.domElement.width;
  21610. this._height = this.domElement.height;
  21611. this._viewport = new Vector4( 0, 0, this._width, this._height );
  21612. this._scissor = new Vector4( 0, 0, this._width, this._height );
  21613. this._scissorTest = false;
  21614. this._attributes = null;
  21615. this._geometries = null;
  21616. this._nodes = null;
  21617. this._animation = null;
  21618. this._bindings = null;
  21619. this._objects = null;
  21620. this._pipelines = null;
  21621. this._bundles = null;
  21622. this._renderLists = null;
  21623. this._renderContexts = null;
  21624. this._textures = null;
  21625. this._background = null;
  21626. this._quad = new QuadMesh( new NodeMaterial() );
  21627. this._quad.material.type = 'Renderer_output';
  21628. this._currentRenderContext = null;
  21629. this._opaqueSort = null;
  21630. this._transparentSort = null;
  21631. this._frameBufferTarget = null;
  21632. const alphaClear = this.alpha === true ? 0 : 1;
  21633. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  21634. this._clearDepth = 1;
  21635. this._clearStencil = 0;
  21636. this._renderTarget = null;
  21637. this._activeCubeFace = 0;
  21638. this._activeMipmapLevel = 0;
  21639. this._mrt = null;
  21640. this._renderObjectFunction = null;
  21641. this._currentRenderObjectFunction = null;
  21642. this._currentRenderBundle = null;
  21643. this._handleObjectFunction = this._renderObjectDirect;
  21644. this._isDeviceLost = false;
  21645. this.onDeviceLost = this._onDeviceLost;
  21646. this._initialized = false;
  21647. this._initPromise = null;
  21648. this._compilationPromises = null;
  21649. this.transparent = true;
  21650. this.opaque = true;
  21651. this.shadowMap = {
  21652. enabled: false,
  21653. type: PCFShadowMap
  21654. };
  21655. this.xr = {
  21656. enabled: false
  21657. };
  21658. this.debug = {
  21659. checkShaderErrors: true,
  21660. onShaderError: null,
  21661. getShaderAsync: async ( scene, camera, object ) => {
  21662. await this.compileAsync( scene, camera );
  21663. const renderList = this._renderLists.get( scene, camera );
  21664. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  21665. const material = scene.overrideMaterial || object.material;
  21666. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  21667. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  21668. return { fragmentShader, vertexShader };
  21669. }
  21670. };
  21671. }
  21672. async init() {
  21673. if ( this._initialized ) {
  21674. throw new Error( 'Renderer: Backend has already been initialized.' );
  21675. }
  21676. if ( this._initPromise !== null ) {
  21677. return this._initPromise;
  21678. }
  21679. this._initPromise = new Promise( async ( resolve, reject ) => {
  21680. let backend = this.backend;
  21681. try {
  21682. await backend.init( this );
  21683. } catch ( error ) {
  21684. if ( this._getFallback !== null ) {
  21685. // try the fallback
  21686. try {
  21687. this.backend = backend = this._getFallback( error );
  21688. await backend.init( this );
  21689. } catch ( error ) {
  21690. reject( error );
  21691. return;
  21692. }
  21693. } else {
  21694. reject( error );
  21695. return;
  21696. }
  21697. }
  21698. this._nodes = new Nodes( this, backend );
  21699. this._animation = new Animation( this._nodes, this.info );
  21700. this._attributes = new Attributes( backend );
  21701. this._background = new Background( this, this._nodes );
  21702. this._geometries = new Geometries( this._attributes, this.info );
  21703. this._textures = new Textures( this, backend, this.info );
  21704. this._pipelines = new Pipelines( backend, this._nodes );
  21705. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  21706. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  21707. this._renderLists = new RenderLists( this.lighting );
  21708. this._bundles = new RenderBundles();
  21709. this._renderContexts = new RenderContexts();
  21710. //
  21711. this._animation.start();
  21712. this._initialized = true;
  21713. resolve();
  21714. } );
  21715. return this._initPromise;
  21716. }
  21717. get coordinateSystem() {
  21718. return this.backend.coordinateSystem;
  21719. }
  21720. async compileAsync( scene, camera, targetScene = null ) {
  21721. if ( this._isDeviceLost === true ) return;
  21722. if ( this._initialized === false ) await this.init();
  21723. // preserve render tree
  21724. const nodeFrame = this._nodes.nodeFrame;
  21725. const previousRenderId = nodeFrame.renderId;
  21726. const previousRenderContext = this._currentRenderContext;
  21727. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  21728. const previousCompilationPromises = this._compilationPromises;
  21729. //
  21730. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  21731. if ( targetScene === null ) targetScene = scene;
  21732. const renderTarget = this._renderTarget;
  21733. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  21734. const activeMipmapLevel = this._activeMipmapLevel;
  21735. const compilationPromises = [];
  21736. this._currentRenderContext = renderContext;
  21737. this._currentRenderObjectFunction = this.renderObject;
  21738. this._handleObjectFunction = this._createObjectPipeline;
  21739. this._compilationPromises = compilationPromises;
  21740. nodeFrame.renderId ++;
  21741. //
  21742. nodeFrame.update();
  21743. //
  21744. renderContext.depth = this.depth;
  21745. renderContext.stencil = this.stencil;
  21746. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  21747. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  21748. //
  21749. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  21750. //
  21751. const renderList = this._renderLists.get( scene, camera );
  21752. renderList.begin();
  21753. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  21754. // include lights from target scene
  21755. if ( targetScene !== scene ) {
  21756. targetScene.traverseVisible( function ( object ) {
  21757. if ( object.isLight && object.layers.test( camera.layers ) ) {
  21758. renderList.pushLight( object );
  21759. }
  21760. } );
  21761. }
  21762. renderList.finish();
  21763. //
  21764. if ( renderTarget !== null ) {
  21765. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  21766. const renderTargetData = this._textures.get( renderTarget );
  21767. renderContext.textures = renderTargetData.textures;
  21768. renderContext.depthTexture = renderTargetData.depthTexture;
  21769. } else {
  21770. renderContext.textures = null;
  21771. renderContext.depthTexture = null;
  21772. }
  21773. //
  21774. this._nodes.updateScene( sceneRef );
  21775. //
  21776. this._background.update( sceneRef, renderList, renderContext );
  21777. // process render lists
  21778. const opaqueObjects = renderList.opaque;
  21779. const transparentObjects = renderList.transparent;
  21780. const transparentDoublePassObjects = renderList.transparentDoublePass;
  21781. const lightsNode = renderList.lightsNode;
  21782. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  21783. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  21784. // restore render tree
  21785. nodeFrame.renderId = previousRenderId;
  21786. this._currentRenderContext = previousRenderContext;
  21787. this._currentRenderObjectFunction = previousRenderObjectFunction;
  21788. this._compilationPromises = previousCompilationPromises;
  21789. this._handleObjectFunction = this._renderObjectDirect;
  21790. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  21791. await Promise.all( compilationPromises );
  21792. }
  21793. async renderAsync( scene, camera ) {
  21794. if ( this._initialized === false ) await this.init();
  21795. const renderContext = this._renderScene( scene, camera );
  21796. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  21797. }
  21798. async waitForGPU() {
  21799. await this.backend.waitForGPU();
  21800. }
  21801. setMRT( mrt ) {
  21802. this._mrt = mrt;
  21803. return this;
  21804. }
  21805. getMRT() {
  21806. return this._mrt;
  21807. }
  21808. _onDeviceLost( info ) {
  21809. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  21810. if ( info.reason ) {
  21811. errorMessage += `\nReason: ${info.reason}`;
  21812. }
  21813. console.error( errorMessage );
  21814. this._isDeviceLost = true;
  21815. }
  21816. _renderBundle( bundle, sceneRef, lightsNode ) {
  21817. const { bundleGroup, camera, renderList } = bundle;
  21818. const renderContext = this._currentRenderContext;
  21819. //
  21820. const renderBundle = this._bundles.get( bundleGroup, camera );
  21821. const renderBundleData = this.backend.get( renderBundle );
  21822. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  21823. //
  21824. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  21825. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  21826. renderBundleData.renderContexts.add( renderContext );
  21827. if ( renderBundleNeedsUpdate ) {
  21828. this.backend.beginBundle( renderContext );
  21829. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  21830. renderBundleData.renderObjects = [];
  21831. }
  21832. this._currentRenderBundle = renderBundle;
  21833. const opaqueObjects = renderList.opaque;
  21834. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  21835. this._currentRenderBundle = null;
  21836. //
  21837. this.backend.finishBundle( renderContext, renderBundle );
  21838. renderBundleData.version = bundleGroup.version;
  21839. } else {
  21840. const { renderObjects } = renderBundleData;
  21841. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  21842. const renderObject = renderObjects[ i ];
  21843. if ( this._nodes.needsRefresh( renderObject ) ) {
  21844. this._nodes.updateBefore( renderObject );
  21845. this._nodes.updateForRender( renderObject );
  21846. this._bindings.updateForRender( renderObject );
  21847. this._nodes.updateAfter( renderObject );
  21848. }
  21849. }
  21850. }
  21851. this.backend.addBundle( renderContext, renderBundle );
  21852. }
  21853. render( scene, camera ) {
  21854. if ( this._initialized === false ) {
  21855. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  21856. return this.renderAsync( scene, camera );
  21857. }
  21858. this._renderScene( scene, camera );
  21859. }
  21860. _getFrameBufferTarget() {
  21861. const { currentToneMapping, currentColorSpace } = this;
  21862. const useToneMapping = currentToneMapping !== NoToneMapping;
  21863. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  21864. if ( useToneMapping === false && useColorSpace === false ) return null;
  21865. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  21866. const { depth, stencil } = this;
  21867. let frameBufferTarget = this._frameBufferTarget;
  21868. if ( frameBufferTarget === null ) {
  21869. frameBufferTarget = new RenderTarget( width, height, {
  21870. depthBuffer: depth,
  21871. stencilBuffer: stencil,
  21872. type: HalfFloatType, // FloatType
  21873. format: RGBAFormat,
  21874. colorSpace: LinearSRGBColorSpace,
  21875. generateMipmaps: false,
  21876. minFilter: LinearFilter,
  21877. magFilter: LinearFilter,
  21878. samples: this.samples
  21879. } );
  21880. frameBufferTarget.isPostProcessingRenderTarget = true;
  21881. this._frameBufferTarget = frameBufferTarget;
  21882. }
  21883. frameBufferTarget.depthBuffer = depth;
  21884. frameBufferTarget.stencilBuffer = stencil;
  21885. frameBufferTarget.setSize( width, height );
  21886. frameBufferTarget.viewport.copy( this._viewport );
  21887. frameBufferTarget.scissor.copy( this._scissor );
  21888. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  21889. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  21890. frameBufferTarget.scissorTest = this._scissorTest;
  21891. return frameBufferTarget;
  21892. }
  21893. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  21894. if ( this._isDeviceLost === true ) return;
  21895. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  21896. // preserve render tree
  21897. const nodeFrame = this._nodes.nodeFrame;
  21898. const previousRenderId = nodeFrame.renderId;
  21899. const previousRenderContext = this._currentRenderContext;
  21900. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  21901. //
  21902. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  21903. const outputRenderTarget = this._renderTarget;
  21904. const activeCubeFace = this._activeCubeFace;
  21905. const activeMipmapLevel = this._activeMipmapLevel;
  21906. //
  21907. let renderTarget;
  21908. if ( frameBufferTarget !== null ) {
  21909. renderTarget = frameBufferTarget;
  21910. this.setRenderTarget( renderTarget );
  21911. } else {
  21912. renderTarget = outputRenderTarget;
  21913. }
  21914. //
  21915. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  21916. this._currentRenderContext = renderContext;
  21917. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  21918. //
  21919. this.info.calls ++;
  21920. this.info.render.calls ++;
  21921. this.info.render.frameCalls ++;
  21922. nodeFrame.renderId = this.info.calls;
  21923. //
  21924. const coordinateSystem = this.coordinateSystem;
  21925. if ( camera.coordinateSystem !== coordinateSystem ) {
  21926. camera.coordinateSystem = coordinateSystem;
  21927. camera.updateProjectionMatrix();
  21928. }
  21929. //
  21930. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  21931. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  21932. //
  21933. let viewport = this._viewport;
  21934. let scissor = this._scissor;
  21935. let pixelRatio = this._pixelRatio;
  21936. if ( renderTarget !== null ) {
  21937. viewport = renderTarget.viewport;
  21938. scissor = renderTarget.scissor;
  21939. pixelRatio = 1;
  21940. }
  21941. this.getDrawingBufferSize( _drawingBufferSize );
  21942. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  21943. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  21944. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  21945. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  21946. renderContext.viewportValue.width >>= activeMipmapLevel;
  21947. renderContext.viewportValue.height >>= activeMipmapLevel;
  21948. renderContext.viewportValue.minDepth = minDepth;
  21949. renderContext.viewportValue.maxDepth = maxDepth;
  21950. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  21951. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  21952. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  21953. renderContext.scissorValue.width >>= activeMipmapLevel;
  21954. renderContext.scissorValue.height >>= activeMipmapLevel;
  21955. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  21956. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  21957. //
  21958. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  21959. //
  21960. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21961. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  21962. const renderList = this._renderLists.get( scene, camera );
  21963. renderList.begin();
  21964. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  21965. renderList.finish();
  21966. if ( this.sortObjects === true ) {
  21967. renderList.sort( this._opaqueSort, this._transparentSort );
  21968. }
  21969. //
  21970. if ( renderTarget !== null ) {
  21971. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  21972. const renderTargetData = this._textures.get( renderTarget );
  21973. renderContext.textures = renderTargetData.textures;
  21974. renderContext.depthTexture = renderTargetData.depthTexture;
  21975. renderContext.width = renderTargetData.width;
  21976. renderContext.height = renderTargetData.height;
  21977. renderContext.renderTarget = renderTarget;
  21978. renderContext.depth = renderTarget.depthBuffer;
  21979. renderContext.stencil = renderTarget.stencilBuffer;
  21980. } else {
  21981. renderContext.textures = null;
  21982. renderContext.depthTexture = null;
  21983. renderContext.width = this.domElement.width;
  21984. renderContext.height = this.domElement.height;
  21985. renderContext.depth = this.depth;
  21986. renderContext.stencil = this.stencil;
  21987. }
  21988. renderContext.width >>= activeMipmapLevel;
  21989. renderContext.height >>= activeMipmapLevel;
  21990. renderContext.activeCubeFace = activeCubeFace;
  21991. renderContext.activeMipmapLevel = activeMipmapLevel;
  21992. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  21993. //
  21994. this._nodes.updateScene( sceneRef );
  21995. //
  21996. this._background.update( sceneRef, renderList, renderContext );
  21997. //
  21998. this.backend.beginRender( renderContext );
  21999. // process render lists
  22000. const {
  22001. bundles,
  22002. lightsNode,
  22003. transparentDoublePass: transparentDoublePassObjects,
  22004. transparent: transparentObjects,
  22005. opaque: opaqueObjects
  22006. } = renderList;
  22007. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  22008. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  22009. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  22010. // finish render pass
  22011. this.backend.finishRender( renderContext );
  22012. // restore render tree
  22013. nodeFrame.renderId = previousRenderId;
  22014. this._currentRenderContext = previousRenderContext;
  22015. this._currentRenderObjectFunction = previousRenderObjectFunction;
  22016. //
  22017. if ( frameBufferTarget !== null ) {
  22018. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  22019. const quad = this._quad;
  22020. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  22021. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  22022. quad.material.needsUpdate = true;
  22023. }
  22024. this._renderScene( quad, quad.camera, false );
  22025. }
  22026. //
  22027. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  22028. //
  22029. return renderContext;
  22030. }
  22031. getMaxAnisotropy() {
  22032. return this.backend.getMaxAnisotropy();
  22033. }
  22034. getActiveCubeFace() {
  22035. return this._activeCubeFace;
  22036. }
  22037. getActiveMipmapLevel() {
  22038. return this._activeMipmapLevel;
  22039. }
  22040. async setAnimationLoop( callback ) {
  22041. if ( this._initialized === false ) await this.init();
  22042. this._animation.setAnimationLoop( callback );
  22043. }
  22044. async getArrayBufferAsync( attribute ) {
  22045. return await this.backend.getArrayBufferAsync( attribute );
  22046. }
  22047. getContext() {
  22048. return this.backend.getContext();
  22049. }
  22050. getPixelRatio() {
  22051. return this._pixelRatio;
  22052. }
  22053. getDrawingBufferSize( target ) {
  22054. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  22055. }
  22056. getSize( target ) {
  22057. return target.set( this._width, this._height );
  22058. }
  22059. setPixelRatio( value = 1 ) {
  22060. if ( this._pixelRatio === value ) return;
  22061. this._pixelRatio = value;
  22062. this.setSize( this._width, this._height, false );
  22063. }
  22064. setDrawingBufferSize( width, height, pixelRatio ) {
  22065. this._width = width;
  22066. this._height = height;
  22067. this._pixelRatio = pixelRatio;
  22068. this.domElement.width = Math.floor( width * pixelRatio );
  22069. this.domElement.height = Math.floor( height * pixelRatio );
  22070. this.setViewport( 0, 0, width, height );
  22071. if ( this._initialized ) this.backend.updateSize();
  22072. }
  22073. setSize( width, height, updateStyle = true ) {
  22074. this._width = width;
  22075. this._height = height;
  22076. this.domElement.width = Math.floor( width * this._pixelRatio );
  22077. this.domElement.height = Math.floor( height * this._pixelRatio );
  22078. if ( updateStyle === true ) {
  22079. this.domElement.style.width = width + 'px';
  22080. this.domElement.style.height = height + 'px';
  22081. }
  22082. this.setViewport( 0, 0, width, height );
  22083. if ( this._initialized ) this.backend.updateSize();
  22084. }
  22085. setOpaqueSort( method ) {
  22086. this._opaqueSort = method;
  22087. }
  22088. setTransparentSort( method ) {
  22089. this._transparentSort = method;
  22090. }
  22091. getScissor( target ) {
  22092. const scissor = this._scissor;
  22093. target.x = scissor.x;
  22094. target.y = scissor.y;
  22095. target.width = scissor.width;
  22096. target.height = scissor.height;
  22097. return target;
  22098. }
  22099. setScissor( x, y, width, height ) {
  22100. const scissor = this._scissor;
  22101. if ( x.isVector4 ) {
  22102. scissor.copy( x );
  22103. } else {
  22104. scissor.set( x, y, width, height );
  22105. }
  22106. }
  22107. getScissorTest() {
  22108. return this._scissorTest;
  22109. }
  22110. setScissorTest( boolean ) {
  22111. this._scissorTest = boolean;
  22112. this.backend.setScissorTest( boolean );
  22113. }
  22114. getViewport( target ) {
  22115. return target.copy( this._viewport );
  22116. }
  22117. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  22118. const viewport = this._viewport;
  22119. if ( x.isVector4 ) {
  22120. viewport.copy( x );
  22121. } else {
  22122. viewport.set( x, y, width, height );
  22123. }
  22124. viewport.minDepth = minDepth;
  22125. viewport.maxDepth = maxDepth;
  22126. }
  22127. getClearColor( target ) {
  22128. return target.copy( this._clearColor );
  22129. }
  22130. setClearColor( color, alpha = 1 ) {
  22131. this._clearColor.set( color );
  22132. this._clearColor.a = alpha;
  22133. }
  22134. getClearAlpha() {
  22135. return this._clearColor.a;
  22136. }
  22137. setClearAlpha( alpha ) {
  22138. this._clearColor.a = alpha;
  22139. }
  22140. getClearDepth() {
  22141. return this._clearDepth;
  22142. }
  22143. setClearDepth( depth ) {
  22144. this._clearDepth = depth;
  22145. }
  22146. getClearStencil() {
  22147. return this._clearStencil;
  22148. }
  22149. setClearStencil( stencil ) {
  22150. this._clearStencil = stencil;
  22151. }
  22152. isOccluded( object ) {
  22153. const renderContext = this._currentRenderContext;
  22154. return renderContext && this.backend.isOccluded( renderContext, object );
  22155. }
  22156. clear( color = true, depth = true, stencil = true ) {
  22157. if ( this._initialized === false ) {
  22158. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  22159. return this.clearAsync( color, depth, stencil );
  22160. }
  22161. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  22162. let renderTargetData = null;
  22163. if ( renderTarget !== null ) {
  22164. this._textures.updateRenderTarget( renderTarget );
  22165. renderTargetData = this._textures.get( renderTarget );
  22166. }
  22167. this.backend.clear( color, depth, stencil, renderTargetData );
  22168. if ( renderTarget !== null && this._renderTarget === null ) {
  22169. // If a color space transform or tone mapping is required,
  22170. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  22171. const quad = this._quad;
  22172. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  22173. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  22174. quad.material.needsUpdate = true;
  22175. }
  22176. this._renderScene( quad, quad.camera, false );
  22177. }
  22178. }
  22179. clearColor() {
  22180. return this.clear( true, false, false );
  22181. }
  22182. clearDepth() {
  22183. return this.clear( false, true, false );
  22184. }
  22185. clearStencil() {
  22186. return this.clear( false, false, true );
  22187. }
  22188. async clearAsync( color = true, depth = true, stencil = true ) {
  22189. if ( this._initialized === false ) await this.init();
  22190. this.clear( color, depth, stencil );
  22191. }
  22192. clearColorAsync() {
  22193. return this.clearAsync( true, false, false );
  22194. }
  22195. clearDepthAsync() {
  22196. return this.clearAsync( false, true, false );
  22197. }
  22198. clearStencilAsync() {
  22199. return this.clearAsync( false, false, true );
  22200. }
  22201. get currentToneMapping() {
  22202. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  22203. }
  22204. get currentColorSpace() {
  22205. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  22206. }
  22207. dispose() {
  22208. this.info.dispose();
  22209. this.backend.dispose();
  22210. this._animation.dispose();
  22211. this._objects.dispose();
  22212. this._pipelines.dispose();
  22213. this._nodes.dispose();
  22214. this._bindings.dispose();
  22215. this._renderLists.dispose();
  22216. this._renderContexts.dispose();
  22217. this._textures.dispose();
  22218. this.setRenderTarget( null );
  22219. this.setAnimationLoop( null );
  22220. }
  22221. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  22222. this._renderTarget = renderTarget;
  22223. this._activeCubeFace = activeCubeFace;
  22224. this._activeMipmapLevel = activeMipmapLevel;
  22225. }
  22226. getRenderTarget() {
  22227. return this._renderTarget;
  22228. }
  22229. setRenderObjectFunction( renderObjectFunction ) {
  22230. this._renderObjectFunction = renderObjectFunction;
  22231. }
  22232. getRenderObjectFunction() {
  22233. return this._renderObjectFunction;
  22234. }
  22235. compute( computeNodes ) {
  22236. if ( this.isDeviceLost === true ) return;
  22237. if ( this._initialized === false ) {
  22238. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  22239. return this.computeAsync( computeNodes );
  22240. }
  22241. //
  22242. const nodeFrame = this._nodes.nodeFrame;
  22243. const previousRenderId = nodeFrame.renderId;
  22244. //
  22245. this.info.calls ++;
  22246. this.info.compute.calls ++;
  22247. this.info.compute.frameCalls ++;
  22248. nodeFrame.renderId = this.info.calls;
  22249. //
  22250. const backend = this.backend;
  22251. const pipelines = this._pipelines;
  22252. const bindings = this._bindings;
  22253. const nodes = this._nodes;
  22254. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  22255. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  22256. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  22257. }
  22258. backend.beginCompute( computeNodes );
  22259. for ( const computeNode of computeList ) {
  22260. // onInit
  22261. if ( pipelines.has( computeNode ) === false ) {
  22262. const dispose = () => {
  22263. computeNode.removeEventListener( 'dispose', dispose );
  22264. pipelines.delete( computeNode );
  22265. bindings.delete( computeNode );
  22266. nodes.delete( computeNode );
  22267. };
  22268. computeNode.addEventListener( 'dispose', dispose );
  22269. //
  22270. const onInitFn = computeNode.onInitFunction;
  22271. if ( onInitFn !== null ) {
  22272. onInitFn.call( computeNode, { renderer: this } );
  22273. }
  22274. }
  22275. nodes.updateForCompute( computeNode );
  22276. bindings.updateForCompute( computeNode );
  22277. const computeBindings = bindings.getForCompute( computeNode );
  22278. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  22279. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  22280. }
  22281. backend.finishCompute( computeNodes );
  22282. //
  22283. nodeFrame.renderId = previousRenderId;
  22284. }
  22285. async computeAsync( computeNodes ) {
  22286. if ( this._initialized === false ) await this.init();
  22287. this.compute( computeNodes );
  22288. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  22289. }
  22290. async hasFeatureAsync( name ) {
  22291. if ( this._initialized === false ) await this.init();
  22292. return this.backend.hasFeature( name );
  22293. }
  22294. hasFeature( name ) {
  22295. if ( this._initialized === false ) {
  22296. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  22297. return false;
  22298. }
  22299. return this.backend.hasFeature( name );
  22300. }
  22301. hasInitialized() {
  22302. return this._initialized;
  22303. }
  22304. async initTextureAsync( texture ) {
  22305. if ( this._initialized === false ) await this.init();
  22306. this._textures.updateTexture( texture );
  22307. }
  22308. initTexture( texture ) {
  22309. if ( this._initialized === false ) {
  22310. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  22311. return false;
  22312. }
  22313. this._textures.updateTexture( texture );
  22314. }
  22315. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  22316. if ( rectangle !== null ) {
  22317. if ( rectangle.isVector2 ) {
  22318. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  22319. } else if ( rectangle.isVector4 ) {
  22320. rectangle = _vector4.copy( rectangle ).floor();
  22321. } else {
  22322. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  22323. return;
  22324. }
  22325. } else {
  22326. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  22327. }
  22328. //
  22329. let renderContext = this._currentRenderContext;
  22330. let renderTarget;
  22331. if ( renderContext !== null ) {
  22332. renderTarget = renderContext.renderTarget;
  22333. } else {
  22334. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  22335. if ( renderTarget !== null ) {
  22336. this._textures.updateRenderTarget( renderTarget );
  22337. renderContext = this._textures.get( renderTarget );
  22338. }
  22339. }
  22340. //
  22341. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  22342. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  22343. }
  22344. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  22345. this._textures.updateTexture( srcTexture );
  22346. this._textures.updateTexture( dstTexture );
  22347. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  22348. }
  22349. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  22350. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  22351. }
  22352. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  22353. if ( object.visible === false ) return;
  22354. const visible = object.layers.test( camera.layers );
  22355. if ( visible ) {
  22356. if ( object.isGroup ) {
  22357. groupOrder = object.renderOrder;
  22358. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  22359. } else if ( object.isLOD ) {
  22360. if ( object.autoUpdate === true ) object.update( camera );
  22361. } else if ( object.isLight ) {
  22362. renderList.pushLight( object );
  22363. } else if ( object.isSprite ) {
  22364. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  22365. if ( this.sortObjects === true ) {
  22366. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  22367. }
  22368. const { geometry, material } = object;
  22369. if ( material.visible ) {
  22370. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  22371. }
  22372. }
  22373. } else if ( object.isLineLoop ) {
  22374. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  22375. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  22376. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  22377. const { geometry, material } = object;
  22378. if ( this.sortObjects === true ) {
  22379. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  22380. _vector4
  22381. .copy( geometry.boundingSphere.center )
  22382. .applyMatrix4( object.matrixWorld )
  22383. .applyMatrix4( _projScreenMatrix );
  22384. }
  22385. if ( Array.isArray( material ) ) {
  22386. const groups = geometry.groups;
  22387. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  22388. const group = groups[ i ];
  22389. const groupMaterial = material[ group.materialIndex ];
  22390. if ( groupMaterial && groupMaterial.visible ) {
  22391. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  22392. }
  22393. }
  22394. } else if ( material.visible ) {
  22395. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  22396. }
  22397. }
  22398. }
  22399. }
  22400. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  22401. const baseRenderList = renderList;
  22402. // replace render list
  22403. renderList = this._renderLists.get( object, camera );
  22404. renderList.begin();
  22405. baseRenderList.pushBundle( {
  22406. bundleGroup: object,
  22407. camera,
  22408. renderList,
  22409. } );
  22410. renderList.finish();
  22411. }
  22412. const children = object.children;
  22413. for ( let i = 0, l = children.length; i < l; i ++ ) {
  22414. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  22415. }
  22416. }
  22417. _renderBundles( bundles, sceneRef, lightsNode ) {
  22418. for ( const bundle of bundles ) {
  22419. this._renderBundle( bundle, sceneRef, lightsNode );
  22420. }
  22421. }
  22422. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  22423. if ( doublePassList.length > 0 ) {
  22424. // render back side
  22425. for ( const { material } of doublePassList ) {
  22426. material.side = BackSide;
  22427. }
  22428. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  22429. // render front side
  22430. for ( const { material } of doublePassList ) {
  22431. material.side = FrontSide;
  22432. }
  22433. this._renderObjects( renderList, camera, scene, lightsNode );
  22434. // restore
  22435. for ( const { material } of doublePassList ) {
  22436. material.side = DoubleSide;
  22437. }
  22438. } else {
  22439. this._renderObjects( renderList, camera, scene, lightsNode );
  22440. }
  22441. }
  22442. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  22443. // process renderable objects
  22444. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  22445. const renderItem = renderList[ i ];
  22446. // @TODO: Add support for multiple materials per object. This will require to extract
  22447. // the material from the renderItem object and pass it with its group data to renderObject().
  22448. const { object, geometry, material, group, clippingContext } = renderItem;
  22449. if ( camera.isArrayCamera ) {
  22450. const cameras = camera.cameras;
  22451. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  22452. const camera2 = cameras[ j ];
  22453. if ( object.layers.test( camera2.layers ) ) {
  22454. const vp = camera2.viewport;
  22455. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  22456. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  22457. const viewportValue = this._currentRenderContext.viewportValue;
  22458. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  22459. viewportValue.minDepth = minDepth;
  22460. viewportValue.maxDepth = maxDepth;
  22461. this.backend.updateViewport( this._currentRenderContext );
  22462. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  22463. }
  22464. }
  22465. } else {
  22466. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  22467. }
  22468. }
  22469. }
  22470. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  22471. let overridePositionNode;
  22472. let overrideColorNode;
  22473. let overrideDepthNode;
  22474. //
  22475. object.onBeforeRender( this, scene, camera, geometry, material, group );
  22476. //
  22477. if ( scene.overrideMaterial !== null ) {
  22478. const overrideMaterial = scene.overrideMaterial;
  22479. if ( material.positionNode && material.positionNode.isNode ) {
  22480. overridePositionNode = overrideMaterial.positionNode;
  22481. overrideMaterial.positionNode = material.positionNode;
  22482. }
  22483. overrideMaterial.alphaTest = material.alphaTest;
  22484. overrideMaterial.alphaMap = material.alphaMap;
  22485. if ( overrideMaterial.isShadowNodeMaterial ) {
  22486. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  22487. if ( material.depthNode && material.depthNode.isNode ) {
  22488. overrideDepthNode = overrideMaterial.depthNode;
  22489. overrideMaterial.depthNode = material.depthNode;
  22490. }
  22491. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  22492. overrideColorNode = overrideMaterial.colorNode;
  22493. overrideMaterial.colorNode = material.castShadowNode;
  22494. }
  22495. }
  22496. material = overrideMaterial;
  22497. }
  22498. //
  22499. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  22500. material.side = BackSide;
  22501. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  22502. material.side = FrontSide;
  22503. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  22504. material.side = DoubleSide;
  22505. } else {
  22506. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  22507. }
  22508. //
  22509. if ( overridePositionNode !== undefined ) {
  22510. scene.overrideMaterial.positionNode = overridePositionNode;
  22511. }
  22512. if ( overrideDepthNode !== undefined ) {
  22513. scene.overrideMaterial.depthNode = overrideDepthNode;
  22514. }
  22515. if ( overrideColorNode !== undefined ) {
  22516. scene.overrideMaterial.colorNode = overrideColorNode;
  22517. }
  22518. //
  22519. object.onAfterRender( this, scene, camera, geometry, material, group );
  22520. }
  22521. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  22522. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  22523. renderObject.drawRange = object.geometry.drawRange;
  22524. renderObject.group = group;
  22525. //
  22526. const needsRefresh = this._nodes.needsRefresh( renderObject );
  22527. if ( needsRefresh ) {
  22528. this._nodes.updateBefore( renderObject );
  22529. this._geometries.updateForRender( renderObject );
  22530. this._nodes.updateForRender( renderObject );
  22531. this._bindings.updateForRender( renderObject );
  22532. }
  22533. this._pipelines.updateForRender( renderObject );
  22534. //
  22535. if ( this._currentRenderBundle !== null ) {
  22536. const renderBundleData = this.backend.get( this._currentRenderBundle );
  22537. renderBundleData.renderObjects.push( renderObject );
  22538. renderObject.bundle = this._currentRenderBundle.scene;
  22539. }
  22540. this.backend.draw( renderObject, this.info );
  22541. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  22542. }
  22543. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  22544. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  22545. //
  22546. this._nodes.updateBefore( renderObject );
  22547. this._geometries.updateForRender( renderObject );
  22548. this._nodes.updateForRender( renderObject );
  22549. this._bindings.updateForRender( renderObject );
  22550. this._pipelines.getForRender( renderObject, this._compilationPromises );
  22551. this._nodes.updateAfter( renderObject );
  22552. }
  22553. get compile() {
  22554. return this.compileAsync;
  22555. }
  22556. }
  22557. class Binding {
  22558. constructor( name = '' ) {
  22559. this.name = name;
  22560. this.visibility = 0;
  22561. }
  22562. setVisibility( visibility ) {
  22563. this.visibility |= visibility;
  22564. }
  22565. clone() {
  22566. return Object.assign( new this.constructor(), this );
  22567. }
  22568. }
  22569. function getFloatLength( floatLength ) {
  22570. // ensure chunk size alignment (STD140 layout)
  22571. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  22572. }
  22573. class Buffer extends Binding {
  22574. constructor( name, buffer = null ) {
  22575. super( name );
  22576. this.isBuffer = true;
  22577. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  22578. this._buffer = buffer;
  22579. }
  22580. get byteLength() {
  22581. return getFloatLength( this._buffer.byteLength );
  22582. }
  22583. get buffer() {
  22584. return this._buffer;
  22585. }
  22586. update() {
  22587. return true;
  22588. }
  22589. }
  22590. class UniformBuffer extends Buffer {
  22591. constructor( name, buffer = null ) {
  22592. super( name, buffer );
  22593. this.isUniformBuffer = true;
  22594. }
  22595. }
  22596. let _id$4 = 0;
  22597. class NodeUniformBuffer extends UniformBuffer {
  22598. constructor( nodeUniform, groupNode ) {
  22599. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  22600. this.nodeUniform = nodeUniform;
  22601. this.groupNode = groupNode;
  22602. }
  22603. get buffer() {
  22604. return this.nodeUniform.value;
  22605. }
  22606. }
  22607. class UniformsGroup extends UniformBuffer {
  22608. constructor( name ) {
  22609. super( name );
  22610. this.isUniformsGroup = true;
  22611. this._values = null;
  22612. // the order of uniforms in this array must match the order of uniforms in the shader
  22613. this.uniforms = [];
  22614. }
  22615. addUniform( uniform ) {
  22616. this.uniforms.push( uniform );
  22617. return this;
  22618. }
  22619. removeUniform( uniform ) {
  22620. const index = this.uniforms.indexOf( uniform );
  22621. if ( index !== - 1 ) {
  22622. this.uniforms.splice( index, 1 );
  22623. }
  22624. return this;
  22625. }
  22626. get values() {
  22627. if ( this._values === null ) {
  22628. this._values = Array.from( this.buffer );
  22629. }
  22630. return this._values;
  22631. }
  22632. get buffer() {
  22633. let buffer = this._buffer;
  22634. if ( buffer === null ) {
  22635. const byteLength = this.byteLength;
  22636. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  22637. this._buffer = buffer;
  22638. }
  22639. return buffer;
  22640. }
  22641. get byteLength() {
  22642. let offset = 0; // global buffer offset in bytes
  22643. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  22644. const uniform = this.uniforms[ i ];
  22645. const { boundary, itemSize } = uniform;
  22646. // offset within a single chunk in bytes
  22647. const chunkOffset = offset % GPU_CHUNK_BYTES;
  22648. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  22649. // conformance tests
  22650. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  22651. // check for chunk overflow
  22652. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  22653. } else if ( chunkOffset % boundary !== 0 ) {
  22654. // check for correct alignment
  22655. offset += ( chunkOffset % boundary );
  22656. }
  22657. uniform.offset = ( offset / this.bytesPerElement );
  22658. offset += ( itemSize * this.bytesPerElement );
  22659. }
  22660. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  22661. }
  22662. update() {
  22663. let updated = false;
  22664. for ( const uniform of this.uniforms ) {
  22665. if ( this.updateByType( uniform ) === true ) {
  22666. updated = true;
  22667. }
  22668. }
  22669. return updated;
  22670. }
  22671. updateByType( uniform ) {
  22672. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  22673. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  22674. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  22675. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  22676. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  22677. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  22678. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  22679. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  22680. }
  22681. updateNumber( uniform ) {
  22682. let updated = false;
  22683. const a = this.values;
  22684. const v = uniform.getValue();
  22685. const offset = uniform.offset;
  22686. const type = uniform.getType();
  22687. if ( a[ offset ] !== v ) {
  22688. const b = this._getBufferForType( type );
  22689. b[ offset ] = a[ offset ] = v;
  22690. updated = true;
  22691. }
  22692. return updated;
  22693. }
  22694. updateVector2( uniform ) {
  22695. let updated = false;
  22696. const a = this.values;
  22697. const v = uniform.getValue();
  22698. const offset = uniform.offset;
  22699. const type = uniform.getType();
  22700. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  22701. const b = this._getBufferForType( type );
  22702. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  22703. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  22704. updated = true;
  22705. }
  22706. return updated;
  22707. }
  22708. updateVector3( uniform ) {
  22709. let updated = false;
  22710. const a = this.values;
  22711. const v = uniform.getValue();
  22712. const offset = uniform.offset;
  22713. const type = uniform.getType();
  22714. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  22715. const b = this._getBufferForType( type );
  22716. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  22717. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  22718. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  22719. updated = true;
  22720. }
  22721. return updated;
  22722. }
  22723. updateVector4( uniform ) {
  22724. let updated = false;
  22725. const a = this.values;
  22726. const v = uniform.getValue();
  22727. const offset = uniform.offset;
  22728. const type = uniform.getType();
  22729. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  22730. const b = this._getBufferForType( type );
  22731. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  22732. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  22733. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  22734. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  22735. updated = true;
  22736. }
  22737. return updated;
  22738. }
  22739. updateColor( uniform ) {
  22740. let updated = false;
  22741. const a = this.values;
  22742. const c = uniform.getValue();
  22743. const offset = uniform.offset;
  22744. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  22745. const b = this.buffer;
  22746. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  22747. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  22748. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  22749. updated = true;
  22750. }
  22751. return updated;
  22752. }
  22753. updateMatrix3( uniform ) {
  22754. let updated = false;
  22755. const a = this.values;
  22756. const e = uniform.getValue().elements;
  22757. const offset = uniform.offset;
  22758. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  22759. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  22760. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  22761. const b = this.buffer;
  22762. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  22763. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  22764. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  22765. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  22766. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  22767. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  22768. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  22769. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  22770. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  22771. updated = true;
  22772. }
  22773. return updated;
  22774. }
  22775. updateMatrix4( uniform ) {
  22776. let updated = false;
  22777. const a = this.values;
  22778. const e = uniform.getValue().elements;
  22779. const offset = uniform.offset;
  22780. if ( arraysEqual( a, e, offset ) === false ) {
  22781. const b = this.buffer;
  22782. b.set( e, offset );
  22783. setArray( a, e, offset );
  22784. updated = true;
  22785. }
  22786. return updated;
  22787. }
  22788. _getBufferForType( type ) {
  22789. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  22790. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  22791. return this.buffer;
  22792. }
  22793. }
  22794. function setArray( a, b, offset ) {
  22795. for ( let i = 0, l = b.length; i < l; i ++ ) {
  22796. a[ offset + i ] = b[ i ];
  22797. }
  22798. }
  22799. function arraysEqual( a, b, offset ) {
  22800. for ( let i = 0, l = b.length; i < l; i ++ ) {
  22801. if ( a[ offset + i ] !== b[ i ] ) return false;
  22802. }
  22803. return true;
  22804. }
  22805. let _id$3 = 0;
  22806. class NodeUniformsGroup extends UniformsGroup {
  22807. constructor( name, groupNode ) {
  22808. super( name );
  22809. this.id = _id$3 ++;
  22810. this.groupNode = groupNode;
  22811. this.isNodeUniformsGroup = true;
  22812. }
  22813. getNodes() {
  22814. const nodes = [];
  22815. for ( const uniform of this.uniforms ) {
  22816. const node = uniform.nodeUniform.node;
  22817. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  22818. nodes.push( node );
  22819. }
  22820. return nodes;
  22821. }
  22822. }
  22823. let _id$2 = 0;
  22824. class SampledTexture extends Binding {
  22825. constructor( name, texture ) {
  22826. super( name );
  22827. this.id = _id$2 ++;
  22828. this.texture = texture;
  22829. this.version = texture ? texture.version : 0;
  22830. this.store = false;
  22831. this.generation = null;
  22832. this.isSampledTexture = true;
  22833. }
  22834. needsBindingsUpdate( generation ) {
  22835. const { texture } = this;
  22836. if ( generation !== this.generation ) {
  22837. this.generation = generation;
  22838. return true;
  22839. }
  22840. return texture.isVideoTexture;
  22841. }
  22842. update() {
  22843. const { texture, version } = this;
  22844. if ( version !== texture.version ) {
  22845. this.version = texture.version;
  22846. return true;
  22847. }
  22848. return false;
  22849. }
  22850. }
  22851. class NodeSampledTexture extends SampledTexture {
  22852. constructor( name, textureNode, groupNode, access = null ) {
  22853. super( name, textureNode ? textureNode.value : null );
  22854. this.textureNode = textureNode;
  22855. this.groupNode = groupNode;
  22856. this.access = access;
  22857. }
  22858. needsBindingsUpdate( generation ) {
  22859. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  22860. }
  22861. update() {
  22862. const { textureNode } = this;
  22863. if ( this.texture !== textureNode.value ) {
  22864. this.texture = textureNode.value;
  22865. return true;
  22866. }
  22867. return super.update();
  22868. }
  22869. }
  22870. class NodeSampledCubeTexture extends NodeSampledTexture {
  22871. constructor( name, textureNode, groupNode, access ) {
  22872. super( name, textureNode, groupNode, access );
  22873. this.isSampledCubeTexture = true;
  22874. }
  22875. }
  22876. class NodeSampledTexture3D extends NodeSampledTexture {
  22877. constructor( name, textureNode, groupNode, access ) {
  22878. super( name, textureNode, groupNode, access );
  22879. this.isSampledTexture3D = true;
  22880. }
  22881. }
  22882. const glslMethods = {
  22883. atan2: 'atan',
  22884. textureDimensions: 'textureSize',
  22885. equals: 'equal'
  22886. };
  22887. const precisionLib = {
  22888. low: 'lowp',
  22889. medium: 'mediump',
  22890. high: 'highp'
  22891. };
  22892. const supports$1 = {
  22893. swizzleAssign: true,
  22894. storageBuffer: false
  22895. };
  22896. const defaultPrecisions = `
  22897. precision highp float;
  22898. precision highp int;
  22899. precision highp sampler2D;
  22900. precision highp sampler3D;
  22901. precision highp samplerCube;
  22902. precision highp sampler2DArray;
  22903. precision highp usampler2D;
  22904. precision highp usampler3D;
  22905. precision highp usamplerCube;
  22906. precision highp usampler2DArray;
  22907. precision highp isampler2D;
  22908. precision highp isampler3D;
  22909. precision highp isamplerCube;
  22910. precision highp isampler2DArray;
  22911. precision lowp sampler2DShadow;
  22912. `;
  22913. class GLSLNodeBuilder extends NodeBuilder {
  22914. constructor( object, renderer ) {
  22915. super( object, renderer, new GLSLNodeParser() );
  22916. this.uniformGroups = {};
  22917. this.transforms = [];
  22918. this.extensions = {};
  22919. this.builtins = { vertex: [], fragment: [], compute: [] };
  22920. this.useComparisonMethod = true;
  22921. }
  22922. needsToWorkingColorSpace( texture ) {
  22923. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  22924. }
  22925. getMethod( method ) {
  22926. return glslMethods[ method ] || method;
  22927. }
  22928. getOutputStructName() {
  22929. return '';
  22930. }
  22931. buildFunctionCode( shaderNode ) {
  22932. const layout = shaderNode.layout;
  22933. const flowData = this.flowShaderNode( shaderNode );
  22934. const parameters = [];
  22935. for ( const input of layout.inputs ) {
  22936. parameters.push( this.getType( input.type ) + ' ' + input.name );
  22937. }
  22938. //
  22939. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  22940. ${ flowData.vars }
  22941. ${ flowData.code }
  22942. return ${ flowData.result };
  22943. }`;
  22944. //
  22945. return code;
  22946. }
  22947. setupPBO( storageBufferNode ) {
  22948. const attribute = storageBufferNode.value;
  22949. if ( attribute.pbo === undefined ) {
  22950. const originalArray = attribute.array;
  22951. const numElements = attribute.count * attribute.itemSize;
  22952. const { itemSize } = attribute;
  22953. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  22954. let format = isInteger ? RedIntegerFormat : RedFormat;
  22955. if ( itemSize === 2 ) {
  22956. format = isInteger ? RGIntegerFormat : RGFormat;
  22957. } else if ( itemSize === 3 ) {
  22958. format = isInteger ? RGBIntegerFormat : RGBFormat;
  22959. } else if ( itemSize === 4 ) {
  22960. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  22961. }
  22962. const typeMap = {
  22963. Float32Array: FloatType,
  22964. Uint8Array: UnsignedByteType,
  22965. Uint16Array: UnsignedShortType,
  22966. Uint32Array: UnsignedIntType,
  22967. Int8Array: ByteType,
  22968. Int16Array: ShortType,
  22969. Int32Array: IntType,
  22970. Uint8ClampedArray: UnsignedByteType,
  22971. };
  22972. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  22973. let height = Math.ceil( ( numElements / itemSize ) / width );
  22974. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  22975. const newSize = width * height * itemSize;
  22976. const newArray = new originalArray.constructor( newSize );
  22977. newArray.set( originalArray, 0 );
  22978. attribute.array = newArray;
  22979. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  22980. pboTexture.needsUpdate = true;
  22981. pboTexture.isPBOTexture = true;
  22982. const pbo = new TextureNode( pboTexture, null, null );
  22983. pbo.setPrecision( 'high' );
  22984. attribute.pboNode = pbo;
  22985. attribute.pbo = pbo.value;
  22986. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  22987. }
  22988. }
  22989. getPropertyName( node, shaderStage = this.shaderStage ) {
  22990. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  22991. return shaderStage.charAt( 0 ) + '_' + node.name;
  22992. }
  22993. return super.getPropertyName( node, shaderStage );
  22994. }
  22995. generatePBO( storageArrayElementNode ) {
  22996. const { node, indexNode } = storageArrayElementNode;
  22997. const attribute = node.value;
  22998. if ( this.renderer.backend.has( attribute ) ) {
  22999. const attributeData = this.renderer.backend.get( attribute );
  23000. attributeData.pbo = attribute.pbo;
  23001. }
  23002. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  23003. const textureName = this.getPropertyName( nodeUniform );
  23004. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  23005. const indexSnippet = indexNode.build( this, 'uint' );
  23006. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  23007. let propertyName = elementNodeData.propertyName;
  23008. if ( propertyName === undefined ) {
  23009. // property element
  23010. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  23011. propertyName = this.getPropertyName( nodeVar );
  23012. // property size
  23013. const bufferNodeData = this.getDataFromNode( node );
  23014. let propertySizeName = bufferNodeData.propertySizeName;
  23015. if ( propertySizeName === undefined ) {
  23016. propertySizeName = propertyName + 'Size';
  23017. this.getVarFromNode( node, propertySizeName, 'uint' );
  23018. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  23019. bufferNodeData.propertySizeName = propertySizeName;
  23020. }
  23021. //
  23022. const { itemSize } = attribute;
  23023. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  23024. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  23025. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  23026. //
  23027. let prefix = 'vec4';
  23028. if ( attribute.pbo.type === UnsignedIntType ) {
  23029. prefix = 'uvec4';
  23030. } else if ( attribute.pbo.type === IntType ) {
  23031. prefix = 'ivec4';
  23032. }
  23033. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  23034. elementNodeData.propertyName = propertyName;
  23035. }
  23036. return propertyName;
  23037. }
  23038. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  23039. if ( depthSnippet ) {
  23040. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  23041. } else {
  23042. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  23043. }
  23044. }
  23045. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  23046. if ( texture.isDepthTexture ) {
  23047. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  23048. } else {
  23049. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  23050. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  23051. }
  23052. }
  23053. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  23054. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  23055. }
  23056. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  23057. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  23058. }
  23059. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  23060. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  23061. }
  23062. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  23063. if ( shaderStage === 'fragment' ) {
  23064. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  23065. } else {
  23066. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  23067. }
  23068. }
  23069. getVars( shaderStage ) {
  23070. const snippets = [];
  23071. const vars = this.vars[ shaderStage ];
  23072. if ( vars !== undefined ) {
  23073. for ( const variable of vars ) {
  23074. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  23075. }
  23076. }
  23077. return snippets.join( '\n\t' );
  23078. }
  23079. getUniforms( shaderStage ) {
  23080. const uniforms = this.uniforms[ shaderStage ];
  23081. const bindingSnippets = [];
  23082. const uniformGroups = {};
  23083. for ( const uniform of uniforms ) {
  23084. let snippet = null;
  23085. let group = false;
  23086. if ( uniform.type === 'texture' ) {
  23087. const texture = uniform.node.value;
  23088. let typePrefix = '';
  23089. if ( texture.isDataTexture === true ) {
  23090. if ( texture.type === UnsignedIntType ) {
  23091. typePrefix = 'u';
  23092. } else if ( texture.type === IntType ) {
  23093. typePrefix = 'i';
  23094. }
  23095. }
  23096. if ( texture.compareFunction ) {
  23097. snippet = `sampler2DShadow ${ uniform.name };`;
  23098. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  23099. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  23100. } else {
  23101. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  23102. }
  23103. } else if ( uniform.type === 'cubeTexture' ) {
  23104. snippet = `samplerCube ${ uniform.name };`;
  23105. } else if ( uniform.type === 'texture3D' ) {
  23106. snippet = `sampler3D ${ uniform.name };`;
  23107. } else if ( uniform.type === 'buffer' ) {
  23108. const bufferNode = uniform.node;
  23109. const bufferType = this.getType( bufferNode.bufferType );
  23110. const bufferCount = bufferNode.bufferCount;
  23111. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  23112. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  23113. } else {
  23114. const vectorType = this.getVectorType( uniform.type );
  23115. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  23116. group = true;
  23117. }
  23118. const precision = uniform.node.precision;
  23119. if ( precision !== null ) {
  23120. snippet = precisionLib[ precision ] + ' ' + snippet;
  23121. }
  23122. if ( group ) {
  23123. snippet = '\t' + snippet;
  23124. const groupName = uniform.groupNode.name;
  23125. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  23126. groupSnippets.push( snippet );
  23127. } else {
  23128. snippet = 'uniform ' + snippet;
  23129. bindingSnippets.push( snippet );
  23130. }
  23131. }
  23132. let output = '';
  23133. for ( const name in uniformGroups ) {
  23134. const groupSnippets = uniformGroups[ name ];
  23135. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  23136. }
  23137. output += bindingSnippets.join( '\n' );
  23138. return output;
  23139. }
  23140. getTypeFromAttribute( attribute ) {
  23141. let nodeType = super.getTypeFromAttribute( attribute );
  23142. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  23143. let dataAttribute = attribute;
  23144. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  23145. const array = dataAttribute.array;
  23146. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  23147. nodeType = nodeType.slice( 1 );
  23148. }
  23149. }
  23150. return nodeType;
  23151. }
  23152. getAttributes( shaderStage ) {
  23153. let snippet = '';
  23154. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  23155. const attributes = this.getAttributesArray();
  23156. let location = 0;
  23157. for ( const attribute of attributes ) {
  23158. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  23159. }
  23160. }
  23161. return snippet;
  23162. }
  23163. getStructMembers( struct ) {
  23164. const snippets = [];
  23165. const members = struct.getMemberTypes();
  23166. for ( let i = 0; i < members.length; i ++ ) {
  23167. const member = members[ i ];
  23168. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  23169. }
  23170. return snippets.join( '\n' );
  23171. }
  23172. getStructs( shaderStage ) {
  23173. const snippets = [];
  23174. const structs = this.structs[ shaderStage ];
  23175. if ( structs.length === 0 ) {
  23176. return 'layout( location = 0 ) out vec4 fragColor;\n';
  23177. }
  23178. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  23179. const struct = structs[ index ];
  23180. let snippet = '\n';
  23181. snippet += this.getStructMembers( struct );
  23182. snippet += '\n';
  23183. snippets.push( snippet );
  23184. }
  23185. return snippets.join( '\n\n' );
  23186. }
  23187. getVaryings( shaderStage ) {
  23188. let snippet = '';
  23189. const varyings = this.varyings;
  23190. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  23191. for ( const varying of varyings ) {
  23192. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  23193. const type = this.getType( varying.type );
  23194. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  23195. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  23196. }
  23197. } else if ( shaderStage === 'fragment' ) {
  23198. for ( const varying of varyings ) {
  23199. if ( varying.needsInterpolation ) {
  23200. const type = this.getType( varying.type );
  23201. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  23202. snippet += `${flat}in ${type} ${varying.name};\n`;
  23203. }
  23204. }
  23205. }
  23206. for ( const builtin of this.builtins[ shaderStage ] ) {
  23207. snippet += `${builtin};\n`;
  23208. }
  23209. return snippet;
  23210. }
  23211. getVertexIndex() {
  23212. return 'uint( gl_VertexID )';
  23213. }
  23214. getInstanceIndex() {
  23215. return 'uint( gl_InstanceID )';
  23216. }
  23217. getInvocationLocalIndex() {
  23218. const workgroupSize = this.object.workgroupSize;
  23219. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  23220. return `uint( gl_InstanceID ) % ${size}u`;
  23221. }
  23222. getDrawIndex() {
  23223. const extensions = this.renderer.backend.extensions;
  23224. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  23225. return 'uint( gl_DrawID )';
  23226. }
  23227. return null;
  23228. }
  23229. getFrontFacing() {
  23230. return 'gl_FrontFacing';
  23231. }
  23232. getFragCoord() {
  23233. return 'gl_FragCoord.xy';
  23234. }
  23235. getFragDepth() {
  23236. return 'gl_FragDepth';
  23237. }
  23238. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  23239. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  23240. if ( map.has( name ) === false ) {
  23241. map.set( name, {
  23242. name,
  23243. behavior
  23244. } );
  23245. }
  23246. }
  23247. getExtensions( shaderStage ) {
  23248. const snippets = [];
  23249. if ( shaderStage === 'vertex' ) {
  23250. const ext = this.renderer.backend.extensions;
  23251. const isBatchedMesh = this.object.isBatchedMesh;
  23252. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  23253. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  23254. }
  23255. }
  23256. const extensions = this.extensions[ shaderStage ];
  23257. if ( extensions !== undefined ) {
  23258. for ( const { name, behavior } of extensions.values() ) {
  23259. snippets.push( `#extension ${name} : ${behavior}` );
  23260. }
  23261. }
  23262. return snippets.join( '\n' );
  23263. }
  23264. getClipDistance() {
  23265. return 'gl_ClipDistance';
  23266. }
  23267. isAvailable( name ) {
  23268. let result = supports$1[ name ];
  23269. if ( result === undefined ) {
  23270. let extensionName;
  23271. result = false;
  23272. switch ( name ) {
  23273. case 'float32Filterable':
  23274. extensionName = 'OES_texture_float_linear';
  23275. break;
  23276. case 'clipDistance':
  23277. extensionName = 'WEBGL_clip_cull_distance';
  23278. break;
  23279. }
  23280. if ( extensionName !== undefined ) {
  23281. const extensions = this.renderer.backend.extensions;
  23282. if ( extensions.has( extensionName ) ) {
  23283. extensions.get( extensionName );
  23284. result = true;
  23285. }
  23286. }
  23287. supports$1[ name ] = result;
  23288. }
  23289. return result;
  23290. }
  23291. isFlipY() {
  23292. return true;
  23293. }
  23294. enableHardwareClipping( planeCount ) {
  23295. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  23296. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  23297. }
  23298. registerTransform( varyingName, attributeNode ) {
  23299. this.transforms.push( { varyingName, attributeNode } );
  23300. }
  23301. getTransforms( /* shaderStage */ ) {
  23302. const transforms = this.transforms;
  23303. let snippet = '';
  23304. for ( let i = 0; i < transforms.length; i ++ ) {
  23305. const transform = transforms[ i ];
  23306. const attributeName = this.getPropertyName( transform.attributeNode );
  23307. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  23308. }
  23309. return snippet;
  23310. }
  23311. _getGLSLUniformStruct( name, vars ) {
  23312. return `
  23313. layout( std140 ) uniform ${name} {
  23314. ${vars}
  23315. };`;
  23316. }
  23317. _getGLSLVertexCode( shaderData ) {
  23318. return `#version 300 es
  23319. ${ this.getSignature() }
  23320. // extensions
  23321. ${shaderData.extensions}
  23322. // precision
  23323. ${ defaultPrecisions }
  23324. // uniforms
  23325. ${shaderData.uniforms}
  23326. // varyings
  23327. ${shaderData.varyings}
  23328. // attributes
  23329. ${shaderData.attributes}
  23330. // codes
  23331. ${shaderData.codes}
  23332. void main() {
  23333. // vars
  23334. ${shaderData.vars}
  23335. // transforms
  23336. ${shaderData.transforms}
  23337. // flow
  23338. ${shaderData.flow}
  23339. gl_PointSize = 1.0;
  23340. }
  23341. `;
  23342. }
  23343. _getGLSLFragmentCode( shaderData ) {
  23344. return `#version 300 es
  23345. ${ this.getSignature() }
  23346. // precision
  23347. ${ defaultPrecisions }
  23348. // uniforms
  23349. ${shaderData.uniforms}
  23350. // varyings
  23351. ${shaderData.varyings}
  23352. // codes
  23353. ${shaderData.codes}
  23354. ${shaderData.structs}
  23355. void main() {
  23356. // vars
  23357. ${shaderData.vars}
  23358. // flow
  23359. ${shaderData.flow}
  23360. }
  23361. `;
  23362. }
  23363. buildCode() {
  23364. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  23365. this.sortBindingGroups();
  23366. for ( const shaderStage in shadersData ) {
  23367. let flow = '// code\n\n';
  23368. flow += this.flowCode[ shaderStage ];
  23369. const flowNodes = this.flowNodes[ shaderStage ];
  23370. const mainNode = flowNodes[ flowNodes.length - 1 ];
  23371. for ( const node of flowNodes ) {
  23372. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  23373. const slotName = node.name;
  23374. if ( slotName ) {
  23375. if ( flow.length > 0 ) flow += '\n';
  23376. flow += `\t// flow -> ${ slotName }\n\t`;
  23377. }
  23378. flow += `${ flowSlotData.code }\n\t`;
  23379. if ( node === mainNode && shaderStage !== 'compute' ) {
  23380. flow += '// result\n\t';
  23381. if ( shaderStage === 'vertex' ) {
  23382. flow += 'gl_Position = ';
  23383. flow += `${ flowSlotData.result };`;
  23384. } else if ( shaderStage === 'fragment' ) {
  23385. if ( ! node.outputNode.isOutputStructNode ) {
  23386. flow += 'fragColor = ';
  23387. flow += `${ flowSlotData.result };`;
  23388. }
  23389. }
  23390. }
  23391. }
  23392. const stageData = shadersData[ shaderStage ];
  23393. stageData.extensions = this.getExtensions( shaderStage );
  23394. stageData.uniforms = this.getUniforms( shaderStage );
  23395. stageData.attributes = this.getAttributes( shaderStage );
  23396. stageData.varyings = this.getVaryings( shaderStage );
  23397. stageData.vars = this.getVars( shaderStage );
  23398. stageData.structs = this.getStructs( shaderStage );
  23399. stageData.codes = this.getCodes( shaderStage );
  23400. stageData.transforms = this.getTransforms( shaderStage );
  23401. stageData.flow = flow;
  23402. }
  23403. if ( this.material !== null ) {
  23404. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  23405. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  23406. } else {
  23407. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  23408. }
  23409. }
  23410. getUniformFromNode( node, type, shaderStage, name = null ) {
  23411. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  23412. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  23413. let uniformGPU = nodeData.uniformGPU;
  23414. if ( uniformGPU === undefined ) {
  23415. const group = node.groupNode;
  23416. const groupName = group.name;
  23417. const bindings = this.getBindGroupArray( groupName, shaderStage );
  23418. if ( type === 'texture' ) {
  23419. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  23420. bindings.push( uniformGPU );
  23421. } else if ( type === 'cubeTexture' ) {
  23422. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  23423. bindings.push( uniformGPU );
  23424. } else if ( type === 'texture3D' ) {
  23425. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  23426. bindings.push( uniformGPU );
  23427. } else if ( type === 'buffer' ) {
  23428. node.name = `NodeBuffer_${ node.id }`;
  23429. uniformNode.name = `buffer${ node.id }`;
  23430. const buffer = new NodeUniformBuffer( node, group );
  23431. buffer.name = node.name;
  23432. bindings.push( buffer );
  23433. uniformGPU = buffer;
  23434. } else {
  23435. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  23436. let uniformsGroup = uniformsStage[ groupName ];
  23437. if ( uniformsGroup === undefined ) {
  23438. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  23439. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  23440. uniformsStage[ groupName ] = uniformsGroup;
  23441. bindings.push( uniformsGroup );
  23442. }
  23443. uniformGPU = this.getNodeUniform( uniformNode, type );
  23444. uniformsGroup.addUniform( uniformGPU );
  23445. }
  23446. nodeData.uniformGPU = uniformGPU;
  23447. }
  23448. return uniformNode;
  23449. }
  23450. }
  23451. let vector2 = null;
  23452. let vector4 = null;
  23453. let color4 = null;
  23454. class Backend {
  23455. constructor( parameters = {} ) {
  23456. this.parameters = Object.assign( {}, parameters );
  23457. this.data = new WeakMap();
  23458. this.renderer = null;
  23459. this.domElement = null;
  23460. }
  23461. async init( renderer ) {
  23462. this.renderer = renderer;
  23463. }
  23464. // render context
  23465. begin( /*renderContext*/ ) { }
  23466. finish( /*renderContext*/ ) { }
  23467. // render object
  23468. draw( /*renderObject, info*/ ) { }
  23469. // program
  23470. createProgram( /*program*/ ) { }
  23471. destroyProgram( /*program*/ ) { }
  23472. // bindings
  23473. createBindings( /*bingGroup, bindings*/ ) { }
  23474. updateBindings( /*bingGroup, bindings*/ ) { }
  23475. // pipeline
  23476. createRenderPipeline( /*renderObject*/ ) { }
  23477. createComputePipeline( /*computeNode, pipeline*/ ) { }
  23478. destroyPipeline( /*pipeline*/ ) { }
  23479. // cache key
  23480. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  23481. getRenderCacheKey( /*renderObject*/ ) { } // return String
  23482. // node builder
  23483. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  23484. // textures
  23485. createSampler( /*texture*/ ) { }
  23486. createDefaultTexture( /*texture*/ ) { }
  23487. createTexture( /*texture*/ ) { }
  23488. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  23489. // attributes
  23490. createAttribute( /*attribute*/ ) { }
  23491. createIndexAttribute( /*attribute*/ ) { }
  23492. updateAttribute( /*attribute*/ ) { }
  23493. destroyAttribute( /*attribute*/ ) { }
  23494. // canvas
  23495. getContext() { }
  23496. updateSize() { }
  23497. // utils
  23498. resolveTimestampAsync( /*renderContext, type*/ ) { }
  23499. hasFeatureAsync( /*name*/ ) { } // return Boolean
  23500. hasFeature( /*name*/ ) { } // return Boolean
  23501. getInstanceCount( renderObject ) {
  23502. const { object, geometry } = renderObject;
  23503. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  23504. }
  23505. getDrawingBufferSize() {
  23506. vector2 = vector2 || new Vector2();
  23507. return this.renderer.getDrawingBufferSize( vector2 );
  23508. }
  23509. getScissor() {
  23510. vector4 = vector4 || new Vector4();
  23511. return this.renderer.getScissor( vector4 );
  23512. }
  23513. setScissorTest( /*boolean*/ ) { }
  23514. getClearColor() {
  23515. const renderer = this.renderer;
  23516. color4 = color4 || new Color4();
  23517. renderer.getClearColor( color4 );
  23518. color4.getRGB( color4, this.renderer.currentColorSpace );
  23519. return color4;
  23520. }
  23521. getDomElement() {
  23522. let domElement = this.domElement;
  23523. if ( domElement === null ) {
  23524. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  23525. // OffscreenCanvas does not have setAttribute, see #22811
  23526. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  23527. this.domElement = domElement;
  23528. }
  23529. return domElement;
  23530. }
  23531. // resource properties
  23532. set( object, value ) {
  23533. this.data.set( object, value );
  23534. }
  23535. get( object ) {
  23536. let map = this.data.get( object );
  23537. if ( map === undefined ) {
  23538. map = {};
  23539. this.data.set( object, map );
  23540. }
  23541. return map;
  23542. }
  23543. has( object ) {
  23544. return this.data.has( object );
  23545. }
  23546. delete( object ) {
  23547. this.data.delete( object );
  23548. }
  23549. dispose() { }
  23550. }
  23551. let _id$1 = 0;
  23552. class DualAttributeData {
  23553. constructor( attributeData, dualBuffer ) {
  23554. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  23555. this.type = attributeData.type;
  23556. this.bufferType = attributeData.bufferType;
  23557. this.pbo = attributeData.pbo;
  23558. this.byteLength = attributeData.byteLength;
  23559. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  23560. this.version = attributeData.version;
  23561. this.isInteger = attributeData.isInteger;
  23562. this.activeBufferIndex = 0;
  23563. this.baseId = attributeData.id;
  23564. }
  23565. get id() {
  23566. return `${ this.baseId }|${ this.activeBufferIndex }`;
  23567. }
  23568. get bufferGPU() {
  23569. return this.buffers[ this.activeBufferIndex ];
  23570. }
  23571. get transformBuffer() {
  23572. return this.buffers[ this.activeBufferIndex ^ 1 ];
  23573. }
  23574. switchBuffers() {
  23575. this.activeBufferIndex ^= 1;
  23576. }
  23577. }
  23578. class WebGLAttributeUtils {
  23579. constructor( backend ) {
  23580. this.backend = backend;
  23581. }
  23582. createAttribute( attribute, bufferType ) {
  23583. const backend = this.backend;
  23584. const { gl } = backend;
  23585. const array = attribute.array;
  23586. const usage = attribute.usage || gl.STATIC_DRAW;
  23587. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  23588. const bufferData = backend.get( bufferAttribute );
  23589. let bufferGPU = bufferData.bufferGPU;
  23590. if ( bufferGPU === undefined ) {
  23591. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  23592. bufferData.bufferGPU = bufferGPU;
  23593. bufferData.bufferType = bufferType;
  23594. bufferData.version = bufferAttribute.version;
  23595. }
  23596. //attribute.onUploadCallback();
  23597. let type;
  23598. if ( array instanceof Float32Array ) {
  23599. type = gl.FLOAT;
  23600. } else if ( array instanceof Uint16Array ) {
  23601. if ( attribute.isFloat16BufferAttribute ) {
  23602. type = gl.HALF_FLOAT;
  23603. } else {
  23604. type = gl.UNSIGNED_SHORT;
  23605. }
  23606. } else if ( array instanceof Int16Array ) {
  23607. type = gl.SHORT;
  23608. } else if ( array instanceof Uint32Array ) {
  23609. type = gl.UNSIGNED_INT;
  23610. } else if ( array instanceof Int32Array ) {
  23611. type = gl.INT;
  23612. } else if ( array instanceof Int8Array ) {
  23613. type = gl.BYTE;
  23614. } else if ( array instanceof Uint8Array ) {
  23615. type = gl.UNSIGNED_BYTE;
  23616. } else if ( array instanceof Uint8ClampedArray ) {
  23617. type = gl.UNSIGNED_BYTE;
  23618. } else {
  23619. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  23620. }
  23621. let attributeData = {
  23622. bufferGPU,
  23623. bufferType,
  23624. type,
  23625. byteLength: array.byteLength,
  23626. bytesPerElement: array.BYTES_PER_ELEMENT,
  23627. version: attribute.version,
  23628. pbo: attribute.pbo,
  23629. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  23630. id: _id$1 ++
  23631. };
  23632. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  23633. // create buffer for tranform feedback use
  23634. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  23635. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  23636. }
  23637. backend.set( attribute, attributeData );
  23638. }
  23639. updateAttribute( attribute ) {
  23640. const backend = this.backend;
  23641. const { gl } = backend;
  23642. const array = attribute.array;
  23643. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  23644. const bufferData = backend.get( bufferAttribute );
  23645. const bufferType = bufferData.bufferType;
  23646. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  23647. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  23648. if ( updateRanges.length === 0 ) {
  23649. // Not using update ranges
  23650. gl.bufferSubData( bufferType, 0, array );
  23651. } else {
  23652. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  23653. const range = updateRanges[ i ];
  23654. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  23655. array, range.start, range.count );
  23656. }
  23657. bufferAttribute.clearUpdateRanges();
  23658. }
  23659. gl.bindBuffer( bufferType, null );
  23660. bufferData.version = bufferAttribute.version;
  23661. }
  23662. destroyAttribute( attribute ) {
  23663. const backend = this.backend;
  23664. const { gl } = backend;
  23665. if ( attribute.isInterleavedBufferAttribute ) {
  23666. backend.delete( attribute.data );
  23667. }
  23668. const attributeData = backend.get( attribute );
  23669. gl.deleteBuffer( attributeData.bufferGPU );
  23670. backend.delete( attribute );
  23671. }
  23672. async getArrayBufferAsync( attribute ) {
  23673. const backend = this.backend;
  23674. const { gl } = backend;
  23675. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  23676. const { bufferGPU } = backend.get( bufferAttribute );
  23677. const array = attribute.array;
  23678. const byteLength = array.byteLength;
  23679. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  23680. const writeBuffer = gl.createBuffer();
  23681. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  23682. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  23683. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  23684. await backend.utils._clientWaitAsync();
  23685. const dstBuffer = new attribute.array.constructor( array.length );
  23686. // Ensure the buffer is bound before reading
  23687. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  23688. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  23689. gl.deleteBuffer( writeBuffer );
  23690. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  23691. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  23692. return dstBuffer.buffer;
  23693. }
  23694. _createBuffer( gl, bufferType, array, usage ) {
  23695. const bufferGPU = gl.createBuffer();
  23696. gl.bindBuffer( bufferType, bufferGPU );
  23697. gl.bufferData( bufferType, array, usage );
  23698. gl.bindBuffer( bufferType, null );
  23699. return bufferGPU;
  23700. }
  23701. }
  23702. let initialized$1 = false, equationToGL, factorToGL;
  23703. class WebGLState {
  23704. constructor( backend ) {
  23705. this.backend = backend;
  23706. this.gl = this.backend.gl;
  23707. this.enabled = {};
  23708. this.currentFlipSided = null;
  23709. this.currentCullFace = null;
  23710. this.currentProgram = null;
  23711. this.currentBlendingEnabled = false;
  23712. this.currentBlending = null;
  23713. this.currentBlendSrc = null;
  23714. this.currentBlendDst = null;
  23715. this.currentBlendSrcAlpha = null;
  23716. this.currentBlendDstAlpha = null;
  23717. this.currentPremultipledAlpha = null;
  23718. this.currentPolygonOffsetFactor = null;
  23719. this.currentPolygonOffsetUnits = null;
  23720. this.currentColorMask = null;
  23721. this.currentDepthFunc = null;
  23722. this.currentDepthMask = null;
  23723. this.currentStencilFunc = null;
  23724. this.currentStencilRef = null;
  23725. this.currentStencilFuncMask = null;
  23726. this.currentStencilFail = null;
  23727. this.currentStencilZFail = null;
  23728. this.currentStencilZPass = null;
  23729. this.currentStencilMask = null;
  23730. this.currentLineWidth = null;
  23731. this.currentClippingPlanes = 0;
  23732. this.currentBoundFramebuffers = {};
  23733. this.currentDrawbuffers = new WeakMap();
  23734. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  23735. this.currentTextureSlot = null;
  23736. this.currentBoundTextures = {};
  23737. this.currentBoundBufferBases = {};
  23738. if ( initialized$1 === false ) {
  23739. this._init( this.gl );
  23740. initialized$1 = true;
  23741. }
  23742. }
  23743. _init( gl ) {
  23744. // Store only WebGL constants here.
  23745. equationToGL = {
  23746. [ AddEquation ]: gl.FUNC_ADD,
  23747. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  23748. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  23749. };
  23750. factorToGL = {
  23751. [ ZeroFactor ]: gl.ZERO,
  23752. [ OneFactor ]: gl.ONE,
  23753. [ SrcColorFactor ]: gl.SRC_COLOR,
  23754. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  23755. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  23756. [ DstColorFactor ]: gl.DST_COLOR,
  23757. [ DstAlphaFactor ]: gl.DST_ALPHA,
  23758. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  23759. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  23760. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  23761. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  23762. };
  23763. }
  23764. enable( id ) {
  23765. const { enabled } = this;
  23766. if ( enabled[ id ] !== true ) {
  23767. this.gl.enable( id );
  23768. enabled[ id ] = true;
  23769. }
  23770. }
  23771. disable( id ) {
  23772. const { enabled } = this;
  23773. if ( enabled[ id ] !== false ) {
  23774. this.gl.disable( id );
  23775. enabled[ id ] = false;
  23776. }
  23777. }
  23778. setFlipSided( flipSided ) {
  23779. if ( this.currentFlipSided !== flipSided ) {
  23780. const { gl } = this;
  23781. if ( flipSided ) {
  23782. gl.frontFace( gl.CW );
  23783. } else {
  23784. gl.frontFace( gl.CCW );
  23785. }
  23786. this.currentFlipSided = flipSided;
  23787. }
  23788. }
  23789. setCullFace( cullFace ) {
  23790. const { gl } = this;
  23791. if ( cullFace !== CullFaceNone ) {
  23792. this.enable( gl.CULL_FACE );
  23793. if ( cullFace !== this.currentCullFace ) {
  23794. if ( cullFace === CullFaceBack ) {
  23795. gl.cullFace( gl.BACK );
  23796. } else if ( cullFace === CullFaceFront ) {
  23797. gl.cullFace( gl.FRONT );
  23798. } else {
  23799. gl.cullFace( gl.FRONT_AND_BACK );
  23800. }
  23801. }
  23802. } else {
  23803. this.disable( gl.CULL_FACE );
  23804. }
  23805. this.currentCullFace = cullFace;
  23806. }
  23807. setLineWidth( width ) {
  23808. const { currentLineWidth, gl } = this;
  23809. if ( width !== currentLineWidth ) {
  23810. gl.lineWidth( width );
  23811. this.currentLineWidth = width;
  23812. }
  23813. }
  23814. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  23815. const { gl } = this;
  23816. if ( blending === NoBlending ) {
  23817. if ( this.currentBlendingEnabled === true ) {
  23818. this.disable( gl.BLEND );
  23819. this.currentBlendingEnabled = false;
  23820. }
  23821. return;
  23822. }
  23823. if ( this.currentBlendingEnabled === false ) {
  23824. this.enable( gl.BLEND );
  23825. this.currentBlendingEnabled = true;
  23826. }
  23827. if ( blending !== CustomBlending ) {
  23828. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  23829. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  23830. gl.blendEquation( gl.FUNC_ADD );
  23831. this.currentBlendEquation = AddEquation;
  23832. this.currentBlendEquationAlpha = AddEquation;
  23833. }
  23834. if ( premultipliedAlpha ) {
  23835. switch ( blending ) {
  23836. case NormalBlending:
  23837. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  23838. break;
  23839. case AdditiveBlending:
  23840. gl.blendFunc( gl.ONE, gl.ONE );
  23841. break;
  23842. case SubtractiveBlending:
  23843. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  23844. break;
  23845. case MultiplyBlending:
  23846. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  23847. break;
  23848. default:
  23849. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  23850. break;
  23851. }
  23852. } else {
  23853. switch ( blending ) {
  23854. case NormalBlending:
  23855. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  23856. break;
  23857. case AdditiveBlending:
  23858. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  23859. break;
  23860. case SubtractiveBlending:
  23861. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  23862. break;
  23863. case MultiplyBlending:
  23864. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  23865. break;
  23866. default:
  23867. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  23868. break;
  23869. }
  23870. }
  23871. this.currentBlendSrc = null;
  23872. this.currentBlendDst = null;
  23873. this.currentBlendSrcAlpha = null;
  23874. this.currentBlendDstAlpha = null;
  23875. this.currentBlending = blending;
  23876. this.currentPremultipledAlpha = premultipliedAlpha;
  23877. }
  23878. return;
  23879. }
  23880. // custom blending
  23881. blendEquationAlpha = blendEquationAlpha || blendEquation;
  23882. blendSrcAlpha = blendSrcAlpha || blendSrc;
  23883. blendDstAlpha = blendDstAlpha || blendDst;
  23884. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  23885. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  23886. this.currentBlendEquation = blendEquation;
  23887. this.currentBlendEquationAlpha = blendEquationAlpha;
  23888. }
  23889. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  23890. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  23891. this.currentBlendSrc = blendSrc;
  23892. this.currentBlendDst = blendDst;
  23893. this.currentBlendSrcAlpha = blendSrcAlpha;
  23894. this.currentBlendDstAlpha = blendDstAlpha;
  23895. }
  23896. this.currentBlending = blending;
  23897. this.currentPremultipledAlpha = false;
  23898. }
  23899. setColorMask( colorMask ) {
  23900. if ( this.currentColorMask !== colorMask ) {
  23901. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  23902. this.currentColorMask = colorMask;
  23903. }
  23904. }
  23905. setDepthTest( depthTest ) {
  23906. const { gl } = this;
  23907. if ( depthTest ) {
  23908. this.enable( gl.DEPTH_TEST );
  23909. } else {
  23910. this.disable( gl.DEPTH_TEST );
  23911. }
  23912. }
  23913. setDepthMask( depthMask ) {
  23914. if ( this.currentDepthMask !== depthMask ) {
  23915. this.gl.depthMask( depthMask );
  23916. this.currentDepthMask = depthMask;
  23917. }
  23918. }
  23919. setDepthFunc( depthFunc ) {
  23920. if ( this.currentDepthFunc !== depthFunc ) {
  23921. const { gl } = this;
  23922. switch ( depthFunc ) {
  23923. case NeverDepth:
  23924. gl.depthFunc( gl.NEVER );
  23925. break;
  23926. case AlwaysDepth:
  23927. gl.depthFunc( gl.ALWAYS );
  23928. break;
  23929. case LessDepth:
  23930. gl.depthFunc( gl.LESS );
  23931. break;
  23932. case LessEqualDepth:
  23933. gl.depthFunc( gl.LEQUAL );
  23934. break;
  23935. case EqualDepth:
  23936. gl.depthFunc( gl.EQUAL );
  23937. break;
  23938. case GreaterEqualDepth:
  23939. gl.depthFunc( gl.GEQUAL );
  23940. break;
  23941. case GreaterDepth:
  23942. gl.depthFunc( gl.GREATER );
  23943. break;
  23944. case NotEqualDepth:
  23945. gl.depthFunc( gl.NOTEQUAL );
  23946. break;
  23947. default:
  23948. gl.depthFunc( gl.LEQUAL );
  23949. }
  23950. this.currentDepthFunc = depthFunc;
  23951. }
  23952. }
  23953. setStencilTest( stencilTest ) {
  23954. const { gl } = this;
  23955. if ( stencilTest ) {
  23956. this.enable( gl.STENCIL_TEST );
  23957. } else {
  23958. this.disable( gl.STENCIL_TEST );
  23959. }
  23960. }
  23961. setStencilMask( stencilMask ) {
  23962. if ( this.currentStencilMask !== stencilMask ) {
  23963. this.gl.stencilMask( stencilMask );
  23964. this.currentStencilMask = stencilMask;
  23965. }
  23966. }
  23967. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  23968. if ( this.currentStencilFunc !== stencilFunc ||
  23969. this.currentStencilRef !== stencilRef ||
  23970. this.currentStencilFuncMask !== stencilMask ) {
  23971. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  23972. this.currentStencilFunc = stencilFunc;
  23973. this.currentStencilRef = stencilRef;
  23974. this.currentStencilFuncMask = stencilMask;
  23975. }
  23976. }
  23977. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  23978. if ( this.currentStencilFail !== stencilFail ||
  23979. this.currentStencilZFail !== stencilZFail ||
  23980. this.currentStencilZPass !== stencilZPass ) {
  23981. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  23982. this.currentStencilFail = stencilFail;
  23983. this.currentStencilZFail = stencilZFail;
  23984. this.currentStencilZPass = stencilZPass;
  23985. }
  23986. }
  23987. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  23988. const { gl } = this;
  23989. material.side === DoubleSide
  23990. ? this.disable( gl.CULL_FACE )
  23991. : this.enable( gl.CULL_FACE );
  23992. let flipSided = ( material.side === BackSide );
  23993. if ( frontFaceCW ) flipSided = ! flipSided;
  23994. this.setFlipSided( flipSided );
  23995. ( material.blending === NormalBlending && material.transparent === false )
  23996. ? this.setBlending( NoBlending )
  23997. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  23998. this.setDepthFunc( material.depthFunc );
  23999. this.setDepthTest( material.depthTest );
  24000. this.setDepthMask( material.depthWrite );
  24001. this.setColorMask( material.colorWrite );
  24002. const stencilWrite = material.stencilWrite;
  24003. this.setStencilTest( stencilWrite );
  24004. if ( stencilWrite ) {
  24005. this.setStencilMask( material.stencilWriteMask );
  24006. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  24007. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  24008. }
  24009. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  24010. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  24011. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  24012. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  24013. if ( hardwareClippingPlanes > 0 ) {
  24014. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  24015. const CLIP_DISTANCE0_WEBGL = 0x3000;
  24016. for ( let i = 0; i < 8; i ++ ) {
  24017. if ( i < hardwareClippingPlanes ) {
  24018. this.enable( CLIP_DISTANCE0_WEBGL + i );
  24019. } else {
  24020. this.disable( CLIP_DISTANCE0_WEBGL + i );
  24021. }
  24022. }
  24023. }
  24024. }
  24025. }
  24026. setPolygonOffset( polygonOffset, factor, units ) {
  24027. const { gl } = this;
  24028. if ( polygonOffset ) {
  24029. this.enable( gl.POLYGON_OFFSET_FILL );
  24030. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  24031. gl.polygonOffset( factor, units );
  24032. this.currentPolygonOffsetFactor = factor;
  24033. this.currentPolygonOffsetUnits = units;
  24034. }
  24035. } else {
  24036. this.disable( gl.POLYGON_OFFSET_FILL );
  24037. }
  24038. }
  24039. useProgram( program ) {
  24040. if ( this.currentProgram !== program ) {
  24041. this.gl.useProgram( program );
  24042. this.currentProgram = program;
  24043. return true;
  24044. }
  24045. return false;
  24046. }
  24047. // framebuffer
  24048. bindFramebuffer( target, framebuffer ) {
  24049. const { gl, currentBoundFramebuffers } = this;
  24050. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  24051. gl.bindFramebuffer( target, framebuffer );
  24052. currentBoundFramebuffers[ target ] = framebuffer;
  24053. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  24054. if ( target === gl.DRAW_FRAMEBUFFER ) {
  24055. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  24056. }
  24057. if ( target === gl.FRAMEBUFFER ) {
  24058. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  24059. }
  24060. return true;
  24061. }
  24062. return false;
  24063. }
  24064. drawBuffers( renderContext, framebuffer ) {
  24065. const { gl } = this;
  24066. let drawBuffers = [];
  24067. let needsUpdate = false;
  24068. if ( renderContext.textures !== null ) {
  24069. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  24070. if ( drawBuffers === undefined ) {
  24071. drawBuffers = [];
  24072. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  24073. }
  24074. const textures = renderContext.textures;
  24075. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  24076. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  24077. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  24078. }
  24079. drawBuffers.length = textures.length;
  24080. needsUpdate = true;
  24081. }
  24082. } else {
  24083. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  24084. drawBuffers[ 0 ] = gl.BACK;
  24085. needsUpdate = true;
  24086. }
  24087. }
  24088. if ( needsUpdate ) {
  24089. gl.drawBuffers( drawBuffers );
  24090. }
  24091. }
  24092. // texture
  24093. activeTexture( webglSlot ) {
  24094. const { gl, currentTextureSlot, maxTextures } = this;
  24095. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  24096. if ( currentTextureSlot !== webglSlot ) {
  24097. gl.activeTexture( webglSlot );
  24098. this.currentTextureSlot = webglSlot;
  24099. }
  24100. }
  24101. bindTexture( webglType, webglTexture, webglSlot ) {
  24102. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  24103. if ( webglSlot === undefined ) {
  24104. if ( currentTextureSlot === null ) {
  24105. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  24106. } else {
  24107. webglSlot = currentTextureSlot;
  24108. }
  24109. }
  24110. let boundTexture = currentBoundTextures[ webglSlot ];
  24111. if ( boundTexture === undefined ) {
  24112. boundTexture = { type: undefined, texture: undefined };
  24113. currentBoundTextures[ webglSlot ] = boundTexture;
  24114. }
  24115. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  24116. if ( currentTextureSlot !== webglSlot ) {
  24117. gl.activeTexture( webglSlot );
  24118. this.currentTextureSlot = webglSlot;
  24119. }
  24120. gl.bindTexture( webglType, webglTexture );
  24121. boundTexture.type = webglType;
  24122. boundTexture.texture = webglTexture;
  24123. }
  24124. }
  24125. bindBufferBase( target, index, buffer ) {
  24126. const { gl } = this;
  24127. const key = `${target}-${index}`;
  24128. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  24129. gl.bindBufferBase( target, index, buffer );
  24130. this.currentBoundBufferBases[ key ] = buffer;
  24131. return true;
  24132. }
  24133. return false;
  24134. }
  24135. unbindTexture() {
  24136. const { gl, currentTextureSlot, currentBoundTextures } = this;
  24137. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  24138. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  24139. gl.bindTexture( boundTexture.type, null );
  24140. boundTexture.type = undefined;
  24141. boundTexture.texture = undefined;
  24142. }
  24143. }
  24144. }
  24145. class WebGLUtils {
  24146. constructor( backend ) {
  24147. this.backend = backend;
  24148. this.gl = this.backend.gl;
  24149. this.extensions = backend.extensions;
  24150. }
  24151. convert( p, colorSpace = NoColorSpace ) {
  24152. const { gl, extensions } = this;
  24153. let extension;
  24154. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  24155. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  24156. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  24157. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  24158. if ( p === ByteType ) return gl.BYTE;
  24159. if ( p === ShortType ) return gl.SHORT;
  24160. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  24161. if ( p === IntType ) return gl.INT;
  24162. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  24163. if ( p === FloatType ) return gl.FLOAT;
  24164. if ( p === HalfFloatType ) {
  24165. return gl.HALF_FLOAT;
  24166. }
  24167. if ( p === AlphaFormat ) return gl.ALPHA;
  24168. if ( p === RGBFormat ) return gl.RGB;
  24169. if ( p === RGBAFormat ) return gl.RGBA;
  24170. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  24171. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  24172. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  24173. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  24174. // WebGL2 formats.
  24175. if ( p === RedFormat ) return gl.RED;
  24176. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  24177. if ( p === RGFormat ) return gl.RG;
  24178. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  24179. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  24180. // S3TC
  24181. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  24182. if ( colorSpace === SRGBColorSpace ) {
  24183. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  24184. if ( extension !== null ) {
  24185. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  24186. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  24187. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  24188. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  24189. } else {
  24190. return null;
  24191. }
  24192. } else {
  24193. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  24194. if ( extension !== null ) {
  24195. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  24196. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24197. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24198. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24199. } else {
  24200. return null;
  24201. }
  24202. }
  24203. }
  24204. // PVRTC
  24205. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  24206. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  24207. if ( extension !== null ) {
  24208. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  24209. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  24210. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  24211. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  24212. } else {
  24213. return null;
  24214. }
  24215. }
  24216. // ETC
  24217. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  24218. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  24219. if ( extension !== null ) {
  24220. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  24221. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  24222. } else {
  24223. return null;
  24224. }
  24225. }
  24226. // ASTC
  24227. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  24228. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  24229. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  24230. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  24231. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  24232. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  24233. if ( extension !== null ) {
  24234. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  24235. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  24236. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  24237. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  24238. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  24239. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  24240. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  24241. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  24242. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  24243. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  24244. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  24245. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  24246. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  24247. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  24248. } else {
  24249. return null;
  24250. }
  24251. }
  24252. // BPTC
  24253. if ( p === RGBA_BPTC_Format ) {
  24254. extension = extensions.get( 'EXT_texture_compression_bptc' );
  24255. if ( extension !== null ) {
  24256. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  24257. } else {
  24258. return null;
  24259. }
  24260. }
  24261. // RGTC
  24262. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  24263. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  24264. if ( extension !== null ) {
  24265. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  24266. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  24267. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  24268. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  24269. } else {
  24270. return null;
  24271. }
  24272. }
  24273. //
  24274. if ( p === UnsignedInt248Type ) {
  24275. return gl.UNSIGNED_INT_24_8;
  24276. }
  24277. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  24278. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  24279. }
  24280. _clientWaitAsync() {
  24281. const { gl } = this;
  24282. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  24283. gl.flush();
  24284. return new Promise( ( resolve, reject ) => {
  24285. function test() {
  24286. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  24287. if ( res === gl.WAIT_FAILED ) {
  24288. gl.deleteSync( sync );
  24289. reject();
  24290. return;
  24291. }
  24292. if ( res === gl.TIMEOUT_EXPIRED ) {
  24293. requestAnimationFrame( test );
  24294. return;
  24295. }
  24296. gl.deleteSync( sync );
  24297. resolve();
  24298. }
  24299. test();
  24300. } );
  24301. }
  24302. }
  24303. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  24304. class WebGLTextureUtils {
  24305. constructor( backend ) {
  24306. this.backend = backend;
  24307. this.gl = backend.gl;
  24308. this.extensions = backend.extensions;
  24309. this.defaultTextures = {};
  24310. if ( initialized === false ) {
  24311. this._init( this.gl );
  24312. initialized = true;
  24313. }
  24314. }
  24315. _init( gl ) {
  24316. // Store only WebGL constants here.
  24317. wrappingToGL = {
  24318. [ RepeatWrapping ]: gl.REPEAT,
  24319. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  24320. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  24321. };
  24322. filterToGL = {
  24323. [ NearestFilter ]: gl.NEAREST,
  24324. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  24325. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  24326. [ LinearFilter ]: gl.LINEAR,
  24327. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  24328. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  24329. };
  24330. compareToGL = {
  24331. [ NeverCompare ]: gl.NEVER,
  24332. [ AlwaysCompare ]: gl.ALWAYS,
  24333. [ LessCompare ]: gl.LESS,
  24334. [ LessEqualCompare ]: gl.LEQUAL,
  24335. [ EqualCompare ]: gl.EQUAL,
  24336. [ GreaterEqualCompare ]: gl.GEQUAL,
  24337. [ GreaterCompare ]: gl.GREATER,
  24338. [ NotEqualCompare ]: gl.NOTEQUAL
  24339. };
  24340. }
  24341. filterFallback( f ) {
  24342. const { gl } = this;
  24343. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  24344. return gl.NEAREST;
  24345. }
  24346. return gl.LINEAR;
  24347. }
  24348. getGLTextureType( texture ) {
  24349. const { gl } = this;
  24350. let glTextureType;
  24351. if ( texture.isCubeTexture === true ) {
  24352. glTextureType = gl.TEXTURE_CUBE_MAP;
  24353. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  24354. glTextureType = gl.TEXTURE_2D_ARRAY;
  24355. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  24356. glTextureType = gl.TEXTURE_3D;
  24357. } else {
  24358. glTextureType = gl.TEXTURE_2D;
  24359. }
  24360. return glTextureType;
  24361. }
  24362. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  24363. const { gl, extensions } = this;
  24364. if ( internalFormatName !== null ) {
  24365. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  24366. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  24367. }
  24368. let internalFormat = glFormat;
  24369. if ( glFormat === gl.RED ) {
  24370. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  24371. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  24372. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  24373. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  24374. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  24375. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  24376. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  24377. if ( glType === gl.INT ) internalFormat = gl.R32I;
  24378. }
  24379. if ( glFormat === gl.RED_INTEGER ) {
  24380. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  24381. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  24382. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  24383. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  24384. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  24385. if ( glType === gl.INT ) internalFormat = gl.R32I;
  24386. }
  24387. if ( glFormat === gl.RG ) {
  24388. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  24389. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  24390. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  24391. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  24392. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  24393. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  24394. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  24395. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  24396. }
  24397. if ( glFormat === gl.RG_INTEGER ) {
  24398. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  24399. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  24400. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  24401. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  24402. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  24403. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  24404. }
  24405. if ( glFormat === gl.RGB ) {
  24406. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  24407. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  24408. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  24409. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  24410. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  24411. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  24412. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  24413. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  24414. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  24415. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  24416. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  24417. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  24418. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  24419. }
  24420. if ( glFormat === gl.RGB_INTEGER ) {
  24421. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  24422. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  24423. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  24424. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  24425. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  24426. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  24427. }
  24428. if ( glFormat === gl.RGBA ) {
  24429. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  24430. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  24431. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  24432. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  24433. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  24434. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  24435. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  24436. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  24437. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  24438. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  24439. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  24440. }
  24441. if ( glFormat === gl.RGBA_INTEGER ) {
  24442. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  24443. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  24444. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  24445. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  24446. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  24447. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  24448. }
  24449. if ( glFormat === gl.DEPTH_COMPONENT ) {
  24450. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  24451. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  24452. }
  24453. if ( glFormat === gl.DEPTH_STENCIL ) {
  24454. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  24455. }
  24456. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  24457. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  24458. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  24459. extensions.get( 'EXT_color_buffer_float' );
  24460. }
  24461. return internalFormat;
  24462. }
  24463. setTextureParameters( textureType, texture ) {
  24464. const { gl, extensions, backend } = this;
  24465. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  24466. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  24467. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  24468. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  24469. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  24470. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  24471. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  24472. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  24473. }
  24474. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  24475. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  24476. // follow WebGPU backend mapping for texture filtering
  24477. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  24478. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  24479. if ( texture.compareFunction ) {
  24480. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  24481. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  24482. }
  24483. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  24484. if ( texture.magFilter === NearestFilter ) return;
  24485. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  24486. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  24487. if ( texture.anisotropy > 1 ) {
  24488. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  24489. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  24490. }
  24491. }
  24492. }
  24493. createDefaultTexture( texture ) {
  24494. const { gl, backend, defaultTextures } = this;
  24495. const glTextureType = this.getGLTextureType( texture );
  24496. let textureGPU = defaultTextures[ glTextureType ];
  24497. if ( textureGPU === undefined ) {
  24498. textureGPU = gl.createTexture();
  24499. backend.state.bindTexture( glTextureType, textureGPU );
  24500. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  24501. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  24502. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  24503. defaultTextures[ glTextureType ] = textureGPU;
  24504. }
  24505. backend.set( texture, {
  24506. textureGPU,
  24507. glTextureType,
  24508. isDefault: true
  24509. } );
  24510. }
  24511. createTexture( texture, options ) {
  24512. const { gl, backend } = this;
  24513. const { levels, width, height, depth } = options;
  24514. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  24515. const glType = backend.utils.convert( texture.type );
  24516. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  24517. const textureGPU = gl.createTexture();
  24518. const glTextureType = this.getGLTextureType( texture );
  24519. backend.state.bindTexture( glTextureType, textureGPU );
  24520. this.setTextureParameters( glTextureType, texture );
  24521. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  24522. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  24523. } else if ( texture.isData3DTexture ) {
  24524. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  24525. } else if ( ! texture.isVideoTexture ) {
  24526. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  24527. }
  24528. backend.set( texture, {
  24529. textureGPU,
  24530. glTextureType,
  24531. glFormat,
  24532. glType,
  24533. glInternalFormat
  24534. } );
  24535. }
  24536. copyBufferToTexture( buffer, texture ) {
  24537. const { gl, backend } = this;
  24538. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  24539. const { width, height } = texture.source.data;
  24540. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  24541. backend.state.bindTexture( glTextureType, textureGPU );
  24542. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  24543. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  24544. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  24545. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  24546. backend.state.unbindTexture();
  24547. // debug
  24548. // const framebuffer = gl.createFramebuffer();
  24549. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  24550. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  24551. // const readout = new Float32Array( width * height * 4 );
  24552. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  24553. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  24554. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  24555. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  24556. // console.log( readout );
  24557. }
  24558. updateTexture( texture, options ) {
  24559. const { gl } = this;
  24560. const { width, height } = options;
  24561. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  24562. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  24563. return;
  24564. const getImage = ( source ) => {
  24565. if ( source.isDataTexture ) {
  24566. return source.image.data;
  24567. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  24568. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  24569. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  24570. source instanceof OffscreenCanvas ) {
  24571. return source;
  24572. }
  24573. return source.data;
  24574. };
  24575. this.backend.state.bindTexture( glTextureType, textureGPU );
  24576. this.setTextureParameters( glTextureType, texture );
  24577. if ( texture.isCompressedTexture ) {
  24578. const mipmaps = texture.mipmaps;
  24579. const image = options.image;
  24580. for ( let i = 0; i < mipmaps.length; i ++ ) {
  24581. const mipmap = mipmaps[ i ];
  24582. if ( texture.isCompressedArrayTexture ) {
  24583. if ( texture.format !== gl.RGBA ) {
  24584. if ( glFormat !== null ) {
  24585. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  24586. } else {
  24587. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  24588. }
  24589. } else {
  24590. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  24591. }
  24592. } else {
  24593. if ( glFormat !== null ) {
  24594. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  24595. } else {
  24596. console.warn( 'Unsupported compressed texture format' );
  24597. }
  24598. }
  24599. }
  24600. } else if ( texture.isCubeTexture ) {
  24601. const images = options.images;
  24602. for ( let i = 0; i < 6; i ++ ) {
  24603. const image = getImage( images[ i ] );
  24604. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  24605. }
  24606. } else if ( texture.isDataArrayTexture ) {
  24607. const image = options.image;
  24608. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  24609. } else if ( texture.isData3DTexture ) {
  24610. const image = options.image;
  24611. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  24612. } else if ( texture.isVideoTexture ) {
  24613. texture.update();
  24614. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  24615. } else {
  24616. const image = getImage( options.image );
  24617. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  24618. }
  24619. }
  24620. generateMipmaps( texture ) {
  24621. const { gl, backend } = this;
  24622. const { textureGPU, glTextureType } = backend.get( texture );
  24623. backend.state.bindTexture( glTextureType, textureGPU );
  24624. gl.generateMipmap( glTextureType );
  24625. }
  24626. deallocateRenderBuffers( renderTarget ) {
  24627. const { gl, backend } = this;
  24628. // remove framebuffer reference
  24629. if ( renderTarget ) {
  24630. const renderContextData = backend.get( renderTarget );
  24631. renderContextData.renderBufferStorageSetup = undefined;
  24632. if ( renderContextData.framebuffers ) {
  24633. for ( const cacheKey in renderContextData.framebuffers ) {
  24634. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  24635. }
  24636. delete renderContextData.framebuffers;
  24637. }
  24638. if ( renderContextData.depthRenderbuffer ) {
  24639. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  24640. delete renderContextData.depthRenderbuffer;
  24641. }
  24642. if ( renderContextData.stencilRenderbuffer ) {
  24643. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  24644. delete renderContextData.stencilRenderbuffer;
  24645. }
  24646. if ( renderContextData.msaaFrameBuffer ) {
  24647. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  24648. delete renderContextData.msaaFrameBuffer;
  24649. }
  24650. if ( renderContextData.msaaRenderbuffers ) {
  24651. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  24652. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  24653. }
  24654. delete renderContextData.msaaRenderbuffers;
  24655. }
  24656. }
  24657. }
  24658. destroyTexture( texture ) {
  24659. const { gl, backend } = this;
  24660. const { textureGPU, renderTarget } = backend.get( texture );
  24661. this.deallocateRenderBuffers( renderTarget );
  24662. gl.deleteTexture( textureGPU );
  24663. backend.delete( texture );
  24664. }
  24665. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  24666. const { gl, backend } = this;
  24667. const { state } = this.backend;
  24668. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  24669. let width, height, minX, minY;
  24670. let dstX, dstY;
  24671. if ( srcRegion !== null ) {
  24672. width = srcRegion.max.x - srcRegion.min.x;
  24673. height = srcRegion.max.y - srcRegion.min.y;
  24674. minX = srcRegion.min.x;
  24675. minY = srcRegion.min.y;
  24676. } else {
  24677. width = srcTexture.image.width;
  24678. height = srcTexture.image.height;
  24679. minX = 0;
  24680. minY = 0;
  24681. }
  24682. if ( dstPosition !== null ) {
  24683. dstX = dstPosition.x;
  24684. dstY = dstPosition.y;
  24685. } else {
  24686. dstX = 0;
  24687. dstY = 0;
  24688. }
  24689. state.bindTexture( glTextureType, dstTextureGPU );
  24690. // As another texture upload may have changed pixelStorei
  24691. // parameters, make sure they are correct for the dstTexture
  24692. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  24693. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  24694. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  24695. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  24696. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  24697. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  24698. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  24699. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  24700. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  24701. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  24702. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  24703. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  24704. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  24705. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  24706. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  24707. const srcTextureData = backend.get( srcTexture );
  24708. const dstTextureData = backend.get( dstTexture );
  24709. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  24710. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  24711. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  24712. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  24713. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  24714. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  24715. let mask = gl.COLOR_BUFFER_BIT;
  24716. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  24717. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  24718. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  24719. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  24720. } else {
  24721. if ( srcTexture.isDataTexture ) {
  24722. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  24723. } else {
  24724. if ( srcTexture.isCompressedTexture ) {
  24725. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  24726. } else {
  24727. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  24728. }
  24729. }
  24730. }
  24731. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  24732. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  24733. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  24734. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  24735. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  24736. // Generate mipmaps only when copying level 0
  24737. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  24738. state.unbindTexture();
  24739. }
  24740. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  24741. const { gl } = this;
  24742. const { state } = this.backend;
  24743. const { textureGPU } = this.backend.get( texture );
  24744. const { x, y, z: width, w: height } = rectangle;
  24745. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  24746. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  24747. if ( requireDrawFrameBuffer ) {
  24748. const partial = ( x !== 0 || y !== 0 );
  24749. let mask;
  24750. let attachment;
  24751. if ( texture.isDepthTexture === true ) {
  24752. mask = gl.DEPTH_BUFFER_BIT;
  24753. attachment = gl.DEPTH_ATTACHMENT;
  24754. if ( renderContext.stencil ) {
  24755. mask |= gl.STENCIL_BUFFER_BIT;
  24756. }
  24757. } else {
  24758. mask = gl.COLOR_BUFFER_BIT;
  24759. attachment = gl.COLOR_ATTACHMENT0;
  24760. }
  24761. if ( partial ) {
  24762. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  24763. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  24764. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  24765. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  24766. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  24767. const flippedY = srcHeight - y - height;
  24768. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  24769. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  24770. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  24771. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  24772. state.unbindTexture();
  24773. } else {
  24774. const fb = gl.createFramebuffer();
  24775. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  24776. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  24777. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  24778. gl.deleteFramebuffer( fb );
  24779. }
  24780. } else {
  24781. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  24782. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  24783. state.unbindTexture();
  24784. }
  24785. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  24786. this.backend._setFramebuffer( renderContext );
  24787. }
  24788. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  24789. setupRenderBufferStorage( renderbuffer, renderContext ) {
  24790. const { gl } = this;
  24791. const renderTarget = renderContext.renderTarget;
  24792. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  24793. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  24794. if ( depthBuffer && ! stencilBuffer ) {
  24795. let glInternalFormat = gl.DEPTH_COMPONENT24;
  24796. if ( samples > 0 ) {
  24797. if ( depthTexture && depthTexture.isDepthTexture ) {
  24798. if ( depthTexture.type === gl.FLOAT ) {
  24799. glInternalFormat = gl.DEPTH_COMPONENT32F;
  24800. }
  24801. }
  24802. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  24803. } else {
  24804. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  24805. }
  24806. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  24807. } else if ( depthBuffer && stencilBuffer ) {
  24808. if ( samples > 0 ) {
  24809. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  24810. } else {
  24811. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  24812. }
  24813. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  24814. }
  24815. }
  24816. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  24817. const { backend, gl } = this;
  24818. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  24819. const fb = gl.createFramebuffer();
  24820. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  24821. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  24822. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  24823. const typedArrayType = this._getTypedArrayType( glType );
  24824. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  24825. const elementCount = width * height;
  24826. const byteLength = elementCount * bytesPerTexel;
  24827. const buffer = gl.createBuffer();
  24828. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  24829. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  24830. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  24831. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  24832. await backend.utils._clientWaitAsync();
  24833. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  24834. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  24835. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  24836. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  24837. gl.deleteFramebuffer( fb );
  24838. return dstBuffer;
  24839. }
  24840. _getTypedArrayType( glType ) {
  24841. const { gl } = this;
  24842. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  24843. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  24844. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  24845. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  24846. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  24847. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  24848. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  24849. if ( glType === gl.FLOAT ) return Float32Array;
  24850. throw new Error( `Unsupported WebGL type: ${glType}` );
  24851. }
  24852. _getBytesPerTexel( glType, glFormat ) {
  24853. const { gl } = this;
  24854. let bytesPerComponent = 0;
  24855. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  24856. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  24857. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  24858. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  24859. glType === gl.UNSIGNED_SHORT ||
  24860. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  24861. if ( glType === gl.UNSIGNED_INT ||
  24862. glType === gl.FLOAT ) bytesPerComponent = 4;
  24863. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  24864. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  24865. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  24866. }
  24867. }
  24868. class WebGLExtensions {
  24869. constructor( backend ) {
  24870. this.backend = backend;
  24871. this.gl = this.backend.gl;
  24872. this.availableExtensions = this.gl.getSupportedExtensions();
  24873. this.extensions = {};
  24874. }
  24875. get( name ) {
  24876. let extension = this.extensions[ name ];
  24877. if ( extension === undefined ) {
  24878. extension = this.gl.getExtension( name );
  24879. this.extensions[ name ] = extension;
  24880. }
  24881. return extension;
  24882. }
  24883. has( name ) {
  24884. return this.availableExtensions.includes( name );
  24885. }
  24886. }
  24887. class WebGLCapabilities {
  24888. constructor( backend ) {
  24889. this.backend = backend;
  24890. this.maxAnisotropy = null;
  24891. }
  24892. getMaxAnisotropy() {
  24893. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  24894. const gl = this.backend.gl;
  24895. const extensions = this.backend.extensions;
  24896. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  24897. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  24898. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  24899. } else {
  24900. this.maxAnisotropy = 0;
  24901. }
  24902. return this.maxAnisotropy;
  24903. }
  24904. }
  24905. const GLFeatureName = {
  24906. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  24907. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  24908. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  24909. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  24910. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  24911. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  24912. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  24913. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  24914. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  24915. };
  24916. class WebGLBufferRenderer {
  24917. constructor( backend ) {
  24918. this.gl = backend.gl;
  24919. this.extensions = backend.extensions;
  24920. this.info = backend.renderer.info;
  24921. this.mode = null;
  24922. this.index = 0;
  24923. this.type = null;
  24924. this.object = null;
  24925. }
  24926. render( start, count ) {
  24927. const { gl, mode, object, type, info, index } = this;
  24928. if ( index !== 0 ) {
  24929. gl.drawElements( mode, count, type, start );
  24930. } else {
  24931. gl.drawArrays( mode, start, count );
  24932. }
  24933. info.update( object, count, mode, 1 );
  24934. }
  24935. renderInstances( start, count, primcount ) {
  24936. const { gl, mode, type, index, object, info } = this;
  24937. if ( primcount === 0 ) return;
  24938. if ( index !== 0 ) {
  24939. gl.drawElementsInstanced( mode, count, type, start, primcount );
  24940. } else {
  24941. gl.drawArraysInstanced( mode, start, count, primcount );
  24942. }
  24943. info.update( object, count, mode, primcount );
  24944. }
  24945. renderMultiDraw( starts, counts, drawCount ) {
  24946. const { extensions, mode, object, info } = this;
  24947. if ( drawCount === 0 ) return;
  24948. const extension = extensions.get( 'WEBGL_multi_draw' );
  24949. if ( extension === null ) {
  24950. for ( let i = 0; i < drawCount; i ++ ) {
  24951. this.render( starts[ i ], counts[ i ] );
  24952. }
  24953. } else {
  24954. if ( this.index !== 0 ) {
  24955. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  24956. } else {
  24957. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  24958. }
  24959. let elementCount = 0;
  24960. for ( let i = 0; i < drawCount; i ++ ) {
  24961. elementCount += counts[ i ];
  24962. }
  24963. info.update( object, elementCount, mode, 1 );
  24964. }
  24965. }
  24966. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  24967. const { extensions, mode, object, info } = this;
  24968. if ( drawCount === 0 ) return;
  24969. const extension = extensions.get( 'WEBGL_multi_draw' );
  24970. if ( extension === null ) {
  24971. for ( let i = 0; i < drawCount; i ++ ) {
  24972. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  24973. }
  24974. } else {
  24975. if ( this.index !== 0 ) {
  24976. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  24977. } else {
  24978. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  24979. }
  24980. let elementCount = 0;
  24981. for ( let i = 0; i < drawCount; i ++ ) {
  24982. elementCount += counts[ i ] * primcount[ i ];
  24983. }
  24984. info.update( object, elementCount, mode, 1 );
  24985. }
  24986. }
  24987. //
  24988. }
  24989. //
  24990. class WebGLBackend extends Backend {
  24991. constructor( parameters = {} ) {
  24992. super( parameters );
  24993. this.isWebGLBackend = true;
  24994. }
  24995. init( renderer ) {
  24996. super.init( renderer );
  24997. //
  24998. const parameters = this.parameters;
  24999. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  25000. function onContextLost( event ) {
  25001. event.preventDefault();
  25002. const contextLossInfo = {
  25003. api: 'WebGL',
  25004. message: event.statusMessage || 'Unknown reason',
  25005. reason: null,
  25006. originalEvent: event
  25007. };
  25008. renderer.onDeviceLost( contextLossInfo );
  25009. }
  25010. this._onContextLost = onContextLost;
  25011. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  25012. this.gl = glContext;
  25013. this.extensions = new WebGLExtensions( this );
  25014. this.capabilities = new WebGLCapabilities( this );
  25015. this.attributeUtils = new WebGLAttributeUtils( this );
  25016. this.textureUtils = new WebGLTextureUtils( this );
  25017. this.bufferRenderer = new WebGLBufferRenderer( this );
  25018. this.state = new WebGLState( this );
  25019. this.utils = new WebGLUtils( this );
  25020. this.vaoCache = {};
  25021. this.transformFeedbackCache = {};
  25022. this.discard = false;
  25023. this.trackTimestamp = ( parameters.trackTimestamp === true );
  25024. this.extensions.get( 'EXT_color_buffer_float' );
  25025. this.extensions.get( 'WEBGL_clip_cull_distance' );
  25026. this.extensions.get( 'OES_texture_float_linear' );
  25027. this.extensions.get( 'EXT_color_buffer_half_float' );
  25028. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  25029. this.extensions.get( 'WEBGL_render_shared_exponent' );
  25030. this.extensions.get( 'WEBGL_multi_draw' );
  25031. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  25032. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  25033. this._knownBindings = new WeakSet();
  25034. this._currentContext = null;
  25035. }
  25036. get coordinateSystem() {
  25037. return WebGLCoordinateSystem;
  25038. }
  25039. async getArrayBufferAsync( attribute ) {
  25040. return await this.attributeUtils.getArrayBufferAsync( attribute );
  25041. }
  25042. async waitForGPU() {
  25043. await this.utils._clientWaitAsync();
  25044. }
  25045. initTimestampQuery( renderContext ) {
  25046. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25047. const renderContextData = this.get( renderContext );
  25048. if ( this.queryRunning ) {
  25049. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  25050. renderContextData.queryQueue.push( renderContext );
  25051. return;
  25052. }
  25053. if ( renderContextData.activeQuery ) {
  25054. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  25055. renderContextData.activeQuery = null;
  25056. }
  25057. renderContextData.activeQuery = this.gl.createQuery();
  25058. if ( renderContextData.activeQuery !== null ) {
  25059. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  25060. this.queryRunning = true;
  25061. }
  25062. }
  25063. // timestamp utils
  25064. prepareTimestampBuffer( renderContext ) {
  25065. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25066. const renderContextData = this.get( renderContext );
  25067. if ( renderContextData.activeQuery ) {
  25068. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  25069. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  25070. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  25071. renderContextData.activeQuery = null;
  25072. this.queryRunning = false;
  25073. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  25074. const nextRenderContext = renderContextData.queryQueue.shift();
  25075. this.initTimestampQuery( nextRenderContext );
  25076. }
  25077. }
  25078. }
  25079. async resolveTimestampAsync( renderContext, type = 'render' ) {
  25080. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25081. const renderContextData = this.get( renderContext );
  25082. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  25083. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  25084. const queryInfo = renderContextData.gpuQueries[ i ];
  25085. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  25086. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  25087. if ( available && ! disjoint ) {
  25088. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  25089. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  25090. this.gl.deleteQuery( queryInfo.query );
  25091. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  25092. i --;
  25093. this.renderer.info.updateTimestamp( type, duration );
  25094. }
  25095. }
  25096. }
  25097. getContext() {
  25098. return this.gl;
  25099. }
  25100. beginRender( renderContext ) {
  25101. const { gl } = this;
  25102. const renderContextData = this.get( renderContext );
  25103. //
  25104. //
  25105. this.initTimestampQuery( renderContext );
  25106. renderContextData.previousContext = this._currentContext;
  25107. this._currentContext = renderContext;
  25108. this._setFramebuffer( renderContext );
  25109. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  25110. //
  25111. if ( renderContext.viewport ) {
  25112. this.updateViewport( renderContext );
  25113. } else {
  25114. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  25115. }
  25116. if ( renderContext.scissor ) {
  25117. const { x, y, width, height } = renderContext.scissorValue;
  25118. gl.scissor( x, renderContext.height - height - y, width, height );
  25119. }
  25120. const occlusionQueryCount = renderContext.occlusionQueryCount;
  25121. if ( occlusionQueryCount > 0 ) {
  25122. // Get a reference to the array of objects with queries. The renderContextData property
  25123. // can be changed by another render pass before the async reading of all previous queries complete
  25124. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  25125. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  25126. renderContextData.lastOcclusionObject = null;
  25127. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  25128. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  25129. renderContextData.occlusionQueryIndex = 0;
  25130. }
  25131. }
  25132. finishRender( renderContext ) {
  25133. const { gl, state } = this;
  25134. const renderContextData = this.get( renderContext );
  25135. const previousContext = renderContextData.previousContext;
  25136. const occlusionQueryCount = renderContext.occlusionQueryCount;
  25137. if ( occlusionQueryCount > 0 ) {
  25138. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  25139. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  25140. }
  25141. this.resolveOccludedAsync( renderContext );
  25142. }
  25143. const textures = renderContext.textures;
  25144. if ( textures !== null ) {
  25145. for ( let i = 0; i < textures.length; i ++ ) {
  25146. const texture = textures[ i ];
  25147. if ( texture.generateMipmaps ) {
  25148. this.generateMipmaps( texture );
  25149. }
  25150. }
  25151. }
  25152. this._currentContext = previousContext;
  25153. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  25154. const renderTargetContextData = this.get( renderContext.renderTarget );
  25155. const { samples } = renderContext.renderTarget;
  25156. if ( samples > 0 ) {
  25157. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  25158. const mask = gl.COLOR_BUFFER_BIT;
  25159. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  25160. const textures = renderContext.textures;
  25161. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  25162. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  25163. for ( let i = 0; i < textures.length; i ++ ) {
  25164. // TODO Add support for MRT
  25165. if ( renderContext.scissor ) {
  25166. const { x, y, width, height } = renderContext.scissorValue;
  25167. const viewY = renderContext.height - height - y;
  25168. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  25169. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  25170. } else {
  25171. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  25172. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  25173. }
  25174. }
  25175. }
  25176. }
  25177. if ( previousContext !== null ) {
  25178. this._setFramebuffer( previousContext );
  25179. if ( previousContext.viewport ) {
  25180. this.updateViewport( previousContext );
  25181. } else {
  25182. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  25183. }
  25184. }
  25185. this.prepareTimestampBuffer( renderContext );
  25186. }
  25187. resolveOccludedAsync( renderContext ) {
  25188. const renderContextData = this.get( renderContext );
  25189. // handle occlusion query results
  25190. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  25191. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  25192. const occluded = new WeakSet();
  25193. const { gl } = this;
  25194. renderContextData.currentOcclusionQueryObjects = null;
  25195. renderContextData.currentOcclusionQueries = null;
  25196. const check = () => {
  25197. let completed = 0;
  25198. // check all queries and requeue as appropriate
  25199. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  25200. const query = currentOcclusionQueries[ i ];
  25201. if ( query === null ) continue;
  25202. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  25203. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  25204. currentOcclusionQueries[ i ] = null;
  25205. gl.deleteQuery( query );
  25206. completed ++;
  25207. }
  25208. }
  25209. if ( completed < currentOcclusionQueries.length ) {
  25210. requestAnimationFrame( check );
  25211. } else {
  25212. renderContextData.occluded = occluded;
  25213. }
  25214. };
  25215. check();
  25216. }
  25217. }
  25218. isOccluded( renderContext, object ) {
  25219. const renderContextData = this.get( renderContext );
  25220. return renderContextData.occluded && renderContextData.occluded.has( object );
  25221. }
  25222. updateViewport( renderContext ) {
  25223. const gl = this.gl;
  25224. const { x, y, width, height } = renderContext.viewportValue;
  25225. gl.viewport( x, renderContext.height - height - y, width, height );
  25226. }
  25227. setScissorTest( boolean ) {
  25228. const gl = this.gl;
  25229. if ( boolean ) {
  25230. gl.enable( gl.SCISSOR_TEST );
  25231. } else {
  25232. gl.disable( gl.SCISSOR_TEST );
  25233. }
  25234. }
  25235. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  25236. const { gl } = this;
  25237. if ( descriptor === null ) {
  25238. const clearColor = this.getClearColor();
  25239. // premultiply alpha
  25240. clearColor.r *= clearColor.a;
  25241. clearColor.g *= clearColor.a;
  25242. clearColor.b *= clearColor.a;
  25243. descriptor = {
  25244. textures: null,
  25245. clearColorValue: clearColor
  25246. };
  25247. }
  25248. //
  25249. let clear = 0;
  25250. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  25251. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  25252. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  25253. if ( clear !== 0 ) {
  25254. let clearColor;
  25255. if ( descriptor.clearColorValue ) {
  25256. clearColor = descriptor.clearColorValue;
  25257. } else {
  25258. clearColor = this.getClearColor();
  25259. // premultiply alpha
  25260. clearColor.r *= clearColor.a;
  25261. clearColor.g *= clearColor.a;
  25262. clearColor.b *= clearColor.a;
  25263. }
  25264. if ( depth ) this.state.setDepthMask( true );
  25265. if ( descriptor.textures === null ) {
  25266. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  25267. gl.clear( clear );
  25268. } else {
  25269. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  25270. if ( color ) {
  25271. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  25272. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  25273. }
  25274. }
  25275. if ( depth && stencil ) {
  25276. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  25277. } else if ( depth ) {
  25278. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  25279. } else if ( stencil ) {
  25280. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  25281. }
  25282. }
  25283. }
  25284. }
  25285. beginCompute( computeGroup ) {
  25286. const { state, gl } = this;
  25287. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  25288. this.initTimestampQuery( computeGroup );
  25289. }
  25290. compute( computeGroup, computeNode, bindings, pipeline ) {
  25291. const { state, gl } = this;
  25292. if ( ! this.discard ) {
  25293. // required here to handle async behaviour of render.compute()
  25294. gl.enable( gl.RASTERIZER_DISCARD );
  25295. this.discard = true;
  25296. }
  25297. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  25298. const vaoKey = this._getVaoKey( null, attributes );
  25299. const vaoGPU = this.vaoCache[ vaoKey ];
  25300. if ( vaoGPU === undefined ) {
  25301. this._createVao( null, attributes );
  25302. } else {
  25303. gl.bindVertexArray( vaoGPU );
  25304. }
  25305. state.useProgram( programGPU );
  25306. this._bindUniforms( bindings );
  25307. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  25308. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  25309. gl.beginTransformFeedback( gl.POINTS );
  25310. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  25311. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  25312. } else {
  25313. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  25314. }
  25315. gl.endTransformFeedback();
  25316. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  25317. // switch active buffers
  25318. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  25319. const dualAttributeData = transformBuffers[ i ];
  25320. if ( dualAttributeData.pbo ) {
  25321. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  25322. }
  25323. dualAttributeData.switchBuffers();
  25324. }
  25325. }
  25326. finishCompute( computeGroup ) {
  25327. const gl = this.gl;
  25328. this.discard = false;
  25329. gl.disable( gl.RASTERIZER_DISCARD );
  25330. this.prepareTimestampBuffer( computeGroup );
  25331. if ( this._currentContext ) {
  25332. this._setFramebuffer( this._currentContext );
  25333. }
  25334. }
  25335. draw( renderObject/*, info*/ ) {
  25336. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  25337. const { programGPU } = this.get( pipeline );
  25338. const { gl, state } = this;
  25339. const contextData = this.get( context );
  25340. const drawParams = renderObject.getDrawParameters();
  25341. if ( drawParams === null ) return;
  25342. //
  25343. this._bindUniforms( renderObject.getBindings() );
  25344. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  25345. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  25346. state.useProgram( programGPU );
  25347. //
  25348. const renderObjectData = this.get( renderObject );
  25349. let vaoGPU = renderObjectData.staticVao;
  25350. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  25351. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  25352. vaoGPU = this.vaoCache[ vaoKey ];
  25353. if ( vaoGPU === undefined ) {
  25354. let staticVao;
  25355. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  25356. if ( staticVao ) {
  25357. renderObjectData.staticVao = vaoGPU;
  25358. renderObjectData.geometryId = renderObject.geometry.id;
  25359. }
  25360. }
  25361. }
  25362. gl.bindVertexArray( vaoGPU );
  25363. //
  25364. const index = renderObject.getIndex();
  25365. //
  25366. const lastObject = contextData.lastOcclusionObject;
  25367. if ( lastObject !== object && lastObject !== undefined ) {
  25368. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  25369. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  25370. contextData.occlusionQueryIndex ++;
  25371. }
  25372. if ( object.occlusionTest === true ) {
  25373. const query = gl.createQuery();
  25374. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  25375. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  25376. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  25377. }
  25378. contextData.lastOcclusionObject = object;
  25379. }
  25380. //
  25381. const renderer = this.bufferRenderer;
  25382. if ( object.isPoints ) renderer.mode = gl.POINTS;
  25383. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  25384. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  25385. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  25386. else {
  25387. if ( material.wireframe === true ) {
  25388. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  25389. renderer.mode = gl.LINES;
  25390. } else {
  25391. renderer.mode = gl.TRIANGLES;
  25392. }
  25393. }
  25394. //
  25395. const { vertexCount, instanceCount } = drawParams;
  25396. let { firstVertex } = drawParams;
  25397. renderer.object = object;
  25398. if ( index !== null ) {
  25399. firstVertex *= index.array.BYTES_PER_ELEMENT;
  25400. const indexData = this.get( index );
  25401. renderer.index = index.count;
  25402. renderer.type = indexData.type;
  25403. } else {
  25404. renderer.index = 0;
  25405. }
  25406. if ( object.isBatchedMesh ) {
  25407. if ( object._multiDrawInstances !== null ) {
  25408. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  25409. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  25410. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  25411. } else {
  25412. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  25413. }
  25414. } else if ( instanceCount > 1 ) {
  25415. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  25416. } else {
  25417. renderer.render( firstVertex, vertexCount );
  25418. }
  25419. //
  25420. gl.bindVertexArray( null );
  25421. }
  25422. needsRenderUpdate( /*renderObject*/ ) {
  25423. return false;
  25424. }
  25425. getRenderCacheKey( /*renderObject*/ ) {
  25426. return '';
  25427. }
  25428. // textures
  25429. createDefaultTexture( texture ) {
  25430. this.textureUtils.createDefaultTexture( texture );
  25431. }
  25432. createTexture( texture, options ) {
  25433. this.textureUtils.createTexture( texture, options );
  25434. }
  25435. updateTexture( texture, options ) {
  25436. this.textureUtils.updateTexture( texture, options );
  25437. }
  25438. generateMipmaps( texture ) {
  25439. this.textureUtils.generateMipmaps( texture );
  25440. }
  25441. destroyTexture( texture ) {
  25442. this.textureUtils.destroyTexture( texture );
  25443. }
  25444. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  25445. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  25446. }
  25447. createSampler( /*texture*/ ) {
  25448. //console.warn( 'Abstract class.' );
  25449. }
  25450. destroySampler() {}
  25451. // node builder
  25452. createNodeBuilder( object, renderer ) {
  25453. return new GLSLNodeBuilder( object, renderer );
  25454. }
  25455. // program
  25456. createProgram( program ) {
  25457. const gl = this.gl;
  25458. const { stage, code } = program;
  25459. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  25460. gl.shaderSource( shader, code );
  25461. gl.compileShader( shader );
  25462. this.set( program, {
  25463. shaderGPU: shader
  25464. } );
  25465. }
  25466. destroyProgram( /*program*/ ) {
  25467. console.warn( 'Abstract class.' );
  25468. }
  25469. createRenderPipeline( renderObject, promises ) {
  25470. const gl = this.gl;
  25471. const pipeline = renderObject.pipeline;
  25472. // Program
  25473. const { fragmentProgram, vertexProgram } = pipeline;
  25474. const programGPU = gl.createProgram();
  25475. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  25476. const vertexShader = this.get( vertexProgram ).shaderGPU;
  25477. gl.attachShader( programGPU, fragmentShader );
  25478. gl.attachShader( programGPU, vertexShader );
  25479. gl.linkProgram( programGPU );
  25480. this.set( pipeline, {
  25481. programGPU,
  25482. fragmentShader,
  25483. vertexShader
  25484. } );
  25485. if ( promises !== null && this.parallel ) {
  25486. const p = new Promise( ( resolve /*, reject*/ ) => {
  25487. const parallel = this.parallel;
  25488. const checkStatus = () => {
  25489. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  25490. this._completeCompile( renderObject, pipeline );
  25491. resolve();
  25492. } else {
  25493. requestAnimationFrame( checkStatus );
  25494. }
  25495. };
  25496. checkStatus();
  25497. } );
  25498. promises.push( p );
  25499. return;
  25500. }
  25501. this._completeCompile( renderObject, pipeline );
  25502. }
  25503. _handleSource( string, errorLine ) {
  25504. const lines = string.split( '\n' );
  25505. const lines2 = [];
  25506. const from = Math.max( errorLine - 6, 0 );
  25507. const to = Math.min( errorLine + 6, lines.length );
  25508. for ( let i = from; i < to; i ++ ) {
  25509. const line = i + 1;
  25510. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  25511. }
  25512. return lines2.join( '\n' );
  25513. }
  25514. _getShaderErrors( gl, shader, type ) {
  25515. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  25516. const errors = gl.getShaderInfoLog( shader ).trim();
  25517. if ( status && errors === '' ) return '';
  25518. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  25519. if ( errorMatches ) {
  25520. const errorLine = parseInt( errorMatches[ 1 ] );
  25521. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  25522. } else {
  25523. return errors;
  25524. }
  25525. }
  25526. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  25527. if ( this.renderer.debug.checkShaderErrors ) {
  25528. const gl = this.gl;
  25529. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  25530. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  25531. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  25532. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  25533. } else {
  25534. // default error reporting
  25535. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  25536. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  25537. console.error(
  25538. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  25539. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  25540. 'Program Info Log: ' + programLog + '\n' +
  25541. vertexErrors + '\n' +
  25542. fragmentErrors
  25543. );
  25544. }
  25545. } else if ( programLog !== '' ) {
  25546. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  25547. }
  25548. }
  25549. }
  25550. _completeCompile( renderObject, pipeline ) {
  25551. const { state, gl } = this;
  25552. const pipelineData = this.get( pipeline );
  25553. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  25554. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  25555. this._logProgramError( programGPU, fragmentShader, vertexShader );
  25556. }
  25557. state.useProgram( programGPU );
  25558. // Bindings
  25559. const bindings = renderObject.getBindings();
  25560. this._setupBindings( bindings, programGPU );
  25561. //
  25562. this.set( pipeline, {
  25563. programGPU
  25564. } );
  25565. }
  25566. createComputePipeline( computePipeline, bindings ) {
  25567. const { state, gl } = this;
  25568. // Program
  25569. const fragmentProgram = {
  25570. stage: 'fragment',
  25571. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  25572. };
  25573. this.createProgram( fragmentProgram );
  25574. const { computeProgram } = computePipeline;
  25575. const programGPU = gl.createProgram();
  25576. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  25577. const vertexShader = this.get( computeProgram ).shaderGPU;
  25578. const transforms = computeProgram.transforms;
  25579. const transformVaryingNames = [];
  25580. const transformAttributeNodes = [];
  25581. for ( let i = 0; i < transforms.length; i ++ ) {
  25582. const transform = transforms[ i ];
  25583. transformVaryingNames.push( transform.varyingName );
  25584. transformAttributeNodes.push( transform.attributeNode );
  25585. }
  25586. gl.attachShader( programGPU, fragmentShader );
  25587. gl.attachShader( programGPU, vertexShader );
  25588. gl.transformFeedbackVaryings(
  25589. programGPU,
  25590. transformVaryingNames,
  25591. gl.SEPARATE_ATTRIBS
  25592. );
  25593. gl.linkProgram( programGPU );
  25594. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  25595. this._logProgramError( programGPU, fragmentShader, vertexShader );
  25596. }
  25597. state.useProgram( programGPU );
  25598. // Bindings
  25599. this._setupBindings( bindings, programGPU );
  25600. const attributeNodes = computeProgram.attributes;
  25601. const attributes = [];
  25602. const transformBuffers = [];
  25603. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  25604. const attribute = attributeNodes[ i ].node.attribute;
  25605. attributes.push( attribute );
  25606. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  25607. }
  25608. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  25609. const attribute = transformAttributeNodes[ i ].attribute;
  25610. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  25611. const attributeData = this.get( attribute );
  25612. transformBuffers.push( attributeData );
  25613. }
  25614. //
  25615. this.set( computePipeline, {
  25616. programGPU,
  25617. transformBuffers,
  25618. attributes
  25619. } );
  25620. }
  25621. createBindings( bindGroup, bindings ) {
  25622. if ( this._knownBindings.has( bindings ) === false ) {
  25623. this._knownBindings.add( bindings );
  25624. let uniformBuffers = 0;
  25625. let textures = 0;
  25626. for ( const bindGroup of bindings ) {
  25627. this.set( bindGroup, {
  25628. textures: textures,
  25629. uniformBuffers: uniformBuffers
  25630. } );
  25631. for ( const binding of bindGroup.bindings ) {
  25632. if ( binding.isUniformBuffer ) uniformBuffers ++;
  25633. if ( binding.isSampledTexture ) textures ++;
  25634. }
  25635. }
  25636. }
  25637. this.updateBindings( bindGroup, bindings );
  25638. }
  25639. updateBindings( bindGroup /*, bindings*/ ) {
  25640. const { gl } = this;
  25641. const bindGroupData = this.get( bindGroup );
  25642. let i = bindGroupData.uniformBuffers;
  25643. let t = bindGroupData.textures;
  25644. for ( const binding of bindGroup.bindings ) {
  25645. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  25646. const data = binding.buffer;
  25647. const bufferGPU = gl.createBuffer();
  25648. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  25649. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  25650. this.set( binding, {
  25651. index: i ++,
  25652. bufferGPU
  25653. } );
  25654. } else if ( binding.isSampledTexture ) {
  25655. const { textureGPU, glTextureType } = this.get( binding.texture );
  25656. this.set( binding, {
  25657. index: t ++,
  25658. textureGPU,
  25659. glTextureType
  25660. } );
  25661. }
  25662. }
  25663. }
  25664. updateBinding( binding ) {
  25665. const gl = this.gl;
  25666. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  25667. const bindingData = this.get( binding );
  25668. const bufferGPU = bindingData.bufferGPU;
  25669. const data = binding.buffer;
  25670. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  25671. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  25672. }
  25673. }
  25674. // attributes
  25675. createIndexAttribute( attribute ) {
  25676. const gl = this.gl;
  25677. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  25678. }
  25679. createAttribute( attribute ) {
  25680. if ( this.has( attribute ) ) return;
  25681. const gl = this.gl;
  25682. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  25683. }
  25684. createStorageAttribute( attribute ) {
  25685. if ( this.has( attribute ) ) return;
  25686. const gl = this.gl;
  25687. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  25688. }
  25689. updateAttribute( attribute ) {
  25690. this.attributeUtils.updateAttribute( attribute );
  25691. }
  25692. destroyAttribute( attribute ) {
  25693. this.attributeUtils.destroyAttribute( attribute );
  25694. }
  25695. updateSize() {
  25696. //console.warn( 'Abstract class.' );
  25697. }
  25698. hasFeature( name ) {
  25699. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  25700. const extensions = this.extensions;
  25701. for ( let i = 0; i < keysMatching.length; i ++ ) {
  25702. if ( extensions.has( keysMatching[ i ] ) ) return true;
  25703. }
  25704. return false;
  25705. }
  25706. getMaxAnisotropy() {
  25707. return this.capabilities.getMaxAnisotropy();
  25708. }
  25709. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  25710. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  25711. }
  25712. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  25713. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  25714. }
  25715. _setFramebuffer( descriptor ) {
  25716. const { gl, state } = this;
  25717. let currentFrameBuffer = null;
  25718. if ( descriptor.textures !== null ) {
  25719. const renderTarget = descriptor.renderTarget;
  25720. const renderTargetContextData = this.get( renderTarget );
  25721. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  25722. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  25723. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  25724. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  25725. const cacheKey = getCacheKey( descriptor );
  25726. let fb;
  25727. if ( isCube ) {
  25728. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  25729. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  25730. } else {
  25731. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  25732. fb = renderTargetContextData.framebuffers[ cacheKey ];
  25733. }
  25734. if ( fb === undefined ) {
  25735. fb = gl.createFramebuffer();
  25736. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  25737. const textures = descriptor.textures;
  25738. if ( isCube ) {
  25739. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  25740. const { textureGPU } = this.get( textures[ 0 ] );
  25741. const cubeFace = this.renderer._activeCubeFace;
  25742. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  25743. } else {
  25744. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  25745. for ( let i = 0; i < textures.length; i ++ ) {
  25746. const texture = textures[ i ];
  25747. const textureData = this.get( texture );
  25748. textureData.renderTarget = descriptor.renderTarget;
  25749. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  25750. const attachment = gl.COLOR_ATTACHMENT0 + i;
  25751. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  25752. }
  25753. state.drawBuffers( descriptor, fb );
  25754. }
  25755. if ( descriptor.depthTexture !== null ) {
  25756. const textureData = this.get( descriptor.depthTexture );
  25757. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  25758. textureData.renderTarget = descriptor.renderTarget;
  25759. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  25760. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  25761. }
  25762. }
  25763. if ( samples > 0 ) {
  25764. if ( msaaFb === undefined ) {
  25765. const invalidationArray = [];
  25766. msaaFb = gl.createFramebuffer();
  25767. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  25768. const msaaRenderbuffers = [];
  25769. const textures = descriptor.textures;
  25770. for ( let i = 0; i < textures.length; i ++ ) {
  25771. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  25772. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  25773. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  25774. if ( depthBuffer ) {
  25775. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  25776. invalidationArray.push( depthStyle );
  25777. }
  25778. const texture = descriptor.textures[ i ];
  25779. const textureData = this.get( texture );
  25780. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  25781. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  25782. }
  25783. renderTargetContextData.msaaFrameBuffer = msaaFb;
  25784. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  25785. if ( depthRenderbuffer === undefined ) {
  25786. depthRenderbuffer = gl.createRenderbuffer();
  25787. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  25788. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  25789. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  25790. invalidationArray.push( depthStyle );
  25791. }
  25792. renderTargetContextData.invalidationArray = invalidationArray;
  25793. }
  25794. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  25795. } else {
  25796. currentFrameBuffer = fb;
  25797. }
  25798. }
  25799. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  25800. }
  25801. _getVaoKey( index, attributes ) {
  25802. let key = [];
  25803. if ( index !== null ) {
  25804. const indexData = this.get( index );
  25805. key += ':' + indexData.id;
  25806. }
  25807. for ( let i = 0; i < attributes.length; i ++ ) {
  25808. const attributeData = this.get( attributes[ i ] );
  25809. key += ':' + attributeData.id;
  25810. }
  25811. return key;
  25812. }
  25813. _createVao( index, attributes ) {
  25814. const { gl } = this;
  25815. const vaoGPU = gl.createVertexArray();
  25816. let key = '';
  25817. let staticVao = true;
  25818. gl.bindVertexArray( vaoGPU );
  25819. if ( index !== null ) {
  25820. const indexData = this.get( index );
  25821. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  25822. key += ':' + indexData.id;
  25823. }
  25824. for ( let i = 0; i < attributes.length; i ++ ) {
  25825. const attribute = attributes[ i ];
  25826. const attributeData = this.get( attribute );
  25827. key += ':' + attributeData.id;
  25828. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  25829. gl.enableVertexAttribArray( i );
  25830. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  25831. let stride, offset;
  25832. if ( attribute.isInterleavedBufferAttribute === true ) {
  25833. stride = attribute.data.stride * attributeData.bytesPerElement;
  25834. offset = attribute.offset * attributeData.bytesPerElement;
  25835. } else {
  25836. stride = 0;
  25837. offset = 0;
  25838. }
  25839. if ( attributeData.isInteger ) {
  25840. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  25841. } else {
  25842. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  25843. }
  25844. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  25845. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  25846. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  25847. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  25848. }
  25849. }
  25850. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  25851. this.vaoCache[ key ] = vaoGPU;
  25852. return { vaoGPU, staticVao };
  25853. }
  25854. _getTransformFeedback( transformBuffers ) {
  25855. let key = '';
  25856. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  25857. key += ':' + transformBuffers[ i ].id;
  25858. }
  25859. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  25860. if ( transformFeedbackGPU !== undefined ) {
  25861. return transformFeedbackGPU;
  25862. }
  25863. const { gl } = this;
  25864. transformFeedbackGPU = gl.createTransformFeedback();
  25865. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  25866. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  25867. const attributeData = transformBuffers[ i ];
  25868. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  25869. }
  25870. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  25871. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  25872. return transformFeedbackGPU;
  25873. }
  25874. _setupBindings( bindings, programGPU ) {
  25875. const gl = this.gl;
  25876. for ( const bindGroup of bindings ) {
  25877. for ( const binding of bindGroup.bindings ) {
  25878. const bindingData = this.get( binding );
  25879. const index = bindingData.index;
  25880. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  25881. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  25882. gl.uniformBlockBinding( programGPU, location, index );
  25883. } else if ( binding.isSampledTexture ) {
  25884. const location = gl.getUniformLocation( programGPU, binding.name );
  25885. gl.uniform1i( location, index );
  25886. }
  25887. }
  25888. }
  25889. }
  25890. _bindUniforms( bindings ) {
  25891. const { gl, state } = this;
  25892. for ( const bindGroup of bindings ) {
  25893. for ( const binding of bindGroup.bindings ) {
  25894. const bindingData = this.get( binding );
  25895. const index = bindingData.index;
  25896. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  25897. // TODO USE bindBufferRange to group multiple uniform buffers
  25898. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  25899. } else if ( binding.isSampledTexture ) {
  25900. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  25901. }
  25902. }
  25903. }
  25904. }
  25905. dispose() {
  25906. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  25907. }
  25908. }
  25909. const GPUPrimitiveTopology = {
  25910. PointList: 'point-list',
  25911. LineList: 'line-list',
  25912. LineStrip: 'line-strip',
  25913. TriangleList: 'triangle-list',
  25914. TriangleStrip: 'triangle-strip',
  25915. };
  25916. const GPUCompareFunction = {
  25917. Never: 'never',
  25918. Less: 'less',
  25919. Equal: 'equal',
  25920. LessEqual: 'less-equal',
  25921. Greater: 'greater',
  25922. NotEqual: 'not-equal',
  25923. GreaterEqual: 'greater-equal',
  25924. Always: 'always'
  25925. };
  25926. const GPUStoreOp = {
  25927. Store: 'store',
  25928. Discard: 'discard'
  25929. };
  25930. const GPULoadOp = {
  25931. Load: 'load',
  25932. Clear: 'clear'
  25933. };
  25934. const GPUFrontFace = {
  25935. CCW: 'ccw',
  25936. CW: 'cw'
  25937. };
  25938. const GPUCullMode = {
  25939. None: 'none',
  25940. Front: 'front',
  25941. Back: 'back'
  25942. };
  25943. const GPUIndexFormat = {
  25944. Uint16: 'uint16',
  25945. Uint32: 'uint32'
  25946. };
  25947. const GPUTextureFormat = {
  25948. // 8-bit formats
  25949. R8Unorm: 'r8unorm',
  25950. R8Snorm: 'r8snorm',
  25951. R8Uint: 'r8uint',
  25952. R8Sint: 'r8sint',
  25953. // 16-bit formats
  25954. R16Uint: 'r16uint',
  25955. R16Sint: 'r16sint',
  25956. R16Float: 'r16float',
  25957. RG8Unorm: 'rg8unorm',
  25958. RG8Snorm: 'rg8snorm',
  25959. RG8Uint: 'rg8uint',
  25960. RG8Sint: 'rg8sint',
  25961. // 32-bit formats
  25962. R32Uint: 'r32uint',
  25963. R32Sint: 'r32sint',
  25964. R32Float: 'r32float',
  25965. RG16Uint: 'rg16uint',
  25966. RG16Sint: 'rg16sint',
  25967. RG16Float: 'rg16float',
  25968. RGBA8Unorm: 'rgba8unorm',
  25969. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  25970. RGBA8Snorm: 'rgba8snorm',
  25971. RGBA8Uint: 'rgba8uint',
  25972. RGBA8Sint: 'rgba8sint',
  25973. BGRA8Unorm: 'bgra8unorm',
  25974. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  25975. // Packed 32-bit formats
  25976. RGB9E5UFloat: 'rgb9e5ufloat',
  25977. RGB10A2Unorm: 'rgb10a2unorm',
  25978. RG11B10uFloat: 'rgb10a2unorm',
  25979. // 64-bit formats
  25980. RG32Uint: 'rg32uint',
  25981. RG32Sint: 'rg32sint',
  25982. RG32Float: 'rg32float',
  25983. RGBA16Uint: 'rgba16uint',
  25984. RGBA16Sint: 'rgba16sint',
  25985. RGBA16Float: 'rgba16float',
  25986. // 128-bit formats
  25987. RGBA32Uint: 'rgba32uint',
  25988. RGBA32Sint: 'rgba32sint',
  25989. RGBA32Float: 'rgba32float',
  25990. // Depth and stencil formats
  25991. Stencil8: 'stencil8',
  25992. Depth16Unorm: 'depth16unorm',
  25993. Depth24Plus: 'depth24plus',
  25994. Depth24PlusStencil8: 'depth24plus-stencil8',
  25995. Depth32Float: 'depth32float',
  25996. // 'depth32float-stencil8' extension
  25997. Depth32FloatStencil8: 'depth32float-stencil8',
  25998. // BC compressed formats usable if 'texture-compression-bc' is both
  25999. // supported by the device/user agent and enabled in requestDevice.
  26000. BC1RGBAUnorm: 'bc1-rgba-unorm',
  26001. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  26002. BC2RGBAUnorm: 'bc2-rgba-unorm',
  26003. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  26004. BC3RGBAUnorm: 'bc3-rgba-unorm',
  26005. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  26006. BC4RUnorm: 'bc4-r-unorm',
  26007. BC4RSnorm: 'bc4-r-snorm',
  26008. BC5RGUnorm: 'bc5-rg-unorm',
  26009. BC5RGSnorm: 'bc5-rg-snorm',
  26010. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  26011. BC6HRGBFloat: 'bc6h-rgb-float',
  26012. BC7RGBAUnorm: 'bc7-rgba-unorm',
  26013. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  26014. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  26015. // supported by the device/user agent and enabled in requestDevice.
  26016. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  26017. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  26018. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  26019. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  26020. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  26021. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  26022. EACR11Unorm: 'eac-r11unorm',
  26023. EACR11Snorm: 'eac-r11snorm',
  26024. EACRG11Unorm: 'eac-rg11unorm',
  26025. EACRG11Snorm: 'eac-rg11snorm',
  26026. // ASTC compressed formats usable if 'texture-compression-astc' is both
  26027. // supported by the device/user agent and enabled in requestDevice.
  26028. ASTC4x4Unorm: 'astc-4x4-unorm',
  26029. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  26030. ASTC5x4Unorm: 'astc-5x4-unorm',
  26031. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  26032. ASTC5x5Unorm: 'astc-5x5-unorm',
  26033. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  26034. ASTC6x5Unorm: 'astc-6x5-unorm',
  26035. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  26036. ASTC6x6Unorm: 'astc-6x6-unorm',
  26037. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  26038. ASTC8x5Unorm: 'astc-8x5-unorm',
  26039. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  26040. ASTC8x6Unorm: 'astc-8x6-unorm',
  26041. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  26042. ASTC8x8Unorm: 'astc-8x8-unorm',
  26043. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  26044. ASTC10x5Unorm: 'astc-10x5-unorm',
  26045. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  26046. ASTC10x6Unorm: 'astc-10x6-unorm',
  26047. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  26048. ASTC10x8Unorm: 'astc-10x8-unorm',
  26049. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  26050. ASTC10x10Unorm: 'astc-10x10-unorm',
  26051. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  26052. ASTC12x10Unorm: 'astc-12x10-unorm',
  26053. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  26054. ASTC12x12Unorm: 'astc-12x12-unorm',
  26055. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  26056. };
  26057. const GPUAddressMode = {
  26058. ClampToEdge: 'clamp-to-edge',
  26059. Repeat: 'repeat',
  26060. MirrorRepeat: 'mirror-repeat'
  26061. };
  26062. const GPUFilterMode = {
  26063. Linear: 'linear',
  26064. Nearest: 'nearest'
  26065. };
  26066. const GPUBlendFactor = {
  26067. Zero: 'zero',
  26068. One: 'one',
  26069. Src: 'src',
  26070. OneMinusSrc: 'one-minus-src',
  26071. SrcAlpha: 'src-alpha',
  26072. OneMinusSrcAlpha: 'one-minus-src-alpha',
  26073. Dst: 'dst',
  26074. OneMinusDstColor: 'one-minus-dst',
  26075. DstAlpha: 'dst-alpha',
  26076. OneMinusDstAlpha: 'one-minus-dst-alpha',
  26077. SrcAlphaSaturated: 'src-alpha-saturated',
  26078. Constant: 'constant',
  26079. OneMinusConstant: 'one-minus-constant'
  26080. };
  26081. const GPUBlendOperation = {
  26082. Add: 'add',
  26083. Subtract: 'subtract',
  26084. ReverseSubtract: 'reverse-subtract',
  26085. Min: 'min',
  26086. Max: 'max'
  26087. };
  26088. const GPUColorWriteFlags = {
  26089. None: 0,
  26090. Red: 0x1,
  26091. Green: 0x2,
  26092. Blue: 0x4,
  26093. Alpha: 0x8,
  26094. All: 0xF
  26095. };
  26096. const GPUStencilOperation = {
  26097. Keep: 'keep',
  26098. Zero: 'zero',
  26099. Replace: 'replace',
  26100. Invert: 'invert',
  26101. IncrementClamp: 'increment-clamp',
  26102. DecrementClamp: 'decrement-clamp',
  26103. IncrementWrap: 'increment-wrap',
  26104. DecrementWrap: 'decrement-wrap'
  26105. };
  26106. const GPUBufferBindingType = {
  26107. Uniform: 'uniform',
  26108. Storage: 'storage',
  26109. ReadOnlyStorage: 'read-only-storage'
  26110. };
  26111. const GPUStorageTextureAccess = {
  26112. WriteOnly: 'write-only',
  26113. ReadOnly: 'read-only',
  26114. ReadWrite: 'read-write',
  26115. };
  26116. const GPUTextureSampleType = {
  26117. Float: 'float',
  26118. UnfilterableFloat: 'unfilterable-float',
  26119. Depth: 'depth',
  26120. SInt: 'sint',
  26121. UInt: 'uint'
  26122. };
  26123. const GPUTextureDimension = {
  26124. OneD: '1d',
  26125. TwoD: '2d',
  26126. ThreeD: '3d'
  26127. };
  26128. const GPUTextureViewDimension = {
  26129. OneD: '1d',
  26130. TwoD: '2d',
  26131. TwoDArray: '2d-array',
  26132. Cube: 'cube',
  26133. CubeArray: 'cube-array',
  26134. ThreeD: '3d'
  26135. };
  26136. const GPUTextureAspect = {
  26137. All: 'all',
  26138. StencilOnly: 'stencil-only',
  26139. DepthOnly: 'depth-only'
  26140. };
  26141. const GPUInputStepMode = {
  26142. Vertex: 'vertex',
  26143. Instance: 'instance'
  26144. };
  26145. const GPUFeatureName = {
  26146. DepthClipControl: 'depth-clip-control',
  26147. Depth32FloatStencil8: 'depth32float-stencil8',
  26148. TextureCompressionBC: 'texture-compression-bc',
  26149. TextureCompressionETC2: 'texture-compression-etc2',
  26150. TextureCompressionASTC: 'texture-compression-astc',
  26151. TimestampQuery: 'timestamp-query',
  26152. IndirectFirstInstance: 'indirect-first-instance',
  26153. ShaderF16: 'shader-f16',
  26154. RG11B10UFloat: 'rg11b10ufloat-renderable',
  26155. BGRA8UNormStorage: 'bgra8unorm-storage',
  26156. Float32Filterable: 'float32-filterable',
  26157. ClipDistances: 'clip-distances',
  26158. DualSourceBlending: 'dual-source-blending',
  26159. Subgroups: 'subgroups'
  26160. };
  26161. class Sampler extends Binding {
  26162. constructor( name, texture ) {
  26163. super( name );
  26164. this.texture = texture;
  26165. this.version = texture ? texture.version : 0;
  26166. this.isSampler = true;
  26167. }
  26168. }
  26169. class NodeSampler extends Sampler {
  26170. constructor( name, textureNode, groupNode ) {
  26171. super( name, textureNode ? textureNode.value : null );
  26172. this.textureNode = textureNode;
  26173. this.groupNode = groupNode;
  26174. }
  26175. update() {
  26176. this.texture = this.textureNode.value;
  26177. }
  26178. }
  26179. class StorageBuffer extends Buffer {
  26180. constructor( name, attribute ) {
  26181. super( name, attribute ? attribute.array : null );
  26182. this.attribute = attribute;
  26183. this.isStorageBuffer = true;
  26184. }
  26185. }
  26186. let _id = 0;
  26187. class NodeStorageBuffer extends StorageBuffer {
  26188. constructor( nodeUniform, groupNode ) {
  26189. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  26190. this.nodeUniform = nodeUniform;
  26191. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  26192. this.groupNode = groupNode;
  26193. }
  26194. get buffer() {
  26195. return this.nodeUniform.value;
  26196. }
  26197. }
  26198. class WebGPUTexturePassUtils extends DataMap {
  26199. constructor( device ) {
  26200. super();
  26201. this.device = device;
  26202. const mipmapVertexSource = `
  26203. struct VarysStruct {
  26204. @builtin( position ) Position: vec4<f32>,
  26205. @location( 0 ) vTex : vec2<f32>
  26206. };
  26207. @vertex
  26208. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  26209. var Varys : VarysStruct;
  26210. var pos = array< vec2<f32>, 4 >(
  26211. vec2<f32>( -1.0, 1.0 ),
  26212. vec2<f32>( 1.0, 1.0 ),
  26213. vec2<f32>( -1.0, -1.0 ),
  26214. vec2<f32>( 1.0, -1.0 )
  26215. );
  26216. var tex = array< vec2<f32>, 4 >(
  26217. vec2<f32>( 0.0, 0.0 ),
  26218. vec2<f32>( 1.0, 0.0 ),
  26219. vec2<f32>( 0.0, 1.0 ),
  26220. vec2<f32>( 1.0, 1.0 )
  26221. );
  26222. Varys.vTex = tex[ vertexIndex ];
  26223. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  26224. return Varys;
  26225. }
  26226. `;
  26227. const mipmapFragmentSource = `
  26228. @group( 0 ) @binding( 0 )
  26229. var imgSampler : sampler;
  26230. @group( 0 ) @binding( 1 )
  26231. var img : texture_2d<f32>;
  26232. @fragment
  26233. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  26234. return textureSample( img, imgSampler, vTex );
  26235. }
  26236. `;
  26237. const flipYFragmentSource = `
  26238. @group( 0 ) @binding( 0 )
  26239. var imgSampler : sampler;
  26240. @group( 0 ) @binding( 1 )
  26241. var img : texture_2d<f32>;
  26242. @fragment
  26243. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  26244. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  26245. }
  26246. `;
  26247. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  26248. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  26249. // We'll need a new pipeline for every texture format used.
  26250. this.transferPipelines = {};
  26251. this.flipYPipelines = {};
  26252. this.mipmapVertexShaderModule = device.createShaderModule( {
  26253. label: 'mipmapVertex',
  26254. code: mipmapVertexSource
  26255. } );
  26256. this.mipmapFragmentShaderModule = device.createShaderModule( {
  26257. label: 'mipmapFragment',
  26258. code: mipmapFragmentSource
  26259. } );
  26260. this.flipYFragmentShaderModule = device.createShaderModule( {
  26261. label: 'flipYFragment',
  26262. code: flipYFragmentSource
  26263. } );
  26264. }
  26265. getTransferPipeline( format ) {
  26266. let pipeline = this.transferPipelines[ format ];
  26267. if ( pipeline === undefined ) {
  26268. pipeline = this.device.createRenderPipeline( {
  26269. label: `mipmap-${ format }`,
  26270. vertex: {
  26271. module: this.mipmapVertexShaderModule,
  26272. entryPoint: 'main'
  26273. },
  26274. fragment: {
  26275. module: this.mipmapFragmentShaderModule,
  26276. entryPoint: 'main',
  26277. targets: [ { format } ]
  26278. },
  26279. primitive: {
  26280. topology: GPUPrimitiveTopology.TriangleStrip,
  26281. stripIndexFormat: GPUIndexFormat.Uint32
  26282. },
  26283. layout: 'auto'
  26284. } );
  26285. this.transferPipelines[ format ] = pipeline;
  26286. }
  26287. return pipeline;
  26288. }
  26289. getFlipYPipeline( format ) {
  26290. let pipeline = this.flipYPipelines[ format ];
  26291. if ( pipeline === undefined ) {
  26292. pipeline = this.device.createRenderPipeline( {
  26293. label: `flipY-${ format }`,
  26294. vertex: {
  26295. module: this.mipmapVertexShaderModule,
  26296. entryPoint: 'main'
  26297. },
  26298. fragment: {
  26299. module: this.flipYFragmentShaderModule,
  26300. entryPoint: 'main',
  26301. targets: [ { format } ]
  26302. },
  26303. primitive: {
  26304. topology: GPUPrimitiveTopology.TriangleStrip,
  26305. stripIndexFormat: GPUIndexFormat.Uint32
  26306. },
  26307. layout: 'auto'
  26308. } );
  26309. this.flipYPipelines[ format ] = pipeline;
  26310. }
  26311. return pipeline;
  26312. }
  26313. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  26314. const format = textureGPUDescriptor.format;
  26315. const { width, height } = textureGPUDescriptor.size;
  26316. const transferPipeline = this.getTransferPipeline( format );
  26317. const flipYPipeline = this.getFlipYPipeline( format );
  26318. const tempTexture = this.device.createTexture( {
  26319. size: { width, height, depthOrArrayLayers: 1 },
  26320. format,
  26321. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  26322. } );
  26323. const srcView = textureGPU.createView( {
  26324. baseMipLevel: 0,
  26325. mipLevelCount: 1,
  26326. dimension: GPUTextureViewDimension.TwoD,
  26327. baseArrayLayer
  26328. } );
  26329. const dstView = tempTexture.createView( {
  26330. baseMipLevel: 0,
  26331. mipLevelCount: 1,
  26332. dimension: GPUTextureViewDimension.TwoD,
  26333. baseArrayLayer: 0
  26334. } );
  26335. const commandEncoder = this.device.createCommandEncoder( {} );
  26336. const pass = ( pipeline, sourceView, destinationView ) => {
  26337. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  26338. const bindGroup = this.device.createBindGroup( {
  26339. layout: bindGroupLayout,
  26340. entries: [ {
  26341. binding: 0,
  26342. resource: this.flipYSampler
  26343. }, {
  26344. binding: 1,
  26345. resource: sourceView
  26346. } ]
  26347. } );
  26348. const passEncoder = commandEncoder.beginRenderPass( {
  26349. colorAttachments: [ {
  26350. view: destinationView,
  26351. loadOp: GPULoadOp.Clear,
  26352. storeOp: GPUStoreOp.Store,
  26353. clearValue: [ 0, 0, 0, 0 ]
  26354. } ]
  26355. } );
  26356. passEncoder.setPipeline( pipeline );
  26357. passEncoder.setBindGroup( 0, bindGroup );
  26358. passEncoder.draw( 4, 1, 0, 0 );
  26359. passEncoder.end();
  26360. };
  26361. pass( transferPipeline, srcView, dstView );
  26362. pass( flipYPipeline, dstView, srcView );
  26363. this.device.queue.submit( [ commandEncoder.finish() ] );
  26364. tempTexture.destroy();
  26365. }
  26366. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  26367. const textureData = this.get( textureGPU );
  26368. if ( textureData.useCount === undefined ) {
  26369. textureData.useCount = 0;
  26370. textureData.layers = [];
  26371. }
  26372. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  26373. const commandEncoder = this.device.createCommandEncoder( {} );
  26374. this._mipmapRunBundles( commandEncoder, passes );
  26375. this.device.queue.submit( [ commandEncoder.finish() ] );
  26376. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  26377. textureData.useCount ++;
  26378. }
  26379. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  26380. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  26381. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  26382. let srcView = textureGPU.createView( {
  26383. baseMipLevel: 0,
  26384. mipLevelCount: 1,
  26385. dimension: GPUTextureViewDimension.TwoD,
  26386. baseArrayLayer
  26387. } );
  26388. const passes = [];
  26389. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  26390. const bindGroup = this.device.createBindGroup( {
  26391. layout: bindGroupLayout,
  26392. entries: [ {
  26393. binding: 0,
  26394. resource: this.mipmapSampler
  26395. }, {
  26396. binding: 1,
  26397. resource: srcView
  26398. } ]
  26399. } );
  26400. const dstView = textureGPU.createView( {
  26401. baseMipLevel: i,
  26402. mipLevelCount: 1,
  26403. dimension: GPUTextureViewDimension.TwoD,
  26404. baseArrayLayer
  26405. } );
  26406. const passDescriptor = {
  26407. colorAttachments: [ {
  26408. view: dstView,
  26409. loadOp: GPULoadOp.Clear,
  26410. storeOp: GPUStoreOp.Store,
  26411. clearValue: [ 0, 0, 0, 0 ]
  26412. } ]
  26413. };
  26414. const passEncoder = this.device.createRenderBundleEncoder( {
  26415. colorFormats: [ textureGPUDescriptor.format ]
  26416. } );
  26417. passEncoder.setPipeline( pipeline );
  26418. passEncoder.setBindGroup( 0, bindGroup );
  26419. passEncoder.draw( 4, 1, 0, 0 );
  26420. passes.push( {
  26421. renderBundles: [ passEncoder.finish() ],
  26422. passDescriptor
  26423. } );
  26424. srcView = dstView;
  26425. }
  26426. return passes;
  26427. }
  26428. _mipmapRunBundles( commandEncoder, passes ) {
  26429. const levels = passes.length;
  26430. for ( let i = 0; i < levels; i ++ ) {
  26431. const pass = passes[ i ];
  26432. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  26433. passEncoder.executeBundles( pass.renderBundles );
  26434. passEncoder.end();
  26435. }
  26436. }
  26437. }
  26438. const _compareToWebGPU = {
  26439. [ NeverCompare ]: 'never',
  26440. [ LessCompare ]: 'less',
  26441. [ EqualCompare ]: 'equal',
  26442. [ LessEqualCompare ]: 'less-equal',
  26443. [ GreaterCompare ]: 'greater',
  26444. [ GreaterEqualCompare ]: 'greater-equal',
  26445. [ AlwaysCompare ]: 'always',
  26446. [ NotEqualCompare ]: 'not-equal'
  26447. };
  26448. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  26449. class WebGPUTextureUtils {
  26450. constructor( backend ) {
  26451. this.backend = backend;
  26452. this._passUtils = null;
  26453. this.defaultTexture = {};
  26454. this.defaultCubeTexture = {};
  26455. this.defaultVideoFrame = null;
  26456. this.colorBuffer = null;
  26457. this.depthTexture = new DepthTexture();
  26458. this.depthTexture.name = 'depthBuffer';
  26459. }
  26460. createSampler( texture ) {
  26461. const backend = this.backend;
  26462. const device = backend.device;
  26463. const textureGPU = backend.get( texture );
  26464. const samplerDescriptorGPU = {
  26465. addressModeU: this._convertAddressMode( texture.wrapS ),
  26466. addressModeV: this._convertAddressMode( texture.wrapT ),
  26467. addressModeW: this._convertAddressMode( texture.wrapR ),
  26468. magFilter: this._convertFilterMode( texture.magFilter ),
  26469. minFilter: this._convertFilterMode( texture.minFilter ),
  26470. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  26471. maxAnisotropy: 1
  26472. };
  26473. // anisotropy can only be used when all filter modes are set to linear.
  26474. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  26475. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  26476. }
  26477. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  26478. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  26479. }
  26480. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  26481. }
  26482. createDefaultTexture( texture ) {
  26483. let textureGPU;
  26484. const format = getFormat( texture );
  26485. if ( texture.isCubeTexture ) {
  26486. textureGPU = this._getDefaultCubeTextureGPU( format );
  26487. } else if ( texture.isVideoTexture ) {
  26488. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  26489. } else {
  26490. textureGPU = this._getDefaultTextureGPU( format );
  26491. }
  26492. this.backend.get( texture ).texture = textureGPU;
  26493. }
  26494. createTexture( texture, options = {} ) {
  26495. const backend = this.backend;
  26496. const textureData = backend.get( texture );
  26497. if ( textureData.initialized ) {
  26498. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  26499. }
  26500. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  26501. if ( options.levels === undefined ) options.levels = 1;
  26502. if ( options.depth === undefined ) options.depth = 1;
  26503. const { width, height, depth, levels } = options;
  26504. if ( texture.isFramebufferTexture ) {
  26505. if ( options.renderTarget ) {
  26506. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  26507. } else {
  26508. options.format = this.backend.utils.getPreferredCanvasFormat();
  26509. }
  26510. }
  26511. const dimension = this._getDimension( texture );
  26512. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  26513. textureData.format = format;
  26514. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  26515. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  26516. if ( texture.isStorageTexture === true ) {
  26517. usage |= GPUTextureUsage.STORAGE_BINDING;
  26518. }
  26519. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  26520. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  26521. }
  26522. const textureDescriptorGPU = {
  26523. label: texture.name,
  26524. size: {
  26525. width: width,
  26526. height: height,
  26527. depthOrArrayLayers: depth,
  26528. },
  26529. mipLevelCount: levels,
  26530. sampleCount: primarySamples,
  26531. dimension: dimension,
  26532. format: format,
  26533. usage: usage
  26534. };
  26535. // texture creation
  26536. if ( texture.isVideoTexture ) {
  26537. const video = texture.source.data;
  26538. const videoFrame = new VideoFrame( video );
  26539. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  26540. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  26541. videoFrame.close();
  26542. textureData.externalTexture = video;
  26543. } else {
  26544. if ( format === undefined ) {
  26545. console.warn( 'WebGPURenderer: Texture format not supported.' );
  26546. return this.createDefaultTexture( texture );
  26547. }
  26548. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  26549. }
  26550. if ( isMSAA ) {
  26551. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  26552. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  26553. msaaTextureDescriptorGPU.sampleCount = samples;
  26554. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  26555. }
  26556. textureData.initialized = true;
  26557. textureData.textureDescriptorGPU = textureDescriptorGPU;
  26558. }
  26559. destroyTexture( texture ) {
  26560. const backend = this.backend;
  26561. const textureData = backend.get( texture );
  26562. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  26563. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  26564. backend.delete( texture );
  26565. }
  26566. destroySampler( texture ) {
  26567. const backend = this.backend;
  26568. const textureData = backend.get( texture );
  26569. delete textureData.sampler;
  26570. }
  26571. generateMipmaps( texture ) {
  26572. const textureData = this.backend.get( texture );
  26573. if ( texture.isCubeTexture ) {
  26574. for ( let i = 0; i < 6; i ++ ) {
  26575. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  26576. }
  26577. } else {
  26578. const depth = texture.image.depth || 1;
  26579. for ( let i = 0; i < depth; i ++ ) {
  26580. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  26581. }
  26582. }
  26583. }
  26584. getColorBuffer() {
  26585. if ( this.colorBuffer ) this.colorBuffer.destroy();
  26586. const backend = this.backend;
  26587. const { width, height } = backend.getDrawingBufferSize();
  26588. this.colorBuffer = backend.device.createTexture( {
  26589. label: 'colorBuffer',
  26590. size: {
  26591. width: width,
  26592. height: height,
  26593. depthOrArrayLayers: 1
  26594. },
  26595. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  26596. format: backend.utils.getPreferredCanvasFormat(),
  26597. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  26598. } );
  26599. return this.colorBuffer;
  26600. }
  26601. getDepthBuffer( depth = true, stencil = false ) {
  26602. const backend = this.backend;
  26603. const { width, height } = backend.getDrawingBufferSize();
  26604. const depthTexture = this.depthTexture;
  26605. const depthTextureGPU = backend.get( depthTexture ).texture;
  26606. let format, type;
  26607. if ( stencil ) {
  26608. format = DepthStencilFormat;
  26609. type = UnsignedInt248Type;
  26610. } else if ( depth ) {
  26611. format = DepthFormat;
  26612. type = UnsignedIntType;
  26613. }
  26614. if ( depthTextureGPU !== undefined ) {
  26615. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  26616. return depthTextureGPU;
  26617. }
  26618. this.destroyTexture( depthTexture );
  26619. }
  26620. depthTexture.name = 'depthBuffer';
  26621. depthTexture.format = format;
  26622. depthTexture.type = type;
  26623. depthTexture.image.width = width;
  26624. depthTexture.image.height = height;
  26625. this.createTexture( depthTexture, { width, height } );
  26626. return backend.get( depthTexture ).texture;
  26627. }
  26628. updateTexture( texture, options ) {
  26629. const textureData = this.backend.get( texture );
  26630. const { textureDescriptorGPU } = textureData;
  26631. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  26632. return;
  26633. // transfer texture data
  26634. if ( texture.isDataTexture ) {
  26635. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  26636. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  26637. for ( let i = 0; i < options.image.depth; i ++ ) {
  26638. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  26639. }
  26640. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  26641. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  26642. } else if ( texture.isCubeTexture ) {
  26643. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  26644. } else if ( texture.isVideoTexture ) {
  26645. const video = texture.source.data;
  26646. textureData.externalTexture = video;
  26647. } else {
  26648. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  26649. }
  26650. //
  26651. textureData.version = texture.version;
  26652. if ( texture.onUpdate ) texture.onUpdate( texture );
  26653. }
  26654. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  26655. const device = this.backend.device;
  26656. const textureData = this.backend.get( texture );
  26657. const textureGPU = textureData.texture;
  26658. const format = textureData.textureDescriptorGPU.format;
  26659. const bytesPerTexel = this._getBytesPerTexel( format );
  26660. let bytesPerRow = width * bytesPerTexel;
  26661. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  26662. const readBuffer = device.createBuffer(
  26663. {
  26664. size: width * height * bytesPerTexel,
  26665. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  26666. }
  26667. );
  26668. const encoder = device.createCommandEncoder();
  26669. encoder.copyTextureToBuffer(
  26670. {
  26671. texture: textureGPU,
  26672. origin: { x, y, z: faceIndex },
  26673. },
  26674. {
  26675. buffer: readBuffer,
  26676. bytesPerRow: bytesPerRow
  26677. },
  26678. {
  26679. width: width,
  26680. height: height
  26681. }
  26682. );
  26683. const typedArrayType = this._getTypedArrayType( format );
  26684. device.queue.submit( [ encoder.finish() ] );
  26685. await readBuffer.mapAsync( GPUMapMode.READ );
  26686. const buffer = readBuffer.getMappedRange();
  26687. return new typedArrayType( buffer );
  26688. }
  26689. _isEnvironmentTexture( texture ) {
  26690. const mapping = texture.mapping;
  26691. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  26692. }
  26693. _getDefaultTextureGPU( format ) {
  26694. let defaultTexture = this.defaultTexture[ format ];
  26695. if ( defaultTexture === undefined ) {
  26696. const texture = new Texture();
  26697. texture.minFilter = NearestFilter;
  26698. texture.magFilter = NearestFilter;
  26699. this.createTexture( texture, { width: 1, height: 1, format } );
  26700. this.defaultTexture[ format ] = defaultTexture = texture;
  26701. }
  26702. return this.backend.get( defaultTexture ).texture;
  26703. }
  26704. _getDefaultCubeTextureGPU( format ) {
  26705. let defaultCubeTexture = this.defaultTexture[ format ];
  26706. if ( defaultCubeTexture === undefined ) {
  26707. const texture = new CubeTexture();
  26708. texture.minFilter = NearestFilter;
  26709. texture.magFilter = NearestFilter;
  26710. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  26711. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  26712. }
  26713. return this.backend.get( defaultCubeTexture ).texture;
  26714. }
  26715. _getDefaultVideoFrame() {
  26716. let defaultVideoFrame = this.defaultVideoFrame;
  26717. if ( defaultVideoFrame === null ) {
  26718. const init = {
  26719. timestamp: 0,
  26720. codedWidth: 1,
  26721. codedHeight: 1,
  26722. format: 'RGBA',
  26723. };
  26724. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  26725. }
  26726. return defaultVideoFrame;
  26727. }
  26728. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  26729. for ( let i = 0; i < 6; i ++ ) {
  26730. const image = images[ i ];
  26731. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  26732. if ( image.isDataTexture ) {
  26733. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  26734. } else {
  26735. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  26736. }
  26737. }
  26738. }
  26739. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  26740. const device = this.backend.device;
  26741. device.queue.copyExternalImageToTexture(
  26742. {
  26743. source: image
  26744. }, {
  26745. texture: textureGPU,
  26746. mipLevel: 0,
  26747. origin: { x: 0, y: 0, z: originDepth }
  26748. }, {
  26749. width: image.width,
  26750. height: image.height,
  26751. depthOrArrayLayers: 1
  26752. }
  26753. );
  26754. if ( flipY === true ) {
  26755. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  26756. }
  26757. }
  26758. _getPassUtils() {
  26759. let passUtils = this._passUtils;
  26760. if ( passUtils === null ) {
  26761. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  26762. }
  26763. return passUtils;
  26764. }
  26765. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  26766. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  26767. }
  26768. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  26769. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  26770. }
  26771. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  26772. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  26773. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  26774. const device = this.backend.device;
  26775. const data = image.data;
  26776. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  26777. const bytesPerRow = image.width * bytesPerTexel;
  26778. device.queue.writeTexture(
  26779. {
  26780. texture: textureGPU,
  26781. mipLevel: 0,
  26782. origin: { x: 0, y: 0, z: originDepth }
  26783. },
  26784. data,
  26785. {
  26786. offset: image.width * image.height * bytesPerTexel * depth,
  26787. bytesPerRow
  26788. },
  26789. {
  26790. width: image.width,
  26791. height: image.height,
  26792. depthOrArrayLayers: 1
  26793. } );
  26794. if ( flipY === true ) {
  26795. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  26796. }
  26797. }
  26798. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  26799. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  26800. const device = this.backend.device;
  26801. const blockData = this._getBlockData( textureDescriptorGPU.format );
  26802. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  26803. for ( let i = 0; i < mipmaps.length; i ++ ) {
  26804. const mipmap = mipmaps[ i ];
  26805. const width = mipmap.width;
  26806. const height = mipmap.height;
  26807. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  26808. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  26809. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  26810. for ( let j = 0; j < depth; j ++ ) {
  26811. device.queue.writeTexture(
  26812. {
  26813. texture: textureGPU,
  26814. mipLevel: i,
  26815. origin: { x: 0, y: 0, z: j }
  26816. },
  26817. mipmap.data,
  26818. {
  26819. offset: j * bytesPerImage,
  26820. bytesPerRow,
  26821. rowsPerImage: Math.ceil( height / blockData.height )
  26822. },
  26823. {
  26824. width: Math.ceil( width / blockData.width ) * blockData.width,
  26825. height: Math.ceil( height / blockData.height ) * blockData.height,
  26826. depthOrArrayLayers: 1
  26827. }
  26828. );
  26829. }
  26830. }
  26831. }
  26832. _getBlockData( format ) {
  26833. // this method is only relevant for compressed texture formats
  26834. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  26835. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  26836. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  26837. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  26838. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  26839. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  26840. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  26841. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  26842. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  26843. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  26844. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  26845. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  26846. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  26847. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  26848. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  26849. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  26850. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  26851. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  26852. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  26853. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  26854. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  26855. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  26856. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  26857. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  26858. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  26859. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  26860. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  26861. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  26862. }
  26863. _convertAddressMode( value ) {
  26864. let addressMode = GPUAddressMode.ClampToEdge;
  26865. if ( value === RepeatWrapping ) {
  26866. addressMode = GPUAddressMode.Repeat;
  26867. } else if ( value === MirroredRepeatWrapping ) {
  26868. addressMode = GPUAddressMode.MirrorRepeat;
  26869. }
  26870. return addressMode;
  26871. }
  26872. _convertFilterMode( value ) {
  26873. let filterMode = GPUFilterMode.Linear;
  26874. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  26875. filterMode = GPUFilterMode.Nearest;
  26876. }
  26877. return filterMode;
  26878. }
  26879. _getBytesPerTexel( format ) {
  26880. // 8-bit formats
  26881. if ( format === GPUTextureFormat.R8Unorm ||
  26882. format === GPUTextureFormat.R8Snorm ||
  26883. format === GPUTextureFormat.R8Uint ||
  26884. format === GPUTextureFormat.R8Sint ) return 1;
  26885. // 16-bit formats
  26886. if ( format === GPUTextureFormat.R16Uint ||
  26887. format === GPUTextureFormat.R16Sint ||
  26888. format === GPUTextureFormat.R16Float ||
  26889. format === GPUTextureFormat.RG8Unorm ||
  26890. format === GPUTextureFormat.RG8Snorm ||
  26891. format === GPUTextureFormat.RG8Uint ||
  26892. format === GPUTextureFormat.RG8Sint ) return 2;
  26893. // 32-bit formats
  26894. if ( format === GPUTextureFormat.R32Uint ||
  26895. format === GPUTextureFormat.R32Sint ||
  26896. format === GPUTextureFormat.R32Float ||
  26897. format === GPUTextureFormat.RG16Uint ||
  26898. format === GPUTextureFormat.RG16Sint ||
  26899. format === GPUTextureFormat.RG16Float ||
  26900. format === GPUTextureFormat.RGBA8Unorm ||
  26901. format === GPUTextureFormat.RGBA8UnormSRGB ||
  26902. format === GPUTextureFormat.RGBA8Snorm ||
  26903. format === GPUTextureFormat.RGBA8Uint ||
  26904. format === GPUTextureFormat.RGBA8Sint ||
  26905. format === GPUTextureFormat.BGRA8Unorm ||
  26906. format === GPUTextureFormat.BGRA8UnormSRGB ||
  26907. // Packed 32-bit formats
  26908. format === GPUTextureFormat.RGB9E5UFloat ||
  26909. format === GPUTextureFormat.RGB10A2Unorm ||
  26910. format === GPUTextureFormat.RG11B10UFloat ||
  26911. format === GPUTextureFormat.Depth32Float ||
  26912. format === GPUTextureFormat.Depth24Plus ||
  26913. format === GPUTextureFormat.Depth24PlusStencil8 ||
  26914. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  26915. // 64-bit formats
  26916. if ( format === GPUTextureFormat.RG32Uint ||
  26917. format === GPUTextureFormat.RG32Sint ||
  26918. format === GPUTextureFormat.RG32Float ||
  26919. format === GPUTextureFormat.RGBA16Uint ||
  26920. format === GPUTextureFormat.RGBA16Sint ||
  26921. format === GPUTextureFormat.RGBA16Float ) return 8;
  26922. // 128-bit formats
  26923. if ( format === GPUTextureFormat.RGBA32Uint ||
  26924. format === GPUTextureFormat.RGBA32Sint ||
  26925. format === GPUTextureFormat.RGBA32Float ) return 16;
  26926. }
  26927. _getTypedArrayType( format ) {
  26928. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  26929. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  26930. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  26931. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  26932. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  26933. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  26934. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  26935. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  26936. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  26937. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  26938. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  26939. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  26940. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  26941. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  26942. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  26943. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  26944. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  26945. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  26946. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  26947. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  26948. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  26949. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  26950. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  26951. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  26952. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  26953. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  26954. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  26955. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  26956. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  26957. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  26958. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  26959. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  26960. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  26961. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  26962. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  26963. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  26964. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  26965. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  26966. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  26967. }
  26968. _getDimension( texture ) {
  26969. let dimension;
  26970. if ( texture.isData3DTexture ) {
  26971. dimension = GPUTextureDimension.ThreeD;
  26972. } else {
  26973. dimension = GPUTextureDimension.TwoD;
  26974. }
  26975. return dimension;
  26976. }
  26977. }
  26978. function getFormat( texture, device = null ) {
  26979. const format = texture.format;
  26980. const type = texture.type;
  26981. const colorSpace = texture.colorSpace;
  26982. let formatGPU;
  26983. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  26984. switch ( format ) {
  26985. case RGBA_S3TC_DXT1_Format:
  26986. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  26987. break;
  26988. case RGBA_S3TC_DXT3_Format:
  26989. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  26990. break;
  26991. case RGBA_S3TC_DXT5_Format:
  26992. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  26993. break;
  26994. case RGB_ETC2_Format:
  26995. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  26996. break;
  26997. case RGBA_ETC2_EAC_Format:
  26998. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  26999. break;
  27000. case RGBA_ASTC_4x4_Format:
  27001. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  27002. break;
  27003. case RGBA_ASTC_5x4_Format:
  27004. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  27005. break;
  27006. case RGBA_ASTC_5x5_Format:
  27007. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  27008. break;
  27009. case RGBA_ASTC_6x5_Format:
  27010. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  27011. break;
  27012. case RGBA_ASTC_6x6_Format:
  27013. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  27014. break;
  27015. case RGBA_ASTC_8x5_Format:
  27016. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  27017. break;
  27018. case RGBA_ASTC_8x6_Format:
  27019. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  27020. break;
  27021. case RGBA_ASTC_8x8_Format:
  27022. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  27023. break;
  27024. case RGBA_ASTC_10x5_Format:
  27025. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  27026. break;
  27027. case RGBA_ASTC_10x6_Format:
  27028. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  27029. break;
  27030. case RGBA_ASTC_10x8_Format:
  27031. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  27032. break;
  27033. case RGBA_ASTC_10x10_Format:
  27034. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  27035. break;
  27036. case RGBA_ASTC_12x10_Format:
  27037. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  27038. break;
  27039. case RGBA_ASTC_12x12_Format:
  27040. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  27041. break;
  27042. case RGBAFormat:
  27043. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  27044. break;
  27045. default:
  27046. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  27047. }
  27048. } else {
  27049. switch ( format ) {
  27050. case RGBAFormat:
  27051. switch ( type ) {
  27052. case ByteType:
  27053. formatGPU = GPUTextureFormat.RGBA8Snorm;
  27054. break;
  27055. case ShortType:
  27056. formatGPU = GPUTextureFormat.RGBA16Sint;
  27057. break;
  27058. case UnsignedShortType:
  27059. formatGPU = GPUTextureFormat.RGBA16Uint;
  27060. break;
  27061. case UnsignedIntType:
  27062. formatGPU = GPUTextureFormat.RGBA32Uint;
  27063. break;
  27064. case IntType:
  27065. formatGPU = GPUTextureFormat.RGBA32Sint;
  27066. break;
  27067. case UnsignedByteType:
  27068. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  27069. break;
  27070. case HalfFloatType:
  27071. formatGPU = GPUTextureFormat.RGBA16Float;
  27072. break;
  27073. case FloatType:
  27074. formatGPU = GPUTextureFormat.RGBA32Float;
  27075. break;
  27076. default:
  27077. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  27078. }
  27079. break;
  27080. case RGBFormat:
  27081. switch ( type ) {
  27082. case UnsignedInt5999Type:
  27083. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  27084. break;
  27085. default:
  27086. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  27087. }
  27088. break;
  27089. case RedFormat:
  27090. switch ( type ) {
  27091. case ByteType:
  27092. formatGPU = GPUTextureFormat.R8Snorm;
  27093. break;
  27094. case ShortType:
  27095. formatGPU = GPUTextureFormat.R16Sint;
  27096. break;
  27097. case UnsignedShortType:
  27098. formatGPU = GPUTextureFormat.R16Uint;
  27099. break;
  27100. case UnsignedIntType:
  27101. formatGPU = GPUTextureFormat.R32Uint;
  27102. break;
  27103. case IntType:
  27104. formatGPU = GPUTextureFormat.R32Sint;
  27105. break;
  27106. case UnsignedByteType:
  27107. formatGPU = GPUTextureFormat.R8Unorm;
  27108. break;
  27109. case HalfFloatType:
  27110. formatGPU = GPUTextureFormat.R16Float;
  27111. break;
  27112. case FloatType:
  27113. formatGPU = GPUTextureFormat.R32Float;
  27114. break;
  27115. default:
  27116. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  27117. }
  27118. break;
  27119. case RGFormat:
  27120. switch ( type ) {
  27121. case ByteType:
  27122. formatGPU = GPUTextureFormat.RG8Snorm;
  27123. break;
  27124. case ShortType:
  27125. formatGPU = GPUTextureFormat.RG16Sint;
  27126. break;
  27127. case UnsignedShortType:
  27128. formatGPU = GPUTextureFormat.RG16Uint;
  27129. break;
  27130. case UnsignedIntType:
  27131. formatGPU = GPUTextureFormat.RG32Uint;
  27132. break;
  27133. case IntType:
  27134. formatGPU = GPUTextureFormat.RG32Sint;
  27135. break;
  27136. case UnsignedByteType:
  27137. formatGPU = GPUTextureFormat.RG8Unorm;
  27138. break;
  27139. case HalfFloatType:
  27140. formatGPU = GPUTextureFormat.RG16Float;
  27141. break;
  27142. case FloatType:
  27143. formatGPU = GPUTextureFormat.RG32Float;
  27144. break;
  27145. default:
  27146. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  27147. }
  27148. break;
  27149. case DepthFormat:
  27150. switch ( type ) {
  27151. case UnsignedShortType:
  27152. formatGPU = GPUTextureFormat.Depth16Unorm;
  27153. break;
  27154. case UnsignedIntType:
  27155. formatGPU = GPUTextureFormat.Depth24Plus;
  27156. break;
  27157. case FloatType:
  27158. formatGPU = GPUTextureFormat.Depth32Float;
  27159. break;
  27160. default:
  27161. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  27162. }
  27163. break;
  27164. case DepthStencilFormat:
  27165. switch ( type ) {
  27166. case UnsignedInt248Type:
  27167. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  27168. break;
  27169. case FloatType:
  27170. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  27171. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  27172. }
  27173. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  27174. break;
  27175. default:
  27176. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  27177. }
  27178. break;
  27179. case RedIntegerFormat:
  27180. switch ( type ) {
  27181. case IntType:
  27182. formatGPU = GPUTextureFormat.R32Sint;
  27183. break;
  27184. case UnsignedIntType:
  27185. formatGPU = GPUTextureFormat.R32Uint;
  27186. break;
  27187. default:
  27188. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  27189. }
  27190. break;
  27191. case RGIntegerFormat:
  27192. switch ( type ) {
  27193. case IntType:
  27194. formatGPU = GPUTextureFormat.RG32Sint;
  27195. break;
  27196. case UnsignedIntType:
  27197. formatGPU = GPUTextureFormat.RG32Uint;
  27198. break;
  27199. default:
  27200. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  27201. }
  27202. break;
  27203. case RGBAIntegerFormat:
  27204. switch ( type ) {
  27205. case IntType:
  27206. formatGPU = GPUTextureFormat.RGBA32Sint;
  27207. break;
  27208. case UnsignedIntType:
  27209. formatGPU = GPUTextureFormat.RGBA32Uint;
  27210. break;
  27211. default:
  27212. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  27213. }
  27214. break;
  27215. default:
  27216. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  27217. }
  27218. }
  27219. return formatGPU;
  27220. }
  27221. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  27222. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  27223. const wgslTypeLib$1 = {
  27224. 'f32': 'float',
  27225. 'i32': 'int',
  27226. 'u32': 'uint',
  27227. 'bool': 'bool',
  27228. 'vec2<f32>': 'vec2',
  27229. 'vec2<i32>': 'ivec2',
  27230. 'vec2<u32>': 'uvec2',
  27231. 'vec2<bool>': 'bvec2',
  27232. 'vec2f': 'vec2',
  27233. 'vec2i': 'ivec2',
  27234. 'vec2u': 'uvec2',
  27235. 'vec2b': 'bvec2',
  27236. 'vec3<f32>': 'vec3',
  27237. 'vec3<i32>': 'ivec3',
  27238. 'vec3<u32>': 'uvec3',
  27239. 'vec3<bool>': 'bvec3',
  27240. 'vec3f': 'vec3',
  27241. 'vec3i': 'ivec3',
  27242. 'vec3u': 'uvec3',
  27243. 'vec3b': 'bvec3',
  27244. 'vec4<f32>': 'vec4',
  27245. 'vec4<i32>': 'ivec4',
  27246. 'vec4<u32>': 'uvec4',
  27247. 'vec4<bool>': 'bvec4',
  27248. 'vec4f': 'vec4',
  27249. 'vec4i': 'ivec4',
  27250. 'vec4u': 'uvec4',
  27251. 'vec4b': 'bvec4',
  27252. 'mat2x2<f32>': 'mat2',
  27253. 'mat2x2f': 'mat2',
  27254. 'mat3x3<f32>': 'mat3',
  27255. 'mat3x3f': 'mat3',
  27256. 'mat4x4<f32>': 'mat4',
  27257. 'mat4x4f': 'mat4',
  27258. 'sampler': 'sampler',
  27259. 'texture_1d': 'texture',
  27260. 'texture_2d': 'texture',
  27261. 'texture_2d_array': 'texture',
  27262. 'texture_multisampled_2d': 'cubeTexture',
  27263. 'texture_depth_2d': 'depthTexture',
  27264. 'texture_3d': 'texture3D',
  27265. 'texture_cube': 'cubeTexture',
  27266. 'texture_cube_array': 'cubeTexture',
  27267. 'texture_storage_1d': 'storageTexture',
  27268. 'texture_storage_2d': 'storageTexture',
  27269. 'texture_storage_2d_array': 'storageTexture',
  27270. 'texture_storage_3d': 'storageTexture'
  27271. };
  27272. const parse = ( source ) => {
  27273. source = source.trim();
  27274. const declaration = source.match( declarationRegexp );
  27275. if ( declaration !== null && declaration.length === 4 ) {
  27276. const inputsCode = declaration[ 2 ];
  27277. const propsMatches = [];
  27278. let match = null;
  27279. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  27280. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  27281. }
  27282. // Process matches to correctly pair names and types
  27283. const inputs = [];
  27284. for ( let i = 0; i < propsMatches.length; i ++ ) {
  27285. const { name, type } = propsMatches[ i ];
  27286. let resolvedType = type;
  27287. if ( resolvedType.startsWith( 'ptr' ) ) {
  27288. resolvedType = 'pointer';
  27289. } else {
  27290. if ( resolvedType.startsWith( 'texture' ) ) {
  27291. resolvedType = type.split( '<' )[ 0 ];
  27292. }
  27293. resolvedType = wgslTypeLib$1[ resolvedType ];
  27294. }
  27295. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  27296. }
  27297. const blockCode = source.substring( declaration[ 0 ].length );
  27298. const outputType = declaration[ 3 ] || 'void';
  27299. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  27300. const type = wgslTypeLib$1[ outputType ] || outputType;
  27301. return {
  27302. type,
  27303. inputs,
  27304. name,
  27305. inputsCode,
  27306. blockCode,
  27307. outputType
  27308. };
  27309. } else {
  27310. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  27311. }
  27312. };
  27313. /**
  27314. * This class represents a WSL node function.
  27315. *
  27316. * @augments NodeFunction
  27317. */
  27318. class WGSLNodeFunction extends NodeFunction {
  27319. /**
  27320. * Constructs a new WGSL node function.
  27321. *
  27322. * @param {String} source - The WGSL source.
  27323. */
  27324. constructor( source ) {
  27325. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  27326. super( type, inputs, name );
  27327. this.inputsCode = inputsCode;
  27328. this.blockCode = blockCode;
  27329. this.outputType = outputType;
  27330. }
  27331. /**
  27332. * This method returns the WGSL code of the node function.
  27333. *
  27334. * @param {String} [name=this.name] - The function's name.
  27335. * @return {String} The shader code.
  27336. */
  27337. getCode( name = this.name ) {
  27338. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  27339. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  27340. }
  27341. }
  27342. /**
  27343. * A WGSL node parser.
  27344. *
  27345. * @augments NodeParser
  27346. */
  27347. class WGSLNodeParser extends NodeParser {
  27348. /**
  27349. * The method parses the given WGSL code an returns a node function.
  27350. *
  27351. * @param {String} source - The WGSL code.
  27352. * @return {WGSLNodeFunction} A node function.
  27353. */
  27354. parseFunction( source ) {
  27355. return new WGSLNodeFunction( source );
  27356. }
  27357. }
  27358. // GPUShaderStage is not defined in browsers not supporting WebGPU
  27359. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  27360. const accessNames = {
  27361. [ NodeAccess.READ_ONLY ]: 'read',
  27362. [ NodeAccess.WRITE_ONLY ]: 'write',
  27363. [ NodeAccess.READ_WRITE ]: 'read_write'
  27364. };
  27365. const wrapNames = {
  27366. [ RepeatWrapping ]: 'repeat',
  27367. [ ClampToEdgeWrapping ]: 'clamp',
  27368. [ MirroredRepeatWrapping ]: 'mirror'
  27369. };
  27370. const gpuShaderStageLib = {
  27371. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  27372. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  27373. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  27374. };
  27375. const supports = {
  27376. instance: true,
  27377. swizzleAssign: false,
  27378. storageBuffer: true
  27379. };
  27380. const wgslFnOpLib = {
  27381. '^^': 'tsl_xor'
  27382. };
  27383. const wgslTypeLib = {
  27384. float: 'f32',
  27385. int: 'i32',
  27386. uint: 'u32',
  27387. bool: 'bool',
  27388. color: 'vec3<f32>',
  27389. vec2: 'vec2<f32>',
  27390. ivec2: 'vec2<i32>',
  27391. uvec2: 'vec2<u32>',
  27392. bvec2: 'vec2<bool>',
  27393. vec3: 'vec3<f32>',
  27394. ivec3: 'vec3<i32>',
  27395. uvec3: 'vec3<u32>',
  27396. bvec3: 'vec3<bool>',
  27397. vec4: 'vec4<f32>',
  27398. ivec4: 'vec4<i32>',
  27399. uvec4: 'vec4<u32>',
  27400. bvec4: 'vec4<bool>',
  27401. mat2: 'mat2x2<f32>',
  27402. mat3: 'mat3x3<f32>',
  27403. mat4: 'mat4x4<f32>'
  27404. };
  27405. const wgslCodeCache = {};
  27406. const wgslPolyfill = {
  27407. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  27408. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  27409. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  27410. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  27411. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  27412. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  27413. 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 ); }' ),
  27414. 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 ); }' ),
  27415. 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 ); }' ),
  27416. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  27417. 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 ); }' ),
  27418. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  27419. biquadraticTexture: new CodeNode( /* wgsl */`
  27420. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  27421. let res = vec2f( iRes );
  27422. let uvScaled = coord * res;
  27423. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  27424. // https://www.shadertoy.com/view/WtyXRy
  27425. let uv = uvWrapping - 0.5;
  27426. let iuv = floor( uv );
  27427. let f = fract( uv );
  27428. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  27429. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  27430. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  27431. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  27432. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  27433. }
  27434. ` )
  27435. };
  27436. const wgslMethods = {
  27437. dFdx: 'dpdx',
  27438. dFdy: '- dpdy',
  27439. mod_float: 'tsl_mod_float',
  27440. mod_vec2: 'tsl_mod_vec2',
  27441. mod_vec3: 'tsl_mod_vec3',
  27442. mod_vec4: 'tsl_mod_vec4',
  27443. equals_bool: 'tsl_equals_bool',
  27444. equals_bvec2: 'tsl_equals_bvec2',
  27445. equals_bvec3: 'tsl_equals_bvec3',
  27446. equals_bvec4: 'tsl_equals_bvec4',
  27447. inversesqrt: 'inverseSqrt',
  27448. bitcast: 'bitcast<f32>'
  27449. };
  27450. // WebGPU issue: does not support pow() with negative base on Windows
  27451. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  27452. 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 ); }' );
  27453. 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 ] );
  27454. 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 ] );
  27455. 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 ] );
  27456. wgslMethods.pow_float = 'tsl_pow_float';
  27457. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  27458. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  27459. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  27460. }
  27461. //
  27462. let diagnostics = '';
  27463. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  27464. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  27465. }
  27466. //
  27467. class WGSLNodeBuilder extends NodeBuilder {
  27468. constructor( object, renderer ) {
  27469. super( object, renderer, new WGSLNodeParser() );
  27470. this.uniformGroups = {};
  27471. this.builtins = {};
  27472. this.directives = {};
  27473. this.scopedArrays = new Map();
  27474. }
  27475. needsToWorkingColorSpace( texture ) {
  27476. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  27477. }
  27478. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27479. if ( shaderStage === 'fragment' ) {
  27480. if ( depthSnippet ) {
  27481. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  27482. } else {
  27483. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  27484. }
  27485. } else if ( this.isFilteredTexture( texture ) ) {
  27486. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  27487. } else {
  27488. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  27489. }
  27490. }
  27491. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  27492. if ( shaderStage === 'fragment' ) {
  27493. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  27494. } else {
  27495. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  27496. }
  27497. }
  27498. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27499. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  27500. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  27501. } else if ( this.isFilteredTexture( texture ) ) {
  27502. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  27503. } else {
  27504. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  27505. }
  27506. }
  27507. generateWrapFunction( texture ) {
  27508. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  27509. let nodeCode = wgslCodeCache[ functionName ];
  27510. if ( nodeCode === undefined ) {
  27511. const includes = [];
  27512. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  27513. const addWrapSnippet = ( wrap, axis ) => {
  27514. if ( wrap === RepeatWrapping ) {
  27515. includes.push( wgslPolyfill.repeatWrapping_float );
  27516. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  27517. } else if ( wrap === ClampToEdgeWrapping ) {
  27518. includes.push( wgslPolyfill.clampWrapping_float );
  27519. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  27520. } else if ( wrap === MirroredRepeatWrapping ) {
  27521. includes.push( wgslPolyfill.mirrorWrapping_float );
  27522. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  27523. } else {
  27524. code += `\t\tcoord.${ axis }`;
  27525. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  27526. }
  27527. };
  27528. addWrapSnippet( texture.wrapS, 'x' );
  27529. code += ',\n';
  27530. addWrapSnippet( texture.wrapT, 'y' );
  27531. code += '\n\t);\n\n}\n';
  27532. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  27533. }
  27534. nodeCode.build( this );
  27535. return functionName;
  27536. }
  27537. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  27538. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  27539. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  27540. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  27541. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  27542. let textureDimensionsParams;
  27543. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  27544. if ( primarySamples > 1 ) {
  27545. textureDimensionsParams = textureProperty;
  27546. } else {
  27547. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  27548. }
  27549. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  27550. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  27551. }
  27552. return textureDimensionNode.build( this );
  27553. }
  27554. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  27555. this._include( 'biquadraticTexture' );
  27556. const wrapFunction = this.generateWrapFunction( texture );
  27557. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  27558. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  27559. }
  27560. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  27561. const wrapFunction = this.generateWrapFunction( texture );
  27562. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  27563. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  27564. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  27565. }
  27566. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  27567. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  27568. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  27569. } else if ( depthSnippet ) {
  27570. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  27571. } else {
  27572. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  27573. }
  27574. }
  27575. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  27576. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  27577. }
  27578. isSampleCompare( texture ) {
  27579. return texture.isDepthTexture === true && texture.compareFunction !== null;
  27580. }
  27581. isUnfilterable( texture ) {
  27582. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  27583. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  27584. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  27585. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  27586. }
  27587. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27588. let snippet = null;
  27589. if ( texture.isVideoTexture === true ) {
  27590. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  27591. } else if ( this.isUnfilterable( texture ) ) {
  27592. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  27593. } else {
  27594. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  27595. }
  27596. return snippet;
  27597. }
  27598. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27599. if ( shaderStage === 'fragment' ) {
  27600. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  27601. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  27602. } else {
  27603. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  27604. }
  27605. }
  27606. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27607. if ( shaderStage === 'fragment' ) {
  27608. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  27609. } else {
  27610. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  27611. }
  27612. }
  27613. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27614. let snippet = null;
  27615. if ( texture.isVideoTexture === true ) {
  27616. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  27617. } else {
  27618. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  27619. }
  27620. return snippet;
  27621. }
  27622. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27623. if ( shaderStage === 'fragment' ) {
  27624. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  27625. } else {
  27626. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  27627. }
  27628. }
  27629. getPropertyName( node, shaderStage = this.shaderStage ) {
  27630. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  27631. if ( shaderStage === 'vertex' ) {
  27632. return `varyings.${ node.name }`;
  27633. }
  27634. } else if ( node.isNodeUniform === true ) {
  27635. const name = node.name;
  27636. const type = node.type;
  27637. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  27638. return name;
  27639. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  27640. return `NodeBuffer_${ node.id }.${name}`;
  27641. } else {
  27642. return node.groupNode.name + '.' + name;
  27643. }
  27644. }
  27645. return super.getPropertyName( node );
  27646. }
  27647. getOutputStructName() {
  27648. return 'output';
  27649. }
  27650. _getUniformGroupCount( shaderStage ) {
  27651. return Object.keys( this.uniforms[ shaderStage ] ).length;
  27652. }
  27653. getFunctionOperator( op ) {
  27654. const fnOp = wgslFnOpLib[ op ];
  27655. if ( fnOp !== undefined ) {
  27656. this._include( fnOp );
  27657. return fnOp;
  27658. }
  27659. return null;
  27660. }
  27661. getNodeAccess( node, shaderStage ) {
  27662. if ( shaderStage !== 'compute' )
  27663. return NodeAccess.READ_ONLY;
  27664. return node.access;
  27665. }
  27666. getStorageAccess( node, shaderStage ) {
  27667. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  27668. }
  27669. getUniformFromNode( node, type, shaderStage, name = null ) {
  27670. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  27671. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  27672. if ( nodeData.uniformGPU === undefined ) {
  27673. let uniformGPU;
  27674. const group = node.groupNode;
  27675. const groupName = group.name;
  27676. const bindings = this.getBindGroupArray( groupName, shaderStage );
  27677. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  27678. let texture = null;
  27679. const access = this.getNodeAccess( node, shaderStage );
  27680. if ( type === 'texture' || type === 'storageTexture' ) {
  27681. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  27682. } else if ( type === 'cubeTexture' ) {
  27683. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  27684. } else if ( type === 'texture3D' ) {
  27685. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  27686. }
  27687. texture.store = node.isStorageTextureNode === true;
  27688. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  27689. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  27690. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  27691. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  27692. bindings.push( sampler, texture );
  27693. uniformGPU = [ sampler, texture ];
  27694. } else {
  27695. bindings.push( texture );
  27696. uniformGPU = [ texture ];
  27697. }
  27698. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  27699. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  27700. const buffer = new bufferClass( node, group );
  27701. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  27702. bindings.push( buffer );
  27703. uniformGPU = buffer;
  27704. } else {
  27705. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  27706. let uniformsGroup = uniformsStage[ groupName ];
  27707. if ( uniformsGroup === undefined ) {
  27708. uniformsGroup = new NodeUniformsGroup( groupName, group );
  27709. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  27710. uniformsStage[ groupName ] = uniformsGroup;
  27711. bindings.push( uniformsGroup );
  27712. }
  27713. uniformGPU = this.getNodeUniform( uniformNode, type );
  27714. uniformsGroup.addUniform( uniformGPU );
  27715. }
  27716. nodeData.uniformGPU = uniformGPU;
  27717. }
  27718. return uniformNode;
  27719. }
  27720. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  27721. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  27722. if ( map.has( name ) === false ) {
  27723. map.set( name, {
  27724. name,
  27725. property,
  27726. type
  27727. } );
  27728. }
  27729. return property;
  27730. }
  27731. hasBuiltin( name, shaderStage = this.shaderStage ) {
  27732. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  27733. }
  27734. getVertexIndex() {
  27735. if ( this.shaderStage === 'vertex' ) {
  27736. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  27737. }
  27738. return 'vertexIndex';
  27739. }
  27740. buildFunctionCode( shaderNode ) {
  27741. const layout = shaderNode.layout;
  27742. const flowData = this.flowShaderNode( shaderNode );
  27743. const parameters = [];
  27744. for ( const input of layout.inputs ) {
  27745. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  27746. }
  27747. //
  27748. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  27749. ${ flowData.vars }
  27750. ${ flowData.code }
  27751. `;
  27752. if ( flowData.result ) {
  27753. code += `\treturn ${ flowData.result };\n`;
  27754. }
  27755. code += '\n}\n';
  27756. //
  27757. return code;
  27758. }
  27759. getInstanceIndex() {
  27760. if ( this.shaderStage === 'vertex' ) {
  27761. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  27762. }
  27763. return 'instanceIndex';
  27764. }
  27765. getInvocationLocalIndex() {
  27766. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  27767. }
  27768. getSubgroupSize() {
  27769. this.enableSubGroups();
  27770. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  27771. }
  27772. getInvocationSubgroupIndex() {
  27773. this.enableSubGroups();
  27774. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  27775. }
  27776. getSubgroupIndex() {
  27777. this.enableSubGroups();
  27778. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  27779. }
  27780. getDrawIndex() {
  27781. return null;
  27782. }
  27783. getFrontFacing() {
  27784. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  27785. }
  27786. getFragCoord() {
  27787. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  27788. }
  27789. getFragDepth() {
  27790. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  27791. }
  27792. getClipDistance() {
  27793. return 'varyings.hw_clip_distances';
  27794. }
  27795. isFlipY() {
  27796. return false;
  27797. }
  27798. enableDirective( name, shaderStage = this.shaderStage ) {
  27799. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  27800. stage.add( name );
  27801. }
  27802. getDirectives( shaderStage ) {
  27803. const snippets = [];
  27804. const directives = this.directives[ shaderStage ];
  27805. if ( directives !== undefined ) {
  27806. for ( const directive of directives ) {
  27807. snippets.push( `enable ${directive};` );
  27808. }
  27809. }
  27810. return snippets.join( '\n' );
  27811. }
  27812. enableSubGroups() {
  27813. this.enableDirective( 'subgroups' );
  27814. }
  27815. enableSubgroupsF16() {
  27816. this.enableDirective( 'subgroups-f16' );
  27817. }
  27818. enableClipDistances() {
  27819. this.enableDirective( 'clip_distances' );
  27820. }
  27821. enableShaderF16() {
  27822. this.enableDirective( 'f16' );
  27823. }
  27824. enableDualSourceBlending() {
  27825. this.enableDirective( 'dual_source_blending' );
  27826. }
  27827. enableHardwareClipping( planeCount ) {
  27828. this.enableClipDistances();
  27829. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  27830. }
  27831. getBuiltins( shaderStage ) {
  27832. const snippets = [];
  27833. const builtins = this.builtins[ shaderStage ];
  27834. if ( builtins !== undefined ) {
  27835. for ( const { name, property, type } of builtins.values() ) {
  27836. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  27837. }
  27838. }
  27839. return snippets.join( ',\n\t' );
  27840. }
  27841. getScopedArray( name, scope, bufferType, bufferCount ) {
  27842. if ( this.scopedArrays.has( name ) === false ) {
  27843. this.scopedArrays.set( name, {
  27844. name,
  27845. scope,
  27846. bufferType,
  27847. bufferCount
  27848. } );
  27849. }
  27850. return name;
  27851. }
  27852. getScopedArrays( shaderStage ) {
  27853. if ( shaderStage !== 'compute' ) {
  27854. return;
  27855. }
  27856. const snippets = [];
  27857. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  27858. const type = this.getType( bufferType );
  27859. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  27860. }
  27861. return snippets.join( '\n' );
  27862. }
  27863. getAttributes( shaderStage ) {
  27864. const snippets = [];
  27865. if ( shaderStage === 'compute' ) {
  27866. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  27867. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  27868. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  27869. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  27870. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  27871. this.enableDirective( 'subgroups', shaderStage );
  27872. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  27873. }
  27874. }
  27875. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  27876. const builtins = this.getBuiltins( 'attribute' );
  27877. if ( builtins ) snippets.push( builtins );
  27878. const attributes = this.getAttributesArray();
  27879. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  27880. const attribute = attributes[ index ];
  27881. const name = attribute.name;
  27882. const type = this.getType( attribute.type );
  27883. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  27884. }
  27885. }
  27886. return snippets.join( ',\n\t' );
  27887. }
  27888. getStructMembers( struct ) {
  27889. const snippets = [];
  27890. const members = struct.getMemberTypes();
  27891. for ( let i = 0; i < members.length; i ++ ) {
  27892. const member = members[ i ];
  27893. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  27894. }
  27895. const builtins = this.getBuiltins( 'output' );
  27896. if ( builtins ) snippets.push( '\t' + builtins );
  27897. return snippets.join( ',\n' );
  27898. }
  27899. getStructs( shaderStage ) {
  27900. const snippets = [];
  27901. const structs = this.structs[ shaderStage ];
  27902. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  27903. const struct = structs[ index ];
  27904. const name = struct.name;
  27905. let snippet = `\struct ${ name } {\n`;
  27906. snippet += this.getStructMembers( struct );
  27907. snippet += '\n}';
  27908. snippets.push( snippet );
  27909. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  27910. }
  27911. return snippets.join( '\n\n' );
  27912. }
  27913. getVar( type, name ) {
  27914. return `var ${ name } : ${ this.getType( type ) }`;
  27915. }
  27916. getVars( shaderStage ) {
  27917. const snippets = [];
  27918. const vars = this.vars[ shaderStage ];
  27919. if ( vars !== undefined ) {
  27920. for ( const variable of vars ) {
  27921. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  27922. }
  27923. }
  27924. return `\n${ snippets.join( '\n' ) }\n`;
  27925. }
  27926. getVaryings( shaderStage ) {
  27927. const snippets = [];
  27928. if ( shaderStage === 'vertex' ) {
  27929. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  27930. }
  27931. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  27932. const varyings = this.varyings;
  27933. const vars = this.vars[ shaderStage ];
  27934. for ( let index = 0; index < varyings.length; index ++ ) {
  27935. const varying = varyings[ index ];
  27936. if ( varying.needsInterpolation ) {
  27937. let attributesSnippet = `@location( ${index} )`;
  27938. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  27939. attributesSnippet += ' @interpolate( flat )';
  27940. }
  27941. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  27942. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  27943. vars.push( varying );
  27944. }
  27945. }
  27946. }
  27947. const builtins = this.getBuiltins( shaderStage );
  27948. if ( builtins ) snippets.push( builtins );
  27949. const code = snippets.join( ',\n\t' );
  27950. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  27951. }
  27952. getUniforms( shaderStage ) {
  27953. const uniforms = this.uniforms[ shaderStage ];
  27954. const bindingSnippets = [];
  27955. const bufferSnippets = [];
  27956. const structSnippets = [];
  27957. const uniformGroups = {};
  27958. for ( const uniform of uniforms ) {
  27959. const groupName = uniform.groupNode.name;
  27960. const uniformIndexes = this.bindingsIndexes[ groupName ];
  27961. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  27962. const texture = uniform.node.value;
  27963. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  27964. if ( this.isSampleCompare( texture ) ) {
  27965. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  27966. } else {
  27967. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  27968. }
  27969. }
  27970. let textureType;
  27971. let multisampled = '';
  27972. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  27973. if ( primarySamples > 1 ) {
  27974. multisampled = '_multisampled';
  27975. }
  27976. if ( texture.isCubeTexture === true ) {
  27977. textureType = 'texture_cube<f32>';
  27978. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  27979. textureType = 'texture_2d_array<f32>';
  27980. } else if ( texture.isDepthTexture === true ) {
  27981. textureType = `texture_depth${multisampled}_2d`;
  27982. } else if ( texture.isVideoTexture === true ) {
  27983. textureType = 'texture_external';
  27984. } else if ( texture.isData3DTexture === true ) {
  27985. textureType = 'texture_3d<f32>';
  27986. } else if ( uniform.node.isStorageTextureNode === true ) {
  27987. const format = getFormat( texture );
  27988. const access = this.getStorageAccess( uniform.node, shaderStage );
  27989. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  27990. } else {
  27991. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  27992. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  27993. }
  27994. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  27995. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  27996. const bufferNode = uniform.node;
  27997. const bufferType = this.getType( bufferNode.bufferType );
  27998. const bufferCount = bufferNode.bufferCount;
  27999. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  28000. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  28001. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  28002. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  28003. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  28004. } else {
  28005. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  28006. const groupName = uniform.groupNode.name;
  28007. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  28008. index: uniformIndexes.binding ++,
  28009. id: uniformIndexes.group,
  28010. snippets: []
  28011. } );
  28012. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  28013. }
  28014. }
  28015. for ( const name in uniformGroups ) {
  28016. const group = uniformGroups[ name ];
  28017. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  28018. }
  28019. let code = bindingSnippets.join( '\n' );
  28020. code += bufferSnippets.join( '\n' );
  28021. code += structSnippets.join( '\n' );
  28022. return code;
  28023. }
  28024. buildCode() {
  28025. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  28026. this.sortBindingGroups();
  28027. for ( const shaderStage in shadersData ) {
  28028. const stageData = shadersData[ shaderStage ];
  28029. stageData.uniforms = this.getUniforms( shaderStage );
  28030. stageData.attributes = this.getAttributes( shaderStage );
  28031. stageData.varyings = this.getVaryings( shaderStage );
  28032. stageData.structs = this.getStructs( shaderStage );
  28033. stageData.vars = this.getVars( shaderStage );
  28034. stageData.codes = this.getCodes( shaderStage );
  28035. stageData.directives = this.getDirectives( shaderStage );
  28036. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  28037. //
  28038. let flow = '// code\n\n';
  28039. flow += this.flowCode[ shaderStage ];
  28040. const flowNodes = this.flowNodes[ shaderStage ];
  28041. const mainNode = flowNodes[ flowNodes.length - 1 ];
  28042. const outputNode = mainNode.outputNode;
  28043. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  28044. for ( const node of flowNodes ) {
  28045. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  28046. const slotName = node.name;
  28047. if ( slotName ) {
  28048. if ( flow.length > 0 ) flow += '\n';
  28049. flow += `\t// flow -> ${ slotName }\n\t`;
  28050. }
  28051. flow += `${ flowSlotData.code }\n\t`;
  28052. if ( node === mainNode && shaderStage !== 'compute' ) {
  28053. flow += '// result\n\n\t';
  28054. if ( shaderStage === 'vertex' ) {
  28055. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  28056. } else if ( shaderStage === 'fragment' ) {
  28057. if ( isOutputStruct ) {
  28058. stageData.returnType = outputNode.nodeType;
  28059. flow += `return ${ flowSlotData.result };`;
  28060. } else {
  28061. let structSnippet = '\t@location(0) color: vec4<f32>';
  28062. const builtins = this.getBuiltins( 'output' );
  28063. if ( builtins ) structSnippet += ',\n\t' + builtins;
  28064. stageData.returnType = 'OutputStruct';
  28065. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  28066. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  28067. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  28068. }
  28069. }
  28070. }
  28071. }
  28072. stageData.flow = flow;
  28073. }
  28074. if ( this.material !== null ) {
  28075. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  28076. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  28077. } else {
  28078. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  28079. }
  28080. }
  28081. getMethod( method, output = null ) {
  28082. let wgslMethod;
  28083. if ( output !== null ) {
  28084. wgslMethod = this._getWGSLMethod( method + '_' + output );
  28085. }
  28086. if ( wgslMethod === undefined ) {
  28087. wgslMethod = this._getWGSLMethod( method );
  28088. }
  28089. return wgslMethod || method;
  28090. }
  28091. getType( type ) {
  28092. return wgslTypeLib[ type ] || type;
  28093. }
  28094. isAvailable( name ) {
  28095. let result = supports[ name ];
  28096. if ( result === undefined ) {
  28097. if ( name === 'float32Filterable' ) {
  28098. result = this.renderer.hasFeature( 'float32-filterable' );
  28099. } else if ( name === 'clipDistance' ) {
  28100. result = this.renderer.hasFeature( 'clip-distances' );
  28101. }
  28102. supports[ name ] = result;
  28103. }
  28104. return result;
  28105. }
  28106. _getWGSLMethod( method ) {
  28107. if ( wgslPolyfill[ method ] !== undefined ) {
  28108. this._include( method );
  28109. }
  28110. return wgslMethods[ method ];
  28111. }
  28112. _include( name ) {
  28113. const codeNode = wgslPolyfill[ name ];
  28114. codeNode.build( this );
  28115. if ( this.currentFunctionNode !== null ) {
  28116. this.currentFunctionNode.includes.push( codeNode );
  28117. }
  28118. return codeNode;
  28119. }
  28120. _getWGSLVertexCode( shaderData ) {
  28121. return `${ this.getSignature() }
  28122. // directives
  28123. ${shaderData.directives}
  28124. // uniforms
  28125. ${shaderData.uniforms}
  28126. // varyings
  28127. ${shaderData.varyings}
  28128. var<private> varyings : VaryingsStruct;
  28129. // codes
  28130. ${shaderData.codes}
  28131. @vertex
  28132. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  28133. // vars
  28134. ${shaderData.vars}
  28135. // flow
  28136. ${shaderData.flow}
  28137. return varyings;
  28138. }
  28139. `;
  28140. }
  28141. _getWGSLFragmentCode( shaderData ) {
  28142. return `${ this.getSignature() }
  28143. // global
  28144. ${ diagnostics }
  28145. // uniforms
  28146. ${shaderData.uniforms}
  28147. // structs
  28148. ${shaderData.structs}
  28149. // codes
  28150. ${shaderData.codes}
  28151. @fragment
  28152. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  28153. // vars
  28154. ${shaderData.vars}
  28155. // flow
  28156. ${shaderData.flow}
  28157. }
  28158. `;
  28159. }
  28160. _getWGSLComputeCode( shaderData, workgroupSize ) {
  28161. return `${ this.getSignature() }
  28162. // directives
  28163. ${shaderData.directives}
  28164. // system
  28165. var<private> instanceIndex : u32;
  28166. // locals
  28167. ${shaderData.scopedArrays}
  28168. // uniforms
  28169. ${shaderData.uniforms}
  28170. // codes
  28171. ${shaderData.codes}
  28172. @compute @workgroup_size( ${workgroupSize} )
  28173. fn main( ${shaderData.attributes} ) {
  28174. // system
  28175. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  28176. // vars
  28177. ${shaderData.vars}
  28178. // flow
  28179. ${shaderData.flow}
  28180. }
  28181. `;
  28182. }
  28183. _getWGSLStruct( name, vars ) {
  28184. return `
  28185. struct ${name} {
  28186. ${vars}
  28187. };`;
  28188. }
  28189. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  28190. const structName = name + 'Struct';
  28191. const structSnippet = this._getWGSLStruct( structName, vars );
  28192. return `${structSnippet}
  28193. @binding( ${binding} ) @group( ${group} )
  28194. var<${access}> ${name} : ${structName};`;
  28195. }
  28196. }
  28197. class WebGPUUtils {
  28198. constructor( backend ) {
  28199. this.backend = backend;
  28200. }
  28201. getCurrentDepthStencilFormat( renderContext ) {
  28202. let format;
  28203. if ( renderContext.depthTexture !== null ) {
  28204. format = this.getTextureFormatGPU( renderContext.depthTexture );
  28205. } else if ( renderContext.depth && renderContext.stencil ) {
  28206. format = GPUTextureFormat.Depth24PlusStencil8;
  28207. } else if ( renderContext.depth ) {
  28208. format = GPUTextureFormat.Depth24Plus;
  28209. }
  28210. return format;
  28211. }
  28212. getTextureFormatGPU( texture ) {
  28213. return this.backend.get( texture ).format;
  28214. }
  28215. getTextureSampleData( texture ) {
  28216. let samples;
  28217. if ( texture.isFramebufferTexture ) {
  28218. samples = 1;
  28219. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  28220. const renderer = this.backend.renderer;
  28221. const renderTarget = renderer.getRenderTarget();
  28222. samples = renderTarget ? renderTarget.samples : renderer.samples;
  28223. } else if ( texture.renderTarget ) {
  28224. samples = texture.renderTarget.samples;
  28225. }
  28226. samples = samples || 1;
  28227. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  28228. const primarySamples = isMSAA ? 1 : samples;
  28229. return { samples, primarySamples, isMSAA };
  28230. }
  28231. getCurrentColorFormat( renderContext ) {
  28232. let format;
  28233. if ( renderContext.textures !== null ) {
  28234. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  28235. } else {
  28236. format = this.getPreferredCanvasFormat(); // default context format
  28237. }
  28238. return format;
  28239. }
  28240. getCurrentColorSpace( renderContext ) {
  28241. if ( renderContext.textures !== null ) {
  28242. return renderContext.textures[ 0 ].colorSpace;
  28243. }
  28244. return this.backend.renderer.outputColorSpace;
  28245. }
  28246. getPrimitiveTopology( object, material ) {
  28247. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  28248. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  28249. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  28250. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  28251. }
  28252. getSampleCount( sampleCount ) {
  28253. let count = 1;
  28254. if ( sampleCount > 1 ) {
  28255. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  28256. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  28257. if ( count === 2 ) {
  28258. count = 4;
  28259. }
  28260. }
  28261. return count;
  28262. }
  28263. getSampleCountRenderContext( renderContext ) {
  28264. if ( renderContext.textures !== null ) {
  28265. return this.getSampleCount( renderContext.sampleCount );
  28266. }
  28267. return this.getSampleCount( this.backend.renderer.samples );
  28268. }
  28269. getPreferredCanvasFormat() {
  28270. // TODO: Remove this check when Quest 34.5 is out
  28271. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  28272. if ( navigator.userAgent.includes( 'Quest' ) ) {
  28273. return GPUTextureFormat.BGRA8Unorm;
  28274. } else {
  28275. return navigator.gpu.getPreferredCanvasFormat();
  28276. }
  28277. }
  28278. }
  28279. const typedArraysToVertexFormatPrefix = new Map( [
  28280. [ Int8Array, [ 'sint8', 'snorm8' ]],
  28281. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  28282. [ Int16Array, [ 'sint16', 'snorm16' ]],
  28283. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  28284. [ Int32Array, [ 'sint32', 'snorm32' ]],
  28285. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  28286. [ Float32Array, [ 'float32', ]],
  28287. ] );
  28288. const typedAttributeToVertexFormatPrefix = new Map( [
  28289. [ Float16BufferAttribute, [ 'float16', ]],
  28290. ] );
  28291. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  28292. [ Int32Array, 'sint32' ],
  28293. [ Int16Array, 'sint32' ], // patch for INT16
  28294. [ Uint32Array, 'uint32' ],
  28295. [ Uint16Array, 'uint32' ], // patch for UINT16
  28296. [ Float32Array, 'float32' ]
  28297. ] );
  28298. class WebGPUAttributeUtils {
  28299. constructor( backend ) {
  28300. this.backend = backend;
  28301. }
  28302. createAttribute( attribute, usage ) {
  28303. const bufferAttribute = this._getBufferAttribute( attribute );
  28304. const backend = this.backend;
  28305. const bufferData = backend.get( bufferAttribute );
  28306. let buffer = bufferData.buffer;
  28307. if ( buffer === undefined ) {
  28308. const device = backend.device;
  28309. let array = bufferAttribute.array;
  28310. // patch for INT16 and UINT16
  28311. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  28312. const tempArray = new Uint32Array( array.length );
  28313. for ( let i = 0; i < array.length; i ++ ) {
  28314. tempArray[ i ] = array[ i ];
  28315. }
  28316. array = tempArray;
  28317. }
  28318. bufferAttribute.array = array;
  28319. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  28320. array = new array.constructor( bufferAttribute.count * 4 );
  28321. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  28322. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  28323. }
  28324. // Update BufferAttribute
  28325. bufferAttribute.itemSize = 4;
  28326. bufferAttribute.array = array;
  28327. }
  28328. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  28329. buffer = device.createBuffer( {
  28330. label: bufferAttribute.name,
  28331. size: size,
  28332. usage: usage,
  28333. mappedAtCreation: true
  28334. } );
  28335. new array.constructor( buffer.getMappedRange() ).set( array );
  28336. buffer.unmap();
  28337. bufferData.buffer = buffer;
  28338. }
  28339. }
  28340. updateAttribute( attribute ) {
  28341. const bufferAttribute = this._getBufferAttribute( attribute );
  28342. const backend = this.backend;
  28343. const device = backend.device;
  28344. const buffer = backend.get( bufferAttribute ).buffer;
  28345. const array = bufferAttribute.array;
  28346. const isTypedArray = this._isTypedArray( array );
  28347. const updateRanges = bufferAttribute.updateRanges;
  28348. if ( updateRanges.length === 0 ) {
  28349. // Not using update ranges
  28350. device.queue.writeBuffer(
  28351. buffer,
  28352. 0,
  28353. array,
  28354. 0
  28355. );
  28356. } else {
  28357. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  28358. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  28359. const range = updateRanges[ i ];
  28360. const dataOffset = range.start * byteOffsetFactor;
  28361. const size = range.count * byteOffsetFactor;
  28362. device.queue.writeBuffer(
  28363. buffer,
  28364. 0,
  28365. array,
  28366. dataOffset,
  28367. size
  28368. );
  28369. }
  28370. bufferAttribute.clearUpdateRanges();
  28371. }
  28372. }
  28373. createShaderVertexBuffers( renderObject ) {
  28374. const attributes = renderObject.getAttributes();
  28375. const vertexBuffers = new Map();
  28376. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  28377. const geometryAttribute = attributes[ slot ];
  28378. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  28379. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  28380. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  28381. if ( vertexBufferLayout === undefined ) {
  28382. let arrayStride, stepMode;
  28383. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  28384. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  28385. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  28386. } else {
  28387. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  28388. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  28389. }
  28390. // patch for INT16 and UINT16
  28391. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  28392. arrayStride = 4;
  28393. }
  28394. vertexBufferLayout = {
  28395. arrayStride,
  28396. attributes: [],
  28397. stepMode
  28398. };
  28399. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  28400. }
  28401. const format = this._getVertexFormat( geometryAttribute );
  28402. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  28403. vertexBufferLayout.attributes.push( {
  28404. shaderLocation: slot,
  28405. offset,
  28406. format
  28407. } );
  28408. }
  28409. return Array.from( vertexBuffers.values() );
  28410. }
  28411. destroyAttribute( attribute ) {
  28412. const backend = this.backend;
  28413. const data = backend.get( this._getBufferAttribute( attribute ) );
  28414. data.buffer.destroy();
  28415. backend.delete( attribute );
  28416. }
  28417. async getArrayBufferAsync( attribute ) {
  28418. const backend = this.backend;
  28419. const device = backend.device;
  28420. const data = backend.get( this._getBufferAttribute( attribute ) );
  28421. const bufferGPU = data.buffer;
  28422. const size = bufferGPU.size;
  28423. const readBufferGPU = device.createBuffer( {
  28424. label: attribute.name,
  28425. size,
  28426. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  28427. } );
  28428. const cmdEncoder = device.createCommandEncoder( {} );
  28429. cmdEncoder.copyBufferToBuffer(
  28430. bufferGPU,
  28431. 0,
  28432. readBufferGPU,
  28433. 0,
  28434. size
  28435. );
  28436. readBufferGPU.unmap();
  28437. const gpuCommands = cmdEncoder.finish();
  28438. device.queue.submit( [ gpuCommands ] );
  28439. await readBufferGPU.mapAsync( GPUMapMode.READ );
  28440. const arrayBuffer = readBufferGPU.getMappedRange();
  28441. return arrayBuffer;
  28442. }
  28443. _getVertexFormat( geometryAttribute ) {
  28444. const { itemSize, normalized } = geometryAttribute;
  28445. const ArrayType = geometryAttribute.array.constructor;
  28446. const AttributeType = geometryAttribute.constructor;
  28447. let format;
  28448. if ( itemSize == 1 ) {
  28449. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  28450. } else {
  28451. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  28452. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  28453. if ( prefix ) {
  28454. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  28455. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  28456. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  28457. if ( paddedItemSize % 1 ) {
  28458. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  28459. }
  28460. format = `${prefix}x${paddedItemSize}`;
  28461. }
  28462. }
  28463. if ( ! format ) {
  28464. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  28465. }
  28466. return format;
  28467. }
  28468. _isTypedArray( array ) {
  28469. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  28470. }
  28471. _getBufferAttribute( attribute ) {
  28472. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  28473. return attribute;
  28474. }
  28475. }
  28476. class WebGPUBindingUtils {
  28477. constructor( backend ) {
  28478. this.backend = backend;
  28479. this.bindGroupLayoutCache = new WeakMap();
  28480. }
  28481. createBindingsLayout( bindGroup ) {
  28482. const backend = this.backend;
  28483. const device = backend.device;
  28484. const entries = [];
  28485. let index = 0;
  28486. for ( const binding of bindGroup.bindings ) {
  28487. const bindingGPU = {
  28488. binding: index ++,
  28489. visibility: binding.visibility
  28490. };
  28491. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  28492. const buffer = {}; // GPUBufferBindingLayout
  28493. if ( binding.isStorageBuffer ) {
  28494. if ( binding.visibility & 4 ) {
  28495. // compute
  28496. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  28497. buffer.type = GPUBufferBindingType.Storage;
  28498. } else {
  28499. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  28500. }
  28501. } else {
  28502. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  28503. }
  28504. }
  28505. bindingGPU.buffer = buffer;
  28506. } else if ( binding.isSampler ) {
  28507. const sampler = {}; // GPUSamplerBindingLayout
  28508. if ( binding.texture.isDepthTexture ) {
  28509. if ( binding.texture.compareFunction !== null ) {
  28510. sampler.type = 'comparison';
  28511. }
  28512. }
  28513. bindingGPU.sampler = sampler;
  28514. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  28515. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  28516. } else if ( binding.isSampledTexture && binding.store ) {
  28517. const storageTexture = {}; // GPUStorageTextureBindingLayout
  28518. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  28519. const access = binding.access;
  28520. if ( access === NodeAccess.READ_WRITE ) {
  28521. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  28522. } else if ( access === NodeAccess.WRITE_ONLY ) {
  28523. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  28524. } else {
  28525. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  28526. }
  28527. bindingGPU.storageTexture = storageTexture;
  28528. } else if ( binding.isSampledTexture ) {
  28529. const texture = {}; // GPUTextureBindingLayout
  28530. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  28531. if ( primarySamples > 1 ) {
  28532. texture.multisampled = true;
  28533. if ( ! binding.texture.isDepthTexture ) {
  28534. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  28535. }
  28536. }
  28537. if ( binding.texture.isDepthTexture ) {
  28538. texture.sampleType = GPUTextureSampleType.Depth;
  28539. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  28540. const type = binding.texture.type;
  28541. if ( type === IntType ) {
  28542. texture.sampleType = GPUTextureSampleType.SInt;
  28543. } else if ( type === UnsignedIntType ) {
  28544. texture.sampleType = GPUTextureSampleType.UInt;
  28545. } else if ( type === FloatType ) {
  28546. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  28547. texture.sampleType = GPUTextureSampleType.Float;
  28548. } else {
  28549. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  28550. }
  28551. }
  28552. }
  28553. if ( binding.isSampledCubeTexture ) {
  28554. texture.viewDimension = GPUTextureViewDimension.Cube;
  28555. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  28556. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  28557. } else if ( binding.isSampledTexture3D ) {
  28558. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  28559. }
  28560. bindingGPU.texture = texture;
  28561. } else {
  28562. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  28563. }
  28564. entries.push( bindingGPU );
  28565. }
  28566. return device.createBindGroupLayout( { entries } );
  28567. }
  28568. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  28569. const { backend, bindGroupLayoutCache } = this;
  28570. const bindingsData = backend.get( bindGroup );
  28571. // setup (static) binding layout and (dynamic) binding group
  28572. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  28573. if ( bindLayoutGPU === undefined ) {
  28574. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  28575. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  28576. }
  28577. let bindGroupGPU;
  28578. if ( cacheIndex > 0 ) {
  28579. if ( bindingsData.groups === undefined ) {
  28580. bindingsData.groups = [];
  28581. bindingsData.versions = [];
  28582. }
  28583. if ( bindingsData.versions[ cacheIndex ] === version ) {
  28584. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  28585. }
  28586. }
  28587. if ( bindGroupGPU === undefined ) {
  28588. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  28589. if ( cacheIndex > 0 ) {
  28590. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  28591. bindingsData.versions[ cacheIndex ] = version;
  28592. }
  28593. }
  28594. bindingsData.group = bindGroupGPU;
  28595. bindingsData.layout = bindLayoutGPU;
  28596. }
  28597. updateBinding( binding ) {
  28598. const backend = this.backend;
  28599. const device = backend.device;
  28600. const buffer = binding.buffer;
  28601. const bufferGPU = backend.get( binding ).buffer;
  28602. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  28603. }
  28604. createBindGroup( bindGroup, layoutGPU ) {
  28605. const backend = this.backend;
  28606. const device = backend.device;
  28607. let bindingPoint = 0;
  28608. const entriesGPU = [];
  28609. for ( const binding of bindGroup.bindings ) {
  28610. if ( binding.isUniformBuffer ) {
  28611. const bindingData = backend.get( binding );
  28612. if ( bindingData.buffer === undefined ) {
  28613. const byteLength = binding.byteLength;
  28614. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  28615. const bufferGPU = device.createBuffer( {
  28616. label: 'bindingBuffer_' + binding.name,
  28617. size: byteLength,
  28618. usage: usage
  28619. } );
  28620. bindingData.buffer = bufferGPU;
  28621. }
  28622. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  28623. } else if ( binding.isStorageBuffer ) {
  28624. const bindingData = backend.get( binding );
  28625. if ( bindingData.buffer === undefined ) {
  28626. const attribute = binding.attribute;
  28627. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  28628. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  28629. bindingData.buffer = backend.get( attribute ).buffer;
  28630. }
  28631. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  28632. } else if ( binding.isSampler ) {
  28633. const textureGPU = backend.get( binding.texture );
  28634. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  28635. } else if ( binding.isSampledTexture ) {
  28636. const textureData = backend.get( binding.texture );
  28637. let resourceGPU;
  28638. if ( textureData.externalTexture !== undefined ) {
  28639. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  28640. } else {
  28641. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  28642. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  28643. resourceGPU = textureData[ propertyName ];
  28644. if ( resourceGPU === undefined ) {
  28645. const aspectGPU = GPUTextureAspect.All;
  28646. let dimensionViewGPU;
  28647. if ( binding.isSampledCubeTexture ) {
  28648. dimensionViewGPU = GPUTextureViewDimension.Cube;
  28649. } else if ( binding.isSampledTexture3D ) {
  28650. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  28651. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  28652. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  28653. } else {
  28654. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  28655. }
  28656. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  28657. }
  28658. }
  28659. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  28660. }
  28661. bindingPoint ++;
  28662. }
  28663. return device.createBindGroup( {
  28664. label: 'bindGroup_' + bindGroup.name,
  28665. layout: layoutGPU,
  28666. entries: entriesGPU
  28667. } );
  28668. }
  28669. }
  28670. class WebGPUPipelineUtils {
  28671. constructor( backend ) {
  28672. this.backend = backend;
  28673. }
  28674. _getSampleCount( renderObjectContext ) {
  28675. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  28676. }
  28677. createRenderPipeline( renderObject, promises ) {
  28678. const { object, material, geometry, pipeline } = renderObject;
  28679. const { vertexProgram, fragmentProgram } = pipeline;
  28680. const backend = this.backend;
  28681. const device = backend.device;
  28682. const utils = backend.utils;
  28683. const pipelineData = backend.get( pipeline );
  28684. // bind group layouts
  28685. const bindGroupLayouts = [];
  28686. for ( const bindGroup of renderObject.getBindings() ) {
  28687. const bindingsData = backend.get( bindGroup );
  28688. bindGroupLayouts.push( bindingsData.layout );
  28689. }
  28690. // vertex buffers
  28691. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  28692. // blending
  28693. let blending;
  28694. if ( material.transparent === true && material.blending !== NoBlending ) {
  28695. blending = this._getBlending( material );
  28696. }
  28697. // stencil
  28698. let stencilFront = {};
  28699. if ( material.stencilWrite === true ) {
  28700. stencilFront = {
  28701. compare: this._getStencilCompare( material ),
  28702. failOp: this._getStencilOperation( material.stencilFail ),
  28703. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  28704. passOp: this._getStencilOperation( material.stencilZPass )
  28705. };
  28706. }
  28707. const colorWriteMask = this._getColorWriteMask( material );
  28708. const targets = [];
  28709. if ( renderObject.context.textures !== null ) {
  28710. const textures = renderObject.context.textures;
  28711. for ( let i = 0; i < textures.length; i ++ ) {
  28712. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  28713. targets.push( {
  28714. format: colorFormat,
  28715. blend: blending,
  28716. writeMask: colorWriteMask
  28717. } );
  28718. }
  28719. } else {
  28720. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  28721. targets.push( {
  28722. format: colorFormat,
  28723. blend: blending,
  28724. writeMask: colorWriteMask
  28725. } );
  28726. }
  28727. const vertexModule = backend.get( vertexProgram ).module;
  28728. const fragmentModule = backend.get( fragmentProgram ).module;
  28729. const primitiveState = this._getPrimitiveState( object, geometry, material );
  28730. const depthCompare = this._getDepthCompare( material );
  28731. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  28732. const sampleCount = this._getSampleCount( renderObject.context );
  28733. const pipelineDescriptor = {
  28734. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  28735. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  28736. fragment: Object.assign( {}, fragmentModule, { targets } ),
  28737. primitive: primitiveState,
  28738. multisample: {
  28739. count: sampleCount,
  28740. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  28741. },
  28742. layout: device.createPipelineLayout( {
  28743. bindGroupLayouts
  28744. } )
  28745. };
  28746. const depthStencil = {};
  28747. const renderDepth = renderObject.context.depth;
  28748. const renderStencil = renderObject.context.stencil;
  28749. if ( renderDepth === true || renderStencil === true ) {
  28750. if ( renderDepth === true ) {
  28751. depthStencil.format = depthStencilFormat;
  28752. depthStencil.depthWriteEnabled = material.depthWrite;
  28753. depthStencil.depthCompare = depthCompare;
  28754. }
  28755. if ( renderStencil === true ) {
  28756. depthStencil.stencilFront = stencilFront;
  28757. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  28758. depthStencil.stencilReadMask = material.stencilFuncMask;
  28759. depthStencil.stencilWriteMask = material.stencilWriteMask;
  28760. }
  28761. pipelineDescriptor.depthStencil = depthStencil;
  28762. }
  28763. if ( promises === null ) {
  28764. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  28765. } else {
  28766. const p = new Promise( ( resolve /*, reject*/ ) => {
  28767. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  28768. pipelineData.pipeline = pipeline;
  28769. resolve();
  28770. } );
  28771. } );
  28772. promises.push( p );
  28773. }
  28774. }
  28775. createBundleEncoder( renderContext ) {
  28776. const backend = this.backend;
  28777. const { utils, device } = backend;
  28778. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  28779. const colorFormat = utils.getCurrentColorFormat( renderContext );
  28780. const sampleCount = this._getSampleCount( renderContext );
  28781. const descriptor = {
  28782. label: 'renderBundleEncoder',
  28783. colorFormats: [ colorFormat ],
  28784. depthStencilFormat,
  28785. sampleCount
  28786. };
  28787. return device.createRenderBundleEncoder( descriptor );
  28788. }
  28789. createComputePipeline( pipeline, bindings ) {
  28790. const backend = this.backend;
  28791. const device = backend.device;
  28792. const computeProgram = backend.get( pipeline.computeProgram ).module;
  28793. const pipelineGPU = backend.get( pipeline );
  28794. // bind group layouts
  28795. const bindGroupLayouts = [];
  28796. for ( const bindingsGroup of bindings ) {
  28797. const bindingsData = backend.get( bindingsGroup );
  28798. bindGroupLayouts.push( bindingsData.layout );
  28799. }
  28800. pipelineGPU.pipeline = device.createComputePipeline( {
  28801. compute: computeProgram,
  28802. layout: device.createPipelineLayout( {
  28803. bindGroupLayouts
  28804. } )
  28805. } );
  28806. }
  28807. _getBlending( material ) {
  28808. let color, alpha;
  28809. const blending = material.blending;
  28810. const blendSrc = material.blendSrc;
  28811. const blendDst = material.blendDst;
  28812. const blendEquation = material.blendEquation;
  28813. if ( blending === CustomBlending ) {
  28814. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  28815. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  28816. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  28817. color = {
  28818. srcFactor: this._getBlendFactor( blendSrc ),
  28819. dstFactor: this._getBlendFactor( blendDst ),
  28820. operation: this._getBlendOperation( blendEquation )
  28821. };
  28822. alpha = {
  28823. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  28824. dstFactor: this._getBlendFactor( blendDstAlpha ),
  28825. operation: this._getBlendOperation( blendEquationAlpha )
  28826. };
  28827. } else {
  28828. const premultipliedAlpha = material.premultipliedAlpha;
  28829. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  28830. color = {
  28831. srcFactor: srcRGB,
  28832. dstFactor: dstRGB,
  28833. operation: GPUBlendOperation.Add
  28834. };
  28835. alpha = {
  28836. srcFactor: srcAlpha,
  28837. dstFactor: dstAlpha,
  28838. operation: GPUBlendOperation.Add
  28839. };
  28840. };
  28841. if ( premultipliedAlpha ) {
  28842. switch ( blending ) {
  28843. case NormalBlending:
  28844. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  28845. break;
  28846. case AdditiveBlending:
  28847. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  28848. break;
  28849. case SubtractiveBlending:
  28850. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  28851. break;
  28852. case MultiplyBlending:
  28853. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  28854. break;
  28855. }
  28856. } else {
  28857. switch ( blending ) {
  28858. case NormalBlending:
  28859. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  28860. break;
  28861. case AdditiveBlending:
  28862. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  28863. break;
  28864. case SubtractiveBlending:
  28865. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  28866. break;
  28867. case MultiplyBlending:
  28868. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  28869. break;
  28870. }
  28871. }
  28872. }
  28873. if ( color !== undefined && alpha !== undefined ) {
  28874. return { color, alpha };
  28875. } else {
  28876. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  28877. }
  28878. }
  28879. _getBlendFactor( blend ) {
  28880. let blendFactor;
  28881. switch ( blend ) {
  28882. case ZeroFactor:
  28883. blendFactor = GPUBlendFactor.Zero;
  28884. break;
  28885. case OneFactor:
  28886. blendFactor = GPUBlendFactor.One;
  28887. break;
  28888. case SrcColorFactor:
  28889. blendFactor = GPUBlendFactor.Src;
  28890. break;
  28891. case OneMinusSrcColorFactor:
  28892. blendFactor = GPUBlendFactor.OneMinusSrc;
  28893. break;
  28894. case SrcAlphaFactor:
  28895. blendFactor = GPUBlendFactor.SrcAlpha;
  28896. break;
  28897. case OneMinusSrcAlphaFactor:
  28898. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  28899. break;
  28900. case DstColorFactor:
  28901. blendFactor = GPUBlendFactor.Dst;
  28902. break;
  28903. case OneMinusDstColorFactor:
  28904. blendFactor = GPUBlendFactor.OneMinusDstColor;
  28905. break;
  28906. case DstAlphaFactor:
  28907. blendFactor = GPUBlendFactor.DstAlpha;
  28908. break;
  28909. case OneMinusDstAlphaFactor:
  28910. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  28911. break;
  28912. case SrcAlphaSaturateFactor:
  28913. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  28914. break;
  28915. case BlendColorFactor:
  28916. blendFactor = GPUBlendFactor.Constant;
  28917. break;
  28918. case OneMinusBlendColorFactor:
  28919. blendFactor = GPUBlendFactor.OneMinusConstant;
  28920. break;
  28921. default:
  28922. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  28923. }
  28924. return blendFactor;
  28925. }
  28926. _getStencilCompare( material ) {
  28927. let stencilCompare;
  28928. const stencilFunc = material.stencilFunc;
  28929. switch ( stencilFunc ) {
  28930. case NeverStencilFunc:
  28931. stencilCompare = GPUCompareFunction.Never;
  28932. break;
  28933. case AlwaysStencilFunc:
  28934. stencilCompare = GPUCompareFunction.Always;
  28935. break;
  28936. case LessStencilFunc:
  28937. stencilCompare = GPUCompareFunction.Less;
  28938. break;
  28939. case LessEqualStencilFunc:
  28940. stencilCompare = GPUCompareFunction.LessEqual;
  28941. break;
  28942. case EqualStencilFunc:
  28943. stencilCompare = GPUCompareFunction.Equal;
  28944. break;
  28945. case GreaterEqualStencilFunc:
  28946. stencilCompare = GPUCompareFunction.GreaterEqual;
  28947. break;
  28948. case GreaterStencilFunc:
  28949. stencilCompare = GPUCompareFunction.Greater;
  28950. break;
  28951. case NotEqualStencilFunc:
  28952. stencilCompare = GPUCompareFunction.NotEqual;
  28953. break;
  28954. default:
  28955. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  28956. }
  28957. return stencilCompare;
  28958. }
  28959. _getStencilOperation( op ) {
  28960. let stencilOperation;
  28961. switch ( op ) {
  28962. case KeepStencilOp:
  28963. stencilOperation = GPUStencilOperation.Keep;
  28964. break;
  28965. case ZeroStencilOp:
  28966. stencilOperation = GPUStencilOperation.Zero;
  28967. break;
  28968. case ReplaceStencilOp:
  28969. stencilOperation = GPUStencilOperation.Replace;
  28970. break;
  28971. case InvertStencilOp:
  28972. stencilOperation = GPUStencilOperation.Invert;
  28973. break;
  28974. case IncrementStencilOp:
  28975. stencilOperation = GPUStencilOperation.IncrementClamp;
  28976. break;
  28977. case DecrementStencilOp:
  28978. stencilOperation = GPUStencilOperation.DecrementClamp;
  28979. break;
  28980. case IncrementWrapStencilOp:
  28981. stencilOperation = GPUStencilOperation.IncrementWrap;
  28982. break;
  28983. case DecrementWrapStencilOp:
  28984. stencilOperation = GPUStencilOperation.DecrementWrap;
  28985. break;
  28986. default:
  28987. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  28988. }
  28989. return stencilOperation;
  28990. }
  28991. _getBlendOperation( blendEquation ) {
  28992. let blendOperation;
  28993. switch ( blendEquation ) {
  28994. case AddEquation:
  28995. blendOperation = GPUBlendOperation.Add;
  28996. break;
  28997. case SubtractEquation:
  28998. blendOperation = GPUBlendOperation.Subtract;
  28999. break;
  29000. case ReverseSubtractEquation:
  29001. blendOperation = GPUBlendOperation.ReverseSubtract;
  29002. break;
  29003. case MinEquation:
  29004. blendOperation = GPUBlendOperation.Min;
  29005. break;
  29006. case MaxEquation:
  29007. blendOperation = GPUBlendOperation.Max;
  29008. break;
  29009. default:
  29010. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  29011. }
  29012. return blendOperation;
  29013. }
  29014. _getPrimitiveState( object, geometry, material ) {
  29015. const descriptor = {};
  29016. const utils = this.backend.utils;
  29017. descriptor.topology = utils.getPrimitiveTopology( object, material );
  29018. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  29019. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  29020. }
  29021. switch ( material.side ) {
  29022. case FrontSide:
  29023. descriptor.frontFace = GPUFrontFace.CCW;
  29024. descriptor.cullMode = GPUCullMode.Back;
  29025. break;
  29026. case BackSide:
  29027. descriptor.frontFace = GPUFrontFace.CCW;
  29028. descriptor.cullMode = GPUCullMode.Front;
  29029. break;
  29030. case DoubleSide:
  29031. descriptor.frontFace = GPUFrontFace.CCW;
  29032. descriptor.cullMode = GPUCullMode.None;
  29033. break;
  29034. default:
  29035. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  29036. break;
  29037. }
  29038. return descriptor;
  29039. }
  29040. _getColorWriteMask( material ) {
  29041. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  29042. }
  29043. _getDepthCompare( material ) {
  29044. let depthCompare;
  29045. if ( material.depthTest === false ) {
  29046. depthCompare = GPUCompareFunction.Always;
  29047. } else {
  29048. const depthFunc = material.depthFunc;
  29049. switch ( depthFunc ) {
  29050. case NeverDepth:
  29051. depthCompare = GPUCompareFunction.Never;
  29052. break;
  29053. case AlwaysDepth:
  29054. depthCompare = GPUCompareFunction.Always;
  29055. break;
  29056. case LessDepth:
  29057. depthCompare = GPUCompareFunction.Less;
  29058. break;
  29059. case LessEqualDepth:
  29060. depthCompare = GPUCompareFunction.LessEqual;
  29061. break;
  29062. case EqualDepth:
  29063. depthCompare = GPUCompareFunction.Equal;
  29064. break;
  29065. case GreaterEqualDepth:
  29066. depthCompare = GPUCompareFunction.GreaterEqual;
  29067. break;
  29068. case GreaterDepth:
  29069. depthCompare = GPUCompareFunction.Greater;
  29070. break;
  29071. case NotEqualDepth:
  29072. depthCompare = GPUCompareFunction.NotEqual;
  29073. break;
  29074. default:
  29075. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  29076. }
  29077. }
  29078. return depthCompare;
  29079. }
  29080. }
  29081. /*// debugger tools
  29082. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  29083. //*/
  29084. //
  29085. class WebGPUBackend extends Backend {
  29086. constructor( parameters = {} ) {
  29087. super( parameters );
  29088. this.isWebGPUBackend = true;
  29089. // some parameters require default values other than "undefined"
  29090. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  29091. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  29092. this.trackTimestamp = ( parameters.trackTimestamp === true );
  29093. this.device = null;
  29094. this.context = null;
  29095. this.colorBuffer = null;
  29096. this.defaultRenderPassdescriptor = null;
  29097. this.utils = new WebGPUUtils( this );
  29098. this.attributeUtils = new WebGPUAttributeUtils( this );
  29099. this.bindingUtils = new WebGPUBindingUtils( this );
  29100. this.pipelineUtils = new WebGPUPipelineUtils( this );
  29101. this.textureUtils = new WebGPUTextureUtils( this );
  29102. this.occludedResolveCache = new Map();
  29103. }
  29104. async init( renderer ) {
  29105. await super.init( renderer );
  29106. //
  29107. const parameters = this.parameters;
  29108. // create the device if it is not passed with parameters
  29109. let device;
  29110. if ( parameters.device === undefined ) {
  29111. const adapterOptions = {
  29112. powerPreference: parameters.powerPreference
  29113. };
  29114. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  29115. if ( adapter === null ) {
  29116. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  29117. }
  29118. // feature support
  29119. const features = Object.values( GPUFeatureName );
  29120. const supportedFeatures = [];
  29121. for ( const name of features ) {
  29122. if ( adapter.features.has( name ) ) {
  29123. supportedFeatures.push( name );
  29124. }
  29125. }
  29126. const deviceDescriptor = {
  29127. requiredFeatures: supportedFeatures,
  29128. requiredLimits: parameters.requiredLimits
  29129. };
  29130. device = await adapter.requestDevice( deviceDescriptor );
  29131. } else {
  29132. device = parameters.device;
  29133. }
  29134. device.lost.then( ( info ) => {
  29135. const deviceLossInfo = {
  29136. api: 'WebGPU',
  29137. message: info.message || 'Unknown reason',
  29138. reason: info.reason || null,
  29139. originalEvent: info
  29140. };
  29141. renderer.onDeviceLost( deviceLossInfo );
  29142. } );
  29143. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  29144. this.device = device;
  29145. this.context = context;
  29146. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  29147. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  29148. this.context.configure( {
  29149. device: this.device,
  29150. format: this.utils.getPreferredCanvasFormat(),
  29151. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  29152. alphaMode: alphaMode
  29153. } );
  29154. this.updateSize();
  29155. }
  29156. get coordinateSystem() {
  29157. return WebGPUCoordinateSystem;
  29158. }
  29159. async getArrayBufferAsync( attribute ) {
  29160. return await this.attributeUtils.getArrayBufferAsync( attribute );
  29161. }
  29162. getContext() {
  29163. return this.context;
  29164. }
  29165. _getDefaultRenderPassDescriptor() {
  29166. let descriptor = this.defaultRenderPassdescriptor;
  29167. if ( descriptor === null ) {
  29168. const renderer = this.renderer;
  29169. descriptor = {
  29170. colorAttachments: [ {
  29171. view: null
  29172. } ],
  29173. };
  29174. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  29175. descriptor.depthStencilAttachment = {
  29176. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  29177. };
  29178. }
  29179. const colorAttachment = descriptor.colorAttachments[ 0 ];
  29180. if ( this.renderer.samples > 0 ) {
  29181. colorAttachment.view = this.colorBuffer.createView();
  29182. } else {
  29183. colorAttachment.resolveTarget = undefined;
  29184. }
  29185. this.defaultRenderPassdescriptor = descriptor;
  29186. }
  29187. const colorAttachment = descriptor.colorAttachments[ 0 ];
  29188. if ( this.renderer.samples > 0 ) {
  29189. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  29190. } else {
  29191. colorAttachment.view = this.context.getCurrentTexture().createView();
  29192. }
  29193. return descriptor;
  29194. }
  29195. _getRenderPassDescriptor( renderContext ) {
  29196. const renderTarget = renderContext.renderTarget;
  29197. const renderTargetData = this.get( renderTarget );
  29198. let descriptors = renderTargetData.descriptors;
  29199. if ( descriptors === undefined ||
  29200. renderTargetData.width !== renderTarget.width ||
  29201. renderTargetData.height !== renderTarget.height ||
  29202. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  29203. renderTargetData.samples !== renderTarget.samples
  29204. ) {
  29205. descriptors = {};
  29206. renderTargetData.descriptors = descriptors;
  29207. // dispose
  29208. const onDispose = () => {
  29209. renderTarget.removeEventListener( 'dispose', onDispose );
  29210. this.delete( renderTarget );
  29211. };
  29212. renderTarget.addEventListener( 'dispose', onDispose );
  29213. }
  29214. const cacheKey = renderContext.getCacheKey();
  29215. let descriptor = descriptors[ cacheKey ];
  29216. if ( descriptor === undefined ) {
  29217. const textures = renderContext.textures;
  29218. const colorAttachments = [];
  29219. for ( let i = 0; i < textures.length; i ++ ) {
  29220. const textureData = this.get( textures[ i ] );
  29221. const textureView = textureData.texture.createView( {
  29222. baseMipLevel: renderContext.activeMipmapLevel,
  29223. mipLevelCount: 1,
  29224. baseArrayLayer: renderContext.activeCubeFace,
  29225. dimension: GPUTextureViewDimension.TwoD
  29226. } );
  29227. let view, resolveTarget;
  29228. if ( textureData.msaaTexture !== undefined ) {
  29229. view = textureData.msaaTexture.createView();
  29230. resolveTarget = textureView;
  29231. } else {
  29232. view = textureView;
  29233. resolveTarget = undefined;
  29234. }
  29235. colorAttachments.push( {
  29236. view,
  29237. resolveTarget,
  29238. loadOp: GPULoadOp.Load,
  29239. storeOp: GPUStoreOp.Store
  29240. } );
  29241. }
  29242. descriptor = {
  29243. colorAttachments,
  29244. };
  29245. if ( renderContext.depth ) {
  29246. const depthTextureData = this.get( renderContext.depthTexture );
  29247. const depthStencilAttachment = {
  29248. view: depthTextureData.texture.createView()
  29249. };
  29250. descriptor.depthStencilAttachment = depthStencilAttachment;
  29251. }
  29252. descriptors[ cacheKey ] = descriptor;
  29253. renderTargetData.width = renderTarget.width;
  29254. renderTargetData.height = renderTarget.height;
  29255. renderTargetData.samples = renderTarget.samples;
  29256. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  29257. }
  29258. return descriptor;
  29259. }
  29260. beginRender( renderContext ) {
  29261. const renderContextData = this.get( renderContext );
  29262. const device = this.device;
  29263. const occlusionQueryCount = renderContext.occlusionQueryCount;
  29264. let occlusionQuerySet;
  29265. if ( occlusionQueryCount > 0 ) {
  29266. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  29267. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  29268. // Get a reference to the array of objects with queries. The renderContextData property
  29269. // can be changed by another render pass before the buffer.mapAsyc() completes.
  29270. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  29271. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  29272. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  29273. //
  29274. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  29275. renderContextData.occlusionQuerySet = occlusionQuerySet;
  29276. renderContextData.occlusionQueryIndex = 0;
  29277. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  29278. renderContextData.lastOcclusionObject = null;
  29279. }
  29280. let descriptor;
  29281. if ( renderContext.textures === null ) {
  29282. descriptor = this._getDefaultRenderPassDescriptor();
  29283. } else {
  29284. descriptor = this._getRenderPassDescriptor( renderContext );
  29285. }
  29286. this.initTimestampQuery( renderContext, descriptor );
  29287. descriptor.occlusionQuerySet = occlusionQuerySet;
  29288. const depthStencilAttachment = descriptor.depthStencilAttachment;
  29289. if ( renderContext.textures !== null ) {
  29290. const colorAttachments = descriptor.colorAttachments;
  29291. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  29292. const colorAttachment = colorAttachments[ i ];
  29293. if ( renderContext.clearColor ) {
  29294. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  29295. colorAttachment.loadOp = GPULoadOp.Clear;
  29296. colorAttachment.storeOp = GPUStoreOp.Store;
  29297. } else {
  29298. colorAttachment.loadOp = GPULoadOp.Load;
  29299. colorAttachment.storeOp = GPUStoreOp.Store;
  29300. }
  29301. }
  29302. } else {
  29303. const colorAttachment = descriptor.colorAttachments[ 0 ];
  29304. if ( renderContext.clearColor ) {
  29305. colorAttachment.clearValue = renderContext.clearColorValue;
  29306. colorAttachment.loadOp = GPULoadOp.Clear;
  29307. colorAttachment.storeOp = GPUStoreOp.Store;
  29308. } else {
  29309. colorAttachment.loadOp = GPULoadOp.Load;
  29310. colorAttachment.storeOp = GPUStoreOp.Store;
  29311. }
  29312. }
  29313. //
  29314. if ( renderContext.depth ) {
  29315. if ( renderContext.clearDepth ) {
  29316. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  29317. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  29318. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  29319. } else {
  29320. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  29321. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  29322. }
  29323. }
  29324. if ( renderContext.stencil ) {
  29325. if ( renderContext.clearStencil ) {
  29326. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  29327. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  29328. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  29329. } else {
  29330. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  29331. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  29332. }
  29333. }
  29334. //
  29335. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  29336. const currentPass = encoder.beginRenderPass( descriptor );
  29337. //
  29338. renderContextData.descriptor = descriptor;
  29339. renderContextData.encoder = encoder;
  29340. renderContextData.currentPass = currentPass;
  29341. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  29342. renderContextData.renderBundles = [];
  29343. //
  29344. if ( renderContext.viewport ) {
  29345. this.updateViewport( renderContext );
  29346. }
  29347. if ( renderContext.scissor ) {
  29348. const { x, y, width, height } = renderContext.scissorValue;
  29349. currentPass.setScissorRect( x, y, width, height );
  29350. }
  29351. }
  29352. finishRender( renderContext ) {
  29353. const renderContextData = this.get( renderContext );
  29354. const occlusionQueryCount = renderContext.occlusionQueryCount;
  29355. if ( renderContextData.renderBundles.length > 0 ) {
  29356. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  29357. }
  29358. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  29359. renderContextData.currentPass.endOcclusionQuery();
  29360. }
  29361. renderContextData.currentPass.end();
  29362. if ( occlusionQueryCount > 0 ) {
  29363. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  29364. //
  29365. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  29366. if ( queryResolveBuffer === undefined ) {
  29367. queryResolveBuffer = this.device.createBuffer(
  29368. {
  29369. size: bufferSize,
  29370. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  29371. }
  29372. );
  29373. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  29374. }
  29375. //
  29376. const readBuffer = this.device.createBuffer(
  29377. {
  29378. size: bufferSize,
  29379. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  29380. }
  29381. );
  29382. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  29383. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  29384. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  29385. renderContextData.occlusionQueryBuffer = readBuffer;
  29386. //
  29387. this.resolveOccludedAsync( renderContext );
  29388. }
  29389. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  29390. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  29391. //
  29392. if ( renderContext.textures !== null ) {
  29393. const textures = renderContext.textures;
  29394. for ( let i = 0; i < textures.length; i ++ ) {
  29395. const texture = textures[ i ];
  29396. if ( texture.generateMipmaps === true ) {
  29397. this.textureUtils.generateMipmaps( texture );
  29398. }
  29399. }
  29400. }
  29401. }
  29402. isOccluded( renderContext, object ) {
  29403. const renderContextData = this.get( renderContext );
  29404. return renderContextData.occluded && renderContextData.occluded.has( object );
  29405. }
  29406. async resolveOccludedAsync( renderContext ) {
  29407. const renderContextData = this.get( renderContext );
  29408. // handle occlusion query results
  29409. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  29410. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  29411. const occluded = new WeakSet();
  29412. renderContextData.currentOcclusionQueryObjects = null;
  29413. renderContextData.currentOcclusionQueryBuffer = null;
  29414. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  29415. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  29416. const results = new BigUint64Array( buffer );
  29417. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  29418. if ( results[ i ] !== BigInt( 0 ) ) {
  29419. occluded.add( currentOcclusionQueryObjects[ i ] );
  29420. }
  29421. }
  29422. currentOcclusionQueryBuffer.destroy();
  29423. renderContextData.occluded = occluded;
  29424. }
  29425. }
  29426. updateViewport( renderContext ) {
  29427. const { currentPass } = this.get( renderContext );
  29428. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  29429. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  29430. }
  29431. clear( color, depth, stencil, renderTargetData = null ) {
  29432. const device = this.device;
  29433. const renderer = this.renderer;
  29434. let colorAttachments = [];
  29435. let depthStencilAttachment;
  29436. let clearValue;
  29437. let supportsDepth;
  29438. let supportsStencil;
  29439. if ( color ) {
  29440. const clearColor = this.getClearColor();
  29441. if ( this.renderer.alpha === true ) {
  29442. // premultiply alpha
  29443. const a = clearColor.a;
  29444. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  29445. } else {
  29446. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  29447. }
  29448. }
  29449. if ( renderTargetData === null ) {
  29450. supportsDepth = renderer.depth;
  29451. supportsStencil = renderer.stencil;
  29452. const descriptor = this._getDefaultRenderPassDescriptor();
  29453. if ( color ) {
  29454. colorAttachments = descriptor.colorAttachments;
  29455. const colorAttachment = colorAttachments[ 0 ];
  29456. colorAttachment.clearValue = clearValue;
  29457. colorAttachment.loadOp = GPULoadOp.Clear;
  29458. colorAttachment.storeOp = GPUStoreOp.Store;
  29459. }
  29460. if ( supportsDepth || supportsStencil ) {
  29461. depthStencilAttachment = descriptor.depthStencilAttachment;
  29462. }
  29463. } else {
  29464. supportsDepth = renderTargetData.depth;
  29465. supportsStencil = renderTargetData.stencil;
  29466. if ( color ) {
  29467. for ( const texture of renderTargetData.textures ) {
  29468. const textureData = this.get( texture );
  29469. const textureView = textureData.texture.createView();
  29470. let view, resolveTarget;
  29471. if ( textureData.msaaTexture !== undefined ) {
  29472. view = textureData.msaaTexture.createView();
  29473. resolveTarget = textureView;
  29474. } else {
  29475. view = textureView;
  29476. resolveTarget = undefined;
  29477. }
  29478. colorAttachments.push( {
  29479. view,
  29480. resolveTarget,
  29481. clearValue,
  29482. loadOp: GPULoadOp.Clear,
  29483. storeOp: GPUStoreOp.Store
  29484. } );
  29485. }
  29486. }
  29487. if ( supportsDepth || supportsStencil ) {
  29488. const depthTextureData = this.get( renderTargetData.depthTexture );
  29489. depthStencilAttachment = {
  29490. view: depthTextureData.texture.createView()
  29491. };
  29492. }
  29493. }
  29494. //
  29495. if ( supportsDepth ) {
  29496. if ( depth ) {
  29497. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  29498. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  29499. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  29500. } else {
  29501. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  29502. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  29503. }
  29504. }
  29505. //
  29506. if ( supportsStencil ) {
  29507. if ( stencil ) {
  29508. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  29509. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  29510. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  29511. } else {
  29512. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  29513. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  29514. }
  29515. }
  29516. //
  29517. const encoder = device.createCommandEncoder( {} );
  29518. const currentPass = encoder.beginRenderPass( {
  29519. colorAttachments,
  29520. depthStencilAttachment
  29521. } );
  29522. currentPass.end();
  29523. device.queue.submit( [ encoder.finish() ] );
  29524. }
  29525. // compute
  29526. beginCompute( computeGroup ) {
  29527. const groupGPU = this.get( computeGroup );
  29528. const descriptor = {};
  29529. this.initTimestampQuery( computeGroup, descriptor );
  29530. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  29531. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  29532. }
  29533. compute( computeGroup, computeNode, bindings, pipeline ) {
  29534. const { passEncoderGPU } = this.get( computeGroup );
  29535. // pipeline
  29536. const pipelineGPU = this.get( pipeline ).pipeline;
  29537. passEncoderGPU.setPipeline( pipelineGPU );
  29538. // bind groups
  29539. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  29540. const bindGroup = bindings[ i ];
  29541. const bindingsData = this.get( bindGroup );
  29542. passEncoderGPU.setBindGroup( i, bindingsData.group );
  29543. }
  29544. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  29545. const computeNodeData = this.get( computeNode );
  29546. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  29547. const { dispatchSize } = computeNodeData;
  29548. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  29549. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  29550. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  29551. } else {
  29552. dispatchSize.x = computeNode.dispatchCount;
  29553. }
  29554. passEncoderGPU.dispatchWorkgroups(
  29555. dispatchSize.x,
  29556. dispatchSize.y,
  29557. dispatchSize.z
  29558. );
  29559. }
  29560. finishCompute( computeGroup ) {
  29561. const groupData = this.get( computeGroup );
  29562. groupData.passEncoderGPU.end();
  29563. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  29564. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  29565. }
  29566. async waitForGPU() {
  29567. await this.device.queue.onSubmittedWorkDone();
  29568. }
  29569. // render object
  29570. draw( renderObject, info ) {
  29571. const { object, context, pipeline } = renderObject;
  29572. const bindings = renderObject.getBindings();
  29573. const renderContextData = this.get( context );
  29574. const pipelineGPU = this.get( pipeline ).pipeline;
  29575. const currentSets = renderContextData.currentSets;
  29576. const passEncoderGPU = renderContextData.currentPass;
  29577. const drawParams = renderObject.getDrawParameters();
  29578. if ( drawParams === null ) return;
  29579. // pipeline
  29580. if ( currentSets.pipeline !== pipelineGPU ) {
  29581. passEncoderGPU.setPipeline( pipelineGPU );
  29582. currentSets.pipeline = pipelineGPU;
  29583. }
  29584. // bind groups
  29585. const currentBindingGroups = currentSets.bindingGroups;
  29586. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  29587. const bindGroup = bindings[ i ];
  29588. const bindingsData = this.get( bindGroup );
  29589. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  29590. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  29591. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  29592. }
  29593. }
  29594. // attributes
  29595. const index = renderObject.getIndex();
  29596. const hasIndex = ( index !== null );
  29597. // index
  29598. if ( hasIndex === true ) {
  29599. if ( currentSets.index !== index ) {
  29600. const buffer = this.get( index ).buffer;
  29601. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  29602. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  29603. currentSets.index = index;
  29604. }
  29605. }
  29606. // vertex buffers
  29607. const vertexBuffers = renderObject.getVertexBuffers();
  29608. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  29609. const vertexBuffer = vertexBuffers[ i ];
  29610. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  29611. const buffer = this.get( vertexBuffer ).buffer;
  29612. passEncoderGPU.setVertexBuffer( i, buffer );
  29613. currentSets.attributes[ i ] = vertexBuffer;
  29614. }
  29615. }
  29616. // occlusion queries - handle multiple consecutive draw calls for an object
  29617. if ( renderContextData.occlusionQuerySet !== undefined ) {
  29618. const lastObject = renderContextData.lastOcclusionObject;
  29619. if ( lastObject !== object ) {
  29620. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  29621. passEncoderGPU.endOcclusionQuery();
  29622. renderContextData.occlusionQueryIndex ++;
  29623. }
  29624. if ( object.occlusionTest === true ) {
  29625. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  29626. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  29627. }
  29628. renderContextData.lastOcclusionObject = object;
  29629. }
  29630. }
  29631. // draw
  29632. if ( object.isBatchedMesh === true ) {
  29633. const starts = object._multiDrawStarts;
  29634. const counts = object._multiDrawCounts;
  29635. const drawCount = object._multiDrawCount;
  29636. const drawInstances = object._multiDrawInstances;
  29637. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  29638. for ( let i = 0; i < drawCount; i ++ ) {
  29639. const count = drawInstances ? drawInstances[ i ] : 1;
  29640. const firstInstance = count > 1 ? 0 : i;
  29641. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  29642. }
  29643. } else if ( hasIndex === true ) {
  29644. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  29645. const indirect = renderObject.getIndirect();
  29646. if ( indirect !== null ) {
  29647. const buffer = this.get( indirect ).buffer;
  29648. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  29649. } else {
  29650. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  29651. }
  29652. info.update( object, indexCount, instanceCount );
  29653. } else {
  29654. const { vertexCount, instanceCount, firstVertex } = drawParams;
  29655. const indirect = renderObject.getIndirect();
  29656. if ( indirect !== null ) {
  29657. const buffer = this.get( indirect ).buffer;
  29658. passEncoderGPU.drawIndirect( buffer, 0 );
  29659. } else {
  29660. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  29661. }
  29662. info.update( object, vertexCount, instanceCount );
  29663. }
  29664. }
  29665. // cache key
  29666. needsRenderUpdate( renderObject ) {
  29667. const data = this.get( renderObject );
  29668. const { object, material } = renderObject;
  29669. const utils = this.utils;
  29670. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  29671. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  29672. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  29673. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  29674. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  29675. let needsUpdate = false;
  29676. if ( data.material !== material || data.materialVersion !== material.version ||
  29677. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  29678. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  29679. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  29680. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  29681. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  29682. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  29683. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  29684. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  29685. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  29686. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  29687. data.primitiveTopology !== primitiveTopology ||
  29688. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  29689. ) {
  29690. data.material = material; data.materialVersion = material.version;
  29691. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  29692. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  29693. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  29694. data.colorWrite = material.colorWrite;
  29695. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  29696. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  29697. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  29698. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  29699. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  29700. data.sampleCount = sampleCount;
  29701. data.colorSpace = colorSpace;
  29702. data.colorFormat = colorFormat;
  29703. data.depthStencilFormat = depthStencilFormat;
  29704. data.primitiveTopology = primitiveTopology;
  29705. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  29706. needsUpdate = true;
  29707. }
  29708. return needsUpdate;
  29709. }
  29710. getRenderCacheKey( renderObject ) {
  29711. const { object, material } = renderObject;
  29712. const utils = this.utils;
  29713. const renderContext = renderObject.context;
  29714. return [
  29715. material.transparent, material.blending, material.premultipliedAlpha,
  29716. material.blendSrc, material.blendDst, material.blendEquation,
  29717. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  29718. material.colorWrite,
  29719. material.depthWrite, material.depthTest, material.depthFunc,
  29720. material.stencilWrite, material.stencilFunc,
  29721. material.stencilFail, material.stencilZFail, material.stencilZPass,
  29722. material.stencilFuncMask, material.stencilWriteMask,
  29723. material.side,
  29724. utils.getSampleCountRenderContext( renderContext ),
  29725. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  29726. utils.getPrimitiveTopology( object, material ),
  29727. renderObject.getGeometryCacheKey(),
  29728. renderObject.clippingContextCacheKey
  29729. ].join();
  29730. }
  29731. // textures
  29732. createSampler( texture ) {
  29733. this.textureUtils.createSampler( texture );
  29734. }
  29735. destroySampler( texture ) {
  29736. this.textureUtils.destroySampler( texture );
  29737. }
  29738. createDefaultTexture( texture ) {
  29739. this.textureUtils.createDefaultTexture( texture );
  29740. }
  29741. createTexture( texture, options ) {
  29742. this.textureUtils.createTexture( texture, options );
  29743. }
  29744. updateTexture( texture, options ) {
  29745. this.textureUtils.updateTexture( texture, options );
  29746. }
  29747. generateMipmaps( texture ) {
  29748. this.textureUtils.generateMipmaps( texture );
  29749. }
  29750. destroyTexture( texture ) {
  29751. this.textureUtils.destroyTexture( texture );
  29752. }
  29753. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  29754. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  29755. }
  29756. initTimestampQuery( renderContext, descriptor ) {
  29757. if ( ! this.trackTimestamp ) return;
  29758. const renderContextData = this.get( renderContext );
  29759. if ( ! renderContextData.timeStampQuerySet ) {
  29760. const type = renderContext.isComputeNode ? 'compute' : 'render';
  29761. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  29762. const timestampWrites = {
  29763. querySet: timeStampQuerySet,
  29764. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  29765. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  29766. };
  29767. Object.assign( descriptor, { timestampWrites } );
  29768. renderContextData.timeStampQuerySet = timeStampQuerySet;
  29769. }
  29770. }
  29771. // timestamp utils
  29772. prepareTimestampBuffer( renderContext, encoder ) {
  29773. if ( ! this.trackTimestamp ) return;
  29774. const renderContextData = this.get( renderContext );
  29775. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  29776. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  29777. renderContextData.currentTimestampQueryBuffers = {
  29778. resolveBuffer: this.device.createBuffer( {
  29779. label: 'timestamp resolve buffer',
  29780. size: size,
  29781. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  29782. } ),
  29783. resultBuffer: this.device.createBuffer( {
  29784. label: 'timestamp result buffer',
  29785. size: size,
  29786. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  29787. } )
  29788. };
  29789. }
  29790. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  29791. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  29792. if ( resultBuffer.mapState === 'unmapped' ) {
  29793. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  29794. }
  29795. }
  29796. async resolveTimestampAsync( renderContext, type = 'render' ) {
  29797. if ( ! this.trackTimestamp ) return;
  29798. const renderContextData = this.get( renderContext );
  29799. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  29800. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  29801. if ( resultBuffer.mapState === 'unmapped' ) {
  29802. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  29803. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  29804. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  29805. this.renderer.info.updateTimestamp( type, duration );
  29806. resultBuffer.unmap();
  29807. } );
  29808. }
  29809. }
  29810. // node builder
  29811. createNodeBuilder( object, renderer ) {
  29812. return new WGSLNodeBuilder( object, renderer );
  29813. }
  29814. // program
  29815. createProgram( program ) {
  29816. const programGPU = this.get( program );
  29817. programGPU.module = {
  29818. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  29819. entryPoint: 'main'
  29820. };
  29821. }
  29822. destroyProgram( program ) {
  29823. this.delete( program );
  29824. }
  29825. // pipelines
  29826. createRenderPipeline( renderObject, promises ) {
  29827. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  29828. }
  29829. createComputePipeline( computePipeline, bindings ) {
  29830. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  29831. }
  29832. beginBundle( renderContext ) {
  29833. const renderContextData = this.get( renderContext );
  29834. renderContextData._currentPass = renderContextData.currentPass;
  29835. renderContextData._currentSets = renderContextData.currentSets;
  29836. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  29837. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  29838. }
  29839. finishBundle( renderContext, bundle ) {
  29840. const renderContextData = this.get( renderContext );
  29841. const bundleEncoder = renderContextData.currentPass;
  29842. const bundleGPU = bundleEncoder.finish();
  29843. this.get( bundle ).bundleGPU = bundleGPU;
  29844. // restore render pass state
  29845. renderContextData.currentSets = renderContextData._currentSets;
  29846. renderContextData.currentPass = renderContextData._currentPass;
  29847. }
  29848. addBundle( renderContext, bundle ) {
  29849. const renderContextData = this.get( renderContext );
  29850. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  29851. }
  29852. // bindings
  29853. createBindings( bindGroup, bindings, cacheIndex, version ) {
  29854. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  29855. }
  29856. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  29857. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  29858. }
  29859. updateBinding( binding ) {
  29860. this.bindingUtils.updateBinding( binding );
  29861. }
  29862. // attributes
  29863. createIndexAttribute( attribute ) {
  29864. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  29865. }
  29866. createAttribute( attribute ) {
  29867. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  29868. }
  29869. createStorageAttribute( attribute ) {
  29870. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  29871. }
  29872. createIndirectStorageAttribute( attribute ) {
  29873. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  29874. }
  29875. updateAttribute( attribute ) {
  29876. this.attributeUtils.updateAttribute( attribute );
  29877. }
  29878. destroyAttribute( attribute ) {
  29879. this.attributeUtils.destroyAttribute( attribute );
  29880. }
  29881. // canvas
  29882. updateSize() {
  29883. this.colorBuffer = this.textureUtils.getColorBuffer();
  29884. this.defaultRenderPassdescriptor = null;
  29885. }
  29886. // utils public
  29887. getMaxAnisotropy() {
  29888. return 16;
  29889. }
  29890. hasFeature( name ) {
  29891. return this.device.features.has( name );
  29892. }
  29893. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  29894. let dstX = 0;
  29895. let dstY = 0;
  29896. let dstLayer = 0;
  29897. let srcX = 0;
  29898. let srcY = 0;
  29899. let srcLayer = 0;
  29900. let srcWidth = srcTexture.image.width;
  29901. let srcHeight = srcTexture.image.height;
  29902. if ( srcRegion !== null ) {
  29903. srcX = srcRegion.x;
  29904. srcY = srcRegion.y;
  29905. srcLayer = srcRegion.z || 0;
  29906. srcWidth = srcRegion.width;
  29907. srcHeight = srcRegion.height;
  29908. }
  29909. if ( dstPosition !== null ) {
  29910. dstX = dstPosition.x;
  29911. dstY = dstPosition.y;
  29912. dstLayer = dstPosition.z || 0;
  29913. }
  29914. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  29915. const sourceGPU = this.get( srcTexture ).texture;
  29916. const destinationGPU = this.get( dstTexture ).texture;
  29917. encoder.copyTextureToTexture(
  29918. {
  29919. texture: sourceGPU,
  29920. mipLevel: level,
  29921. origin: { x: srcX, y: srcY, z: srcLayer }
  29922. },
  29923. {
  29924. texture: destinationGPU,
  29925. mipLevel: level,
  29926. origin: { x: dstX, y: dstY, z: dstLayer }
  29927. },
  29928. [
  29929. srcWidth,
  29930. srcHeight,
  29931. 1
  29932. ]
  29933. );
  29934. this.device.queue.submit( [ encoder.finish() ] );
  29935. }
  29936. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  29937. const renderContextData = this.get( renderContext );
  29938. let sourceGPU = null;
  29939. if ( renderContext.renderTarget ) {
  29940. if ( texture.isDepthTexture ) {
  29941. sourceGPU = this.get( renderContext.depthTexture ).texture;
  29942. } else {
  29943. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  29944. }
  29945. } else {
  29946. if ( texture.isDepthTexture ) {
  29947. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  29948. } else {
  29949. sourceGPU = this.context.getCurrentTexture();
  29950. }
  29951. }
  29952. const destinationGPU = this.get( texture ).texture;
  29953. if ( sourceGPU.format !== destinationGPU.format ) {
  29954. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  29955. return;
  29956. }
  29957. let encoder;
  29958. if ( renderContextData.currentPass ) {
  29959. renderContextData.currentPass.end();
  29960. encoder = renderContextData.encoder;
  29961. } else {
  29962. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  29963. }
  29964. encoder.copyTextureToTexture(
  29965. {
  29966. texture: sourceGPU,
  29967. origin: [ rectangle.x, rectangle.y, 0 ],
  29968. },
  29969. {
  29970. texture: destinationGPU
  29971. },
  29972. [
  29973. rectangle.z,
  29974. rectangle.w
  29975. ]
  29976. );
  29977. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  29978. if ( renderContextData.currentPass ) {
  29979. const { descriptor } = renderContextData;
  29980. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  29981. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  29982. }
  29983. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  29984. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  29985. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  29986. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  29987. if ( renderContext.viewport ) {
  29988. this.updateViewport( renderContext );
  29989. }
  29990. if ( renderContext.scissor ) {
  29991. const { x, y, width, height } = renderContext.scissorValue;
  29992. renderContextData.currentPass.setScissorRect( x, y, width, height );
  29993. }
  29994. } else {
  29995. this.device.queue.submit( [ encoder.finish() ] );
  29996. }
  29997. }
  29998. }
  29999. class IESSpotLight extends SpotLight {
  30000. constructor( color, intensity, distance, angle, penumbra, decay ) {
  30001. super( color, intensity, distance, angle, penumbra, decay );
  30002. this.iesMap = null;
  30003. }
  30004. copy( source, recursive ) {
  30005. super.copy( source, recursive );
  30006. this.iesMap = source.iesMap;
  30007. return this;
  30008. }
  30009. }
  30010. class StandardNodeLibrary extends NodeLibrary {
  30011. constructor() {
  30012. super();
  30013. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  30014. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  30015. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  30016. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  30017. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  30018. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  30019. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  30020. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  30021. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  30022. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  30023. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  30024. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  30025. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  30026. this.addLight( PointLightNode, PointLight );
  30027. this.addLight( DirectionalLightNode, DirectionalLight );
  30028. this.addLight( RectAreaLightNode, RectAreaLight );
  30029. this.addLight( SpotLightNode, SpotLight );
  30030. this.addLight( AmbientLightNode, AmbientLight );
  30031. this.addLight( HemisphereLightNode, HemisphereLight );
  30032. this.addLight( LightProbeNode, LightProbe );
  30033. this.addLight( IESSpotLightNode, IESSpotLight );
  30034. this.addToneMapping( linearToneMapping, LinearToneMapping );
  30035. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  30036. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  30037. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  30038. this.addToneMapping( agxToneMapping, AgXToneMapping );
  30039. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  30040. }
  30041. }
  30042. /*
  30043. const debugHandler = {
  30044. get: function ( target, name ) {
  30045. // Add |update
  30046. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  30047. return target[ name ];
  30048. }
  30049. };
  30050. */
  30051. class WebGPURenderer extends Renderer {
  30052. constructor( parameters = {} ) {
  30053. let BackendClass;
  30054. if ( parameters.forceWebGL ) {
  30055. BackendClass = WebGLBackend;
  30056. } else {
  30057. BackendClass = WebGPUBackend;
  30058. parameters.getFallback = () => {
  30059. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  30060. return new WebGLBackend( parameters );
  30061. };
  30062. }
  30063. const backend = new BackendClass( parameters );
  30064. //super( new Proxy( backend, debugHandler ) );
  30065. super( backend, parameters );
  30066. this.library = new StandardNodeLibrary();
  30067. this.isWebGPURenderer = true;
  30068. }
  30069. }
  30070. class BundleGroup extends Group {
  30071. constructor() {
  30072. super();
  30073. this.isBundleGroup = true;
  30074. this.type = 'BundleGroup';
  30075. this.static = true;
  30076. this.version = 0;
  30077. }
  30078. set needsUpdate( value ) {
  30079. if ( value === true ) this.version ++;
  30080. }
  30081. }
  30082. const _material = /*@__PURE__*/ new NodeMaterial();
  30083. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  30084. class PostProcessing {
  30085. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  30086. this.renderer = renderer;
  30087. this.outputNode = outputNode;
  30088. this.outputColorTransform = true;
  30089. this.needsUpdate = true;
  30090. _material.name = 'PostProcessing';
  30091. }
  30092. render() {
  30093. this.update();
  30094. const renderer = this.renderer;
  30095. const toneMapping = renderer.toneMapping;
  30096. const outputColorSpace = renderer.outputColorSpace;
  30097. renderer.toneMapping = NoToneMapping;
  30098. renderer.outputColorSpace = LinearSRGBColorSpace;
  30099. //
  30100. _quadMesh.render( renderer );
  30101. //
  30102. renderer.toneMapping = toneMapping;
  30103. renderer.outputColorSpace = outputColorSpace;
  30104. }
  30105. update() {
  30106. if ( this.needsUpdate === true ) {
  30107. const renderer = this.renderer;
  30108. const toneMapping = renderer.toneMapping;
  30109. const outputColorSpace = renderer.outputColorSpace;
  30110. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  30111. _quadMesh.material.needsUpdate = true;
  30112. this.needsUpdate = false;
  30113. }
  30114. }
  30115. async renderAsync() {
  30116. this.update();
  30117. const renderer = this.renderer;
  30118. const toneMapping = renderer.toneMapping;
  30119. const outputColorSpace = renderer.outputColorSpace;
  30120. renderer.toneMapping = NoToneMapping;
  30121. renderer.outputColorSpace = LinearSRGBColorSpace;
  30122. //
  30123. await _quadMesh.renderAsync( renderer );
  30124. //
  30125. renderer.toneMapping = toneMapping;
  30126. renderer.outputColorSpace = outputColorSpace;
  30127. }
  30128. }
  30129. // renderer state
  30130. function saveRendererState( renderer, state = {} ) {
  30131. state.toneMapping = renderer.toneMapping;
  30132. state.toneMappingExposure = renderer.toneMappingExposure;
  30133. state.outputColorSpace = renderer.outputColorSpace;
  30134. state.renderTarget = renderer.getRenderTarget();
  30135. state.activeCubeFace = renderer.getActiveCubeFace();
  30136. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30137. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30138. state.pixelRatio = renderer.getPixelRatio();
  30139. state.mrt = renderer.getMRT();
  30140. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30141. state.clearAlpha = renderer.getClearAlpha();
  30142. state.autoClear = renderer.autoClear;
  30143. state.scissorTest = renderer.getScissorTest();
  30144. return state;
  30145. }
  30146. function resetRendererState( renderer, state ) {
  30147. state = saveRendererState( renderer, state );
  30148. renderer.setMRT( null );
  30149. renderer.setRenderObjectFunction( null );
  30150. renderer.setClearColor( 0x000000, 1 );
  30151. renderer.autoClear = true;
  30152. return state;
  30153. }
  30154. function restoreRendererState( renderer, state ) {
  30155. renderer.toneMapping = state.toneMapping;
  30156. renderer.toneMappingExposure = state.toneMappingExposure;
  30157. renderer.outputColorSpace = state.outputColorSpace;
  30158. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30159. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30160. renderer.setPixelRatio( state.pixelRatio );
  30161. renderer.setMRT( state.mrt );
  30162. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30163. renderer.autoClear = state.autoClear;
  30164. renderer.setScissorTest( state.scissorTest );
  30165. }
  30166. // renderer and scene state
  30167. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30168. state = saveRendererState( renderer, state );
  30169. state.background = scene.background;
  30170. state.backgroundNode = scene.backgroundNode;
  30171. state.overrideMaterial = scene.overrideMaterial;
  30172. return state;
  30173. }
  30174. function resetRendererAndSceneState( renderer, scene, state ) {
  30175. state = saveRendererAndSceneState( renderer, scene, state );
  30176. scene.background = null;
  30177. scene.backgroundNode = null;
  30178. scene.overrideMaterial = null;
  30179. return state;
  30180. }
  30181. function restoreRendererAndSceneState( renderer, scene, state ) {
  30182. restoreRendererState( renderer, state );
  30183. scene.background = state.background;
  30184. scene.backgroundNode = state.backgroundNode;
  30185. scene.overrideMaterial = state.overrideMaterial;
  30186. }
  30187. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  30188. __proto__: null,
  30189. resetRendererAndSceneState: resetRendererAndSceneState,
  30190. resetRendererState: resetRendererState,
  30191. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30192. restoreRendererState: restoreRendererState,
  30193. saveRendererAndSceneState: saveRendererAndSceneState,
  30194. saveRendererState: saveRendererState
  30195. });
  30196. class StorageTexture extends Texture {
  30197. constructor( width = 1, height = 1 ) {
  30198. super();
  30199. this.image = { width, height };
  30200. this.magFilter = LinearFilter;
  30201. this.minFilter = LinearFilter;
  30202. this.isStorageTexture = true;
  30203. }
  30204. }
  30205. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  30206. constructor( array, itemSize ) {
  30207. super( array, itemSize, Uint32Array );
  30208. this.isIndirectStorageBufferAttribute = true;
  30209. }
  30210. }
  30211. class NodeLoader extends Loader {
  30212. constructor( manager ) {
  30213. super( manager );
  30214. this.textures = {};
  30215. this.nodes = {};
  30216. }
  30217. load( url, onLoad, onProgress, onError ) {
  30218. const loader = new FileLoader( this.manager );
  30219. loader.setPath( this.path );
  30220. loader.setRequestHeader( this.requestHeader );
  30221. loader.setWithCredentials( this.withCredentials );
  30222. loader.load( url, ( text ) => {
  30223. try {
  30224. onLoad( this.parse( JSON.parse( text ) ) );
  30225. } catch ( e ) {
  30226. if ( onError ) {
  30227. onError( e );
  30228. } else {
  30229. console.error( e );
  30230. }
  30231. this.manager.itemError( url );
  30232. }
  30233. }, onProgress, onError );
  30234. }
  30235. parseNodes( json ) {
  30236. const nodes = {};
  30237. if ( json !== undefined ) {
  30238. for ( const nodeJSON of json ) {
  30239. const { uuid, type } = nodeJSON;
  30240. nodes[ uuid ] = this.createNodeFromType( type );
  30241. nodes[ uuid ].uuid = uuid;
  30242. }
  30243. const meta = { nodes, textures: this.textures };
  30244. for ( const nodeJSON of json ) {
  30245. nodeJSON.meta = meta;
  30246. const node = nodes[ nodeJSON.uuid ];
  30247. node.deserialize( nodeJSON );
  30248. delete nodeJSON.meta;
  30249. }
  30250. }
  30251. return nodes;
  30252. }
  30253. parse( json ) {
  30254. const node = this.createNodeFromType( json.type );
  30255. node.uuid = json.uuid;
  30256. const nodes = this.parseNodes( json.nodes );
  30257. const meta = { nodes, textures: this.textures };
  30258. json.meta = meta;
  30259. node.deserialize( json );
  30260. delete json.meta;
  30261. return node;
  30262. }
  30263. setTextures( value ) {
  30264. this.textures = value;
  30265. return this;
  30266. }
  30267. setNodes( value ) {
  30268. this.nodes = value;
  30269. return this;
  30270. }
  30271. createNodeFromType( type ) {
  30272. if ( this.nodes[ type ] === undefined ) {
  30273. console.error( 'THREE.NodeLoader: Node type not found:', type );
  30274. return float();
  30275. }
  30276. return nodeObject( new this.nodes[ type ]() );
  30277. }
  30278. }
  30279. class NodeMaterialLoader extends MaterialLoader {
  30280. constructor( manager ) {
  30281. super( manager );
  30282. this.nodes = {};
  30283. this.nodeMaterials = {};
  30284. }
  30285. parse( json ) {
  30286. const material = super.parse( json );
  30287. const nodes = this.nodes;
  30288. const inputNodes = json.inputNodes;
  30289. for ( const property in inputNodes ) {
  30290. const uuid = inputNodes[ property ];
  30291. material[ property ] = nodes[ uuid ];
  30292. }
  30293. return material;
  30294. }
  30295. setNodes( value ) {
  30296. this.nodes = value;
  30297. return this;
  30298. }
  30299. setNodeMaterials( value ) {
  30300. this.nodeMaterials = value;
  30301. return this;
  30302. }
  30303. createMaterialFromType( type ) {
  30304. const materialClass = this.nodeMaterials[ type ];
  30305. if ( materialClass !== undefined ) {
  30306. return new materialClass();
  30307. }
  30308. return super.createMaterialFromType( type );
  30309. }
  30310. }
  30311. class NodeObjectLoader extends ObjectLoader {
  30312. constructor( manager ) {
  30313. super( manager );
  30314. this.nodes = {};
  30315. this.nodeMaterials = {};
  30316. this._nodesJSON = null;
  30317. }
  30318. setNodes( value ) {
  30319. this.nodes = value;
  30320. return this;
  30321. }
  30322. setNodeMaterials( value ) {
  30323. this.nodeMaterials = value;
  30324. return this;
  30325. }
  30326. parse( json, onLoad ) {
  30327. this._nodesJSON = json.nodes;
  30328. const data = super.parse( json, onLoad );
  30329. this._nodesJSON = null; // dispose
  30330. return data;
  30331. }
  30332. parseNodes( json, textures ) {
  30333. if ( json !== undefined ) {
  30334. const loader = new NodeLoader();
  30335. loader.setNodes( this.nodes );
  30336. loader.setTextures( textures );
  30337. return loader.parseNodes( json );
  30338. }
  30339. return {};
  30340. }
  30341. parseMaterials( json, textures ) {
  30342. const materials = {};
  30343. if ( json !== undefined ) {
  30344. const nodes = this.parseNodes( this._nodesJSON, textures );
  30345. const loader = new NodeMaterialLoader();
  30346. loader.setTextures( textures );
  30347. loader.setNodes( nodes );
  30348. loader.setNodeMaterials( this.nodeMaterials );
  30349. for ( let i = 0, l = json.length; i < l; i ++ ) {
  30350. const data = json[ i ];
  30351. materials[ data.uuid ] = loader.parse( data );
  30352. }
  30353. }
  30354. return materials;
  30355. }
  30356. }
  30357. class ClippingGroup extends Group {
  30358. constructor() {
  30359. super();
  30360. this.isClippingGroup = true;
  30361. this.clippingPlanes = [];
  30362. this.enabled = true;
  30363. this.clipIntersection = false;
  30364. this.clipShadows = false;
  30365. }
  30366. }
  30367. 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, ShadowBaseNode, 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号